[英]How to check if the input given by the user is Y or N
总结一下,就如何解决它给了我任何想法或解决方案。
我尝试了以下代码中给出的内容。
System.out.print("Want to continue Shopping or end your shopping spree and want the bill for your shopping (answer in Y or N)");
String end = sc.next();
if(end =="Y")
System.out.println("hello");
我期望上面代码中的输出hello,但是实际结果与程序刚结束无关。
首先,我不知道您的问题到底是什么。 我看不到有关正在使用哪种编程语言(我想是Java)或正在使用哪种操作系统的任何信息。
但是我已经知道问题可能出在哪里:在您使用stdout时,我认为程序发生在控制台或终端上。 在某些环境中,该程序终止后,cmd窗口将关闭(使用诸如VS Community这样的IDE时,在没有上下文的情况下我不知道是否这样做)。 在这种情况下,将打印“ hello”,但您不会看到它,因为窗口会立即关闭。 尝试在末尾添加某种getline,然后重试。
假设sc
是Scanner
对象。
字符串比较必须使用equal
方法而不是使用==
来完成,因为这样做将比较内存中对象的引用,而不是String内容,请尝试以下操作:
System.out.print("Want to continue Shopping or end your shopping spree and want the bill for your shopping (answer in Y or N)");
String end = sc.next();
if(end.equals("Y")) {
System.out.println("hello");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.