如何再次接收用户输入数据

img

代码5和7的位置内容与2相同即可

重新调用前面创建的Scanner对象reader的nextInt()方法即可
代码1处创建Scanner对象Scanner reader = new Scanner(System.in);
,下面要重复读取时使用yourGuess = reader.nextInt();进行读取
有帮助望采纳~

运行结果:

img

public class test01 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in); //创建对象
        Random random = new Random();
        System.out.println("分配随机一个1-100的整数,猜数!");
        int realNumber = random.nextInt(100)+1;
        int yourGuess = 0;
        System.out.println("猜测的数:");
        yourGuess = sc.nextInt(); //赋值

        while (yourGuess != realNumber){
            if (yourGuess>realNumber){
                System.out.println("猜大了,重新输入:");
                yourGuess = sc.nextInt(); //重新赋值
            }else if(yourGuess<realNumber){
                System.out.println("猜小了,重新输入:");
                yourGuess = sc.nextInt(); //重新赋值
            }
        }
        System.out.println("猜对了!");
    }
}

Scanner input = new Scanner(System.in);
while(条件){
  int a = input.nextInt();
}

1.Scanner reader = new Scanner(System.in);
2. int yourGuess = reader.nextInt();
3. yourGuess!=realNumber
4.yourGuess > realNumber
5.yourGuess = reader.nextInt();
6.yourGuess < realNumber
7.yourGuess = reader.nextInt();