java - 为什么终端不提示此 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()
没有显示提示,而是代码只在终端结束,必须再次手动运行程序才能播放。我是初学者,所以我很难理解。
解决方案
这将起作用:
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);
}
}
}
推荐阅读
- gradle - 如何更改项目版本的默认策略?
- swift - 无法推断通用参数“T” - 可编码
- symfony - 将全局变量从页面内联脚本传递到 Symfony webpack encore
- javascript - 这是来自 chart.js 的自定义问题
- javascript - TypeError:db.getCollection 不是函数
- python - 如何在 google colab notebook 上的“!pip install tree”之后使“!tree”工作?
- php - 从其他数组分解数组
- python - 在python中使用bs4从一组url中获取律师详细信息
- .net-core - 如何修复:将令牌作为参数传递时,angular7 中的“RangeError:超出最大调用堆栈大小”
- css - 当我使用radial-gradient(circle at)时,为什么具有不透明度的边框会在圆内形成一个正方形?