[英]JAVA jumps into default at switch-case
This is a code from a Decision Support System I'm trying to make. 这是我尝试制作的决策支持系统中的代码。 Bascially the question is whether you want breakfast or not. 基本上,问题是您是否要吃早餐。 StdIn.readChar()
is used to read a char you insert in the console. StdIn.readChar()
用于读取您在控制台中插入的字符。 I am 100% sure it's correct. 我100%确信它是正确的。
Obiously there is a main method missing, I believe it is clear to understand without it, but if you need it I can paste it in later. 显然,这里缺少一个主要方法,我相信没有它很容易理解,但是如果您需要它,我可以在以后粘贴。
Now my Question: 现在我的问题:
If I run this programm I am asked in the main whether I am hungry or not. 如果我运行此程序,则会在主要询问我是否饿了。 So I type j (in german 'ja' is 'yes') and the programm jumps into the Breakfast method. 所以我输入j(德语中的“ ja”是“ yes”),程序跳入Breakfast方法。 But then I am asked if I want breakfast but there is no time to insert a char. 但是随后我被问到是否要早餐,但没有时间插入一个字符。 It directly jumps into the Default method. 它直接跳到Default方法。 I have used the print command to see on wich point, as you can see. 如您所见,我已经使用print命令在最中间点看到了。 Did I do something wrong with the switch-case selection? 开关盒选择是否做错了?
My console says this: 我的控制台说:
Are you hungry?
(I typed) j
Do you want breakfast?
2 (this is due to the testing println command)
This insert is invalid
Do you want breakfast?
And the strange point is, at this moment I am able to write my answer. 奇怪的是,此刻我能够写出答案。 I have the same problem at the question "Do you like it to be warm?", but of course I can never answer because I need to answer the first question (Do you want breakfast) again. 我在“您喜欢温暖吗?”这个问题上也遇到了同样的问题,但是我当然无法回答,因为我需要再次回答第一个问题(您想吃早餐)。
Can you help me? 你能帮助我吗? Do I need to delete the do-while-loop? 我是否需要删除do-while循环? Am I doing so wrong I need to delete everything? 我做错了吗,我需要删除所有内容? :D :d
public static void Breakfast(){
int a = 0;
do {
System.out.println("Do you want Breakfast?");
char y = StdIn.readChar(); //read Char from console
switch (y) {
case 'j':
System.out.println("Do you like it to be warm?");
y=StdIn.readChar();
switch (y) {
case 'j':
System.out.println("Eggs with Bacon");
break;
case 'n':
System.out.println("Cereal");
break;
default:
System.out.println("1");
a=Default();
}
break;
case 'n':
Mittagessen();
break;
default:
System.out.println("2");
a=Default();
}
} while (a!=0);
}
public static int Default (){
System.out.println("This insert is invalid");
return 1;
}
Pressing enter actually gives two characters: Does Windows carriage return \\r\\n consist of two characters or one character? 按Enter实际上会给出两个字符: Windows回车符\\ r \\ n是由两个字符还是一个字符组成?
So, in your case you have first read the J character and on your second question you had already fed in the second character coming from pressing the Enter button. 因此,在您的情况下,您首先阅读了J字符,而在第二个问题上,您已经输入了按下Enter按钮后的第二个字符。
I hope this helps! 我希望这有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.