我想尝试一些可以连续读取用户输入的小编程,除非输入是0
。
但问题是,无论我输入什么(0
除外),它总是显示“请选择一个”(在 默认
部分)。如果我输入 4
,它会向我显示该短语两次!
我不明白为什么。 for
和 switch
之间有冲突吗?
这里是代码:
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println("Choose one: ");
char ch = (char)System.in.read();
while (ch!= '0') {
switch(ch) {
case '1':
System.out.println("The If");
break;
case '2':
System.out.println("The Case");
break;
default:
System.out.println("Please choose one");
}
ch = (char)System.in.read();
}
最佳答案
问题是char ch = (char)System.in.read();
。 Java 不能很好地支持基于字符的输入,我建议使用扫描仪来修复您的输出,但是用户现在必须在每次输入后按回车键。
import java.io.IOException;
import java.util.Scanner;
public class Switch
{
public static void main(String[] args) throws IOException
{
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println("Choose one: ");
Scanner in = new Scanner(System.in);
String s = in.nextLine();
while (!s.equals("0"))
{
switch(s)
{
case "1":
System.out.println("The If");
break;
case "2":
System.out.println("The Case");
break;
default:
System.out.println("Please choose one");
}
s = in.nextLine();
}
}
}
如果你不想按回车键,你也可以读取该字符两次,尽管我只能推测为什么会这样,因为有一个控制字符通过流发送。编辑:我认为它也可能是 UTF-16 字符的另一个字节,在输入 ASCII 字符时不使用该字节,但 System.in.read() 返回整数而不是字节。
import java.io.IOException;
public class Switch
{
public static void main(String[] args) throws IOException
{
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println("Choose one: ");
char ch = (char)System.in.read();
while (ch!= '0')
{
switch(ch)
{
case '1':
System.out.println("The If");
break;
case '2':
System.out.println("The Case");
break;
default:
System.out.println("Please choose one");
}
ch = (char)System.in.read();
ch = (char)System.in.read();
}
}
}
关于java - 'for' 和 'switch' 之间有冲突吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29299066/