如何控制用户输入的内容?

时间:2017-02-17 23:26:42

标签: java if-statement methods operators

我是一名java初学者,我正在阅读第一本Java书籍。 我确实管理了本书所要求的内容,但我正在努力改进该计划

该程序应该生成0-7之间的随机数,然后将它放在一个带有以下两个数字的数组中,用户必须猜测它。 一切正常,除了我试图限制用户输入除0到7之外的任何数据

这是我的尝试,我不知道它为什么不起作用:

public String  checkYourSelf (String stringGuess){
    String result = "miss"; //this will be returned if the guess doesn't match
    if (stringGuess != "0" ||
        stringGuess != "1" ||
        stringGuess != "2" ||
        stringGuess != "3" ||
        stringGuess != "4" ||
        stringGuess != "5" ||
        stringGuess != "6" ||
        stringGuess != "7" ){
            System.out.println("Please Enter a correct number");
            result = "error";
            return result;
        } 

之后我使用parseInt方法

int guess = Integer.parseInt(stringGuess);

整个方法:

    public String  checkYourSelf (String stringGuess){
    String result = "miss"; // this will be returned if the guess doesn't match
    if (stringGuess != "0" ||
        stringGuess != "1" ||
        stringGuess != "2" ||
        stringGuess != "3" ||
        stringGuess != "4" ||
        stringGuess != "5" ||
        stringGuess != "6" ||
        stringGuess != "7" ){
            System.out.println("Please Enter a correct number");
            result = "error";
            return result;
        } 
    int guess = Integer.parseInt(stringGuess);

    for (int cell : cellsLocations) {
        if (enterdNums.contains(guess)){
            result = "error";
            System.out.println ("You've entered this number already.");
            System.out.println("Please try again");
            break;
        }
        if (cell == guess) {
            result = "hit";
            hits++;      
            break;
        }
    }
    if (hits == cellsLocations.length) {
        result = "kill"; 
    }
    if (result != "error"){ 
        System.out.println(result);
    }
    enterdNums.add(guess); // add to the list so it doesnt
    return result;   
}
    }

主要方法:

while (isAlive) {
        guess = input.getUserInput("Enter a number");
        result = dot.checkYourSelf(guess);
        if (result == "error"){
            continue;
            } 
        numOfGuesses++;

        if (result == "kill"){
            System.out.println(numOfGuesses);
            isAlive = false;
            break;
        } 
    }

我知道可能有其他方法可以做到这一点,但我试图用我已经知道的东西来做这件事,而且逻辑上这应该是有效的,但是如果我输入任何数字它会说"请输入正确的号码"

感谢

3 个答案:

答案 0 :(得分:0)

关于您遇到的问题: 您永远不会使用!=来比较字符串,因为String是一个Object,而不是原始的。请改用字符串“equals()”。

一条建议: 因为你只测试某些字符,你可以使用非常简单的正则表达式,它比你的构造更简单,更容易理解:

String regex = "^[0-7]{1}$";

,其中 [0-7] - 允许字符和 {1} - 字符串长度

在你的情况下,你把:​​

if (!stringGuess.matches(regex))

答案 1 :(得分:0)

使用while循环。它简单易实现

foreach ($_POST['test'] as $test) {
    var_dump($test);
}

循环将迭代,直到用户输入介于0-7之间的数字

答案 2 :(得分:-1)

您需要使用方法equalsIgnoreCase,即:

if (!stringGuess.equalsIgnoreCase("0"))

等等