java - 当用户输入“结束”时如何结束这个程序?
问题描述
所以基本上我想弄清楚如何使用Integer.valueOf(String s)
或Integer.parseInt(String s)
为用户输入键入“end”来停止这个程序
import java.util.Scanner;
public class monkey1{
public static void main(String[] args){
Scanner s = new Scanner(System.in);
int sum = 0;
int lol = 1;
do {
System.out.print("Enter a number: ");
lol = s.nextInt();
sum += lol;
if (lol > 0) {
System.out.println("Sum is now: " + sum);
}
} while (lol>0);
}
}
解决方案
首先-您需要更改lol=sc.nextInt()
为String tmp = s.nextLine()
第二——做
try {
if (tmp.equals("END")) {
break; // This will exit do-while loop
}
lol = Integer.parseInt(tmp);
} catch (NumberFormatException e) {
e.printStackTrace();
// Here you can also exit loop by adding break. Or just ask user to enter new text.
}
推荐阅读
- javascript - Jquery将类添加到不同按钮上的div
- javascript - Javascript 控制台在折叠和展开时显示不同的值,并且与引用时不同
- python - 找不到 panda.tslib 模块
- c# - 如何使用 HTTP get 方法从数据库中请求数据?
- python - 即使我将目录下载到 nltk.data.path 的路径列表中,NLTK 也找不到路径
- python - 通过opencv Python检测图像中是否有灰色
- reactjs - React route,在 CoreUI 上使用具有不同 props/parameters 的相同组件
- laravel - Laravel:如何从数据库中设置复选框的值
- arrays - 在 Go 中,如何解组包含结构数组的字符串
- teradata - Teradata - 如何避免发生多次重新分配