[英]How to end this program when user inputs “end”?
So basically I am trying to figure out how to stop this program using Integer.valueOf(String s)
or Integer.parseInt(String s)
by typing "end" for the user input所以基本上我试图通过为用户输入键入“end”来弄清楚如何使用
Integer.valueOf(String s)
或Integer.parseInt(String s)
来停止这个程序
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);
}
}
First - you need to change lol=sc.nextInt()
to String tmp = s.nextLine()
首先-您需要将
lol=sc.nextInt()
更改为String tmp = s.nextLine()
Second - do第二——做
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.
}
you should learn how to use try/catch.你应该学习如何使用 try/catch。 Here we go:
这里我们 go:
String text = "";
int lol = 1;
do {
System.out.print("Enter a number: ");
text = s.nextLine();
try {
lol = Integer.valueOf(text);
}catch (Exception e){
System.out.println("Exit");
System.exit(0);
}
Here is your code这是你的代码
package Phone;
import java.util.Scanner;
public class monkey1{
public static void main(String[] args){
Scanner s = new Scanner(System.in);
int sum = 0;
int hi = 1;
do {
System.out.print("Enter a number: ");
String lol = s.nextLine();
if(lol.equals("end")) {
break;
}
hi = Integer.parseInt(lol);
sum += hi;
if (hi > 0) {
System.out.println("Sum is now: " + sum);
}
} while (hi > 0);
}
What I did here is I changed lol to hi for adding and took String input so that you can input end...我在这里所做的是我将 lol 更改为 hi 以添加并接受 String 输入,以便您可以输入 end ...
I would suggest checking if s.equals("end") before converting to int so something like this:我建议在转换为 int 之前检查 if s.equals("end") ,如下所示:
do {
System.out.print("Enter a number: ");
String userValue = s.nextLine();
if(userValue.equals("end")
break;
lol = Integer.parseInt(userValue);
sum += lol;
if (lol > 0){
System.out.println("Sum is now: " + sum);
}
}while (lol>0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.