首页 > 解决方案 > 为什么终端不提示此 JAVA 代码的另一个输入?

问题描述

class test {
 public static void main(String args[])
  throws java.io.IOException {

    char ch, answer = 'K';

    System.out.println("I'm thinking of a letter between A and Z.");
    System.out.print("Can you guess it: ");

    ch = (char) System.in.read();

    if(ch == answer) {
     System.out.println(" *** YOU ARE RIGHT *** ");   
       else System.out.println("Please try again: ");
        ch = (char) System.in.read();        
   }
  }

}

我正在使用命令行来运行这个java程序,我希望用户能够连续输入一些东西,而不是每次猜错时都必须手动运行程序。尝试了很多方法,但第二种方法System.in.read()没有显示提示,而是代码只在终端结束,必须再次手动运行程序才能播放。我是初学者,所以我很难理解。

标签: java

解决方案


这将起作用:

import java.util.Scanner;
class test {
    public static void main(String args[]) throws java.io.IOException {
            char ch, answer = 'K';
            Scanner s = new Scanner(System.in);
            System.out.println("I'm thinking of a letter between A and Z.");
            System.out.print("Can you guess it: ");
            ch = s.next().charAt(0);
            if(ch == answer){
                    System.out.println(" *** YOU ARE RIGHT *** ");
            } else{
                    System.out.println("Please try again: ");
                    ch = s.next().charAt(0);
            }
    }
}

推荐阅读