该代码在某些情况下起作用,但根据输入的顺序给出不同的输出
预期输出应为:
Download
String: Welcome to HackerRank's Java tutorials!
Double: 3.1415
Int: 42
我的代码根据我首先提出的输入提供了不同的输出。 如果可能的话,请解释我出错的地方。 先感谢您。
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int count = 1;
String typeCase = "";
while (count<4) {
if (!sc.hasNext("[0-9]+[\\.]?[0-9]*") || sc.hasNext(":ascii:")) {
typeCase = "String:";
count++;
} else if (sc.hasNextInt()) {
typeCase = "Int:";
count++;
} else if (sc.hasNextDouble()) {
typeCase = "Double:";
count++;
}
switch (typeCase) {
case "String:":
typeCase = "String: ";
System.out.println(typeCase + sc.nextLine());
break;
case "Int:":
typeCase = "Int: ";
System.out.println(typeCase + sc.nextInt());
break;
case "Double:":
typeCase = "Double: ";
System.out.println(typeCase + sc.nextDouble());
break;
}
}
}
Expected Output should be as such:
Download
String: Welcome to HackerRank's Java tutorials!
Double: 3.1415
Int: 42
My code gives different outputs based on what input I put in at first.
If possible please explain where I went wrong.
Thank you in advance.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int count = 1;
String typeCase = "";
while (count<4) {
if (!sc.hasNext("[0-9]+[\\.]?[0-9]*") || sc.hasNext(":ascii:")) {
typeCase = "String:";
count++;
} else if (sc.hasNextInt()) {
typeCase = "Int:";
count++;
} else if (sc.hasNextDouble()) {
typeCase = "Double:";
count++;
}
switch (typeCase) {
case "String:":
typeCase = "String: ";
System.out.println(typeCase + sc.nextLine());
break;
case "Int:":
typeCase = "Int: ";
System.out.println(typeCase + sc.nextInt());
break;
case "Double:":
typeCase = "Double: ";
System.out.println(typeCase + sc.nextDouble());
break;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为,如果您确定整数和双输入将在自己的行中存在(如果不是,您将在重组您的代码重组以实现诸如此类案例)方面,请从此解决方案中获得提示出色地)。在每个sc.nextint()和sc.nextdouble()之后使用sc.nextline(),因为这些方法不会读取newline字符。
编辑:编辑答案,因为您似乎想将输出以字符串,double和int打印。您可以从扫描仪中暂时存储该值,并以后以您想要的任何顺序打印。
请注意,我现在删除了开关案
I think changing your switch case block as below should solve your problem if you are sure that integers and double inputs will be present in their own line(if not, you will get the hint from this solution on restructuring your code to achieve such cases as well). Use sc.nextLine() after each sc.nextInt() and sc.nextDouble() because these methods will not read the newline character.
Edit: Editing the answer since you seem to want to print the output in the order as String,double and int. You can temporarily store the value from the scanner and print it later in whichever order you want.
Please note that I have now removed the switch case