首页 > 解决方案 > 当用户输入“结束”时如何结束这个程序?

问题描述

所以基本上我想弄清楚如何使用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);
    }
}

标签: javaif-statementwhile-loop

解决方案


首先-您需要更改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.
}


推荐阅读