簡體   English   中英

在Java中使用字符串打破循環

[英]using string to break out of loop in java

如果用戶在掃描儀中輸入“ STOP”,我只是想打破while true循環。 目前,我的掃描儀只接受整數,我相信這就是問題所在。 如果我嘗試鍵入“ STOP”,則會收到很多錯誤,提示“線程主線程中的異常”。 這是我的代碼片段:

public class algorithm {
private Scanner input = new Scanner(System.in);
int n;

while (true){
    System.out.println("Eneter a number to check if it is odd or even, then hit enter: ");
    System.out.println("Type 'STOP' to end the program");
    n = input.nextInt();

    String strN = String.valueOf(n); //convert integer to string
    if (new String(strN).equals("STOP")){ //if string is STOP, breaks
        System.out.println("Thanks for using my program");
        break;
    }

    if (n % 2 == 0){
        System.out.println(n+" is even");
        continue;
    }
    else{
        System.out.println(n+" is odd");
        continue;

我知道我缺少一些右花括號,但請放心,它們都在我的實際代碼中。 謝謝。

這是我得到的錯誤: Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:864) at java.util.Scanner.next(Scanner.java:1485) at java.util.Scanner.nextInt(Scanner.java:2117) at java.util.Scanner.nextInt(Scanner.java:2076) at OddOrEven.algorithm.checker(algorithm.java:13) at OddOrEven.main.main(main.java:7)

您已經自己確定了問題-掃描儀僅讀取整數:

int n;
...
n = input.nextInt();

因此變量n (一個int)不可能包含字符串“ STOP”(無論何時您調用nextInt()時,掃描程序都會拋出異常,但是它遇到一個字符串,例如“ STOP”,因此無法轉換為int)。

為此,您需要從輸入中讀取字符串(可能使用Scanner.nextLine() ),檢查它們是否為“ STOP”,如果不是,則僅使用以下方法嘗試將它們轉換為int:

int n = Integer.parseInt(mystring)

要處理垃圾輸入(既不是STOP也不是整數),請將parseInt行包裝在try-catch塊中,以便您可以通過捕獲Exception來檢測輸入何時為垃圾

try {
  int i = Integer.parseInt(mystring);
  // do something with the int
}
catch (NumberFormatException e) {
  // display warning message to the user instead
}

另請參閱此相關問題

如下所示,應該可以解決。

注意:還沒有測試過編譯錯誤,就把它寫出來了(但是你有一個要點)

     public Scanner input = new Scanner(System.in);
    int n;

while (true){
    System.out.println("Eneter a number to check if it is odd or even, then hit enter: ");
    System.out.println("Type 'STOP' to end the program");
    n = input.next();
    Integer input;

   // String strN = String.valueOf(n); //convert integer to string
    if (strN.equals("STOP")){ //if string is STOP, breaks
        System.out.println("Thanks for using my program");
        break;
    }
    else{
        try{
    input=  Integer.parseInt(strN);

        }
        catch(Exception e)
        {
            System.out.println("Please enter a  number");
        }
    }

    if (input % 2 == 0){
        System.out.println(n+" is even");
        continue;
    }
    else{
        System.out.println(n+" is odd");
        continue;
    }

最簡單的方法可能是使用input.next()而不是input.nextInt()。 使用input.next()會將輸入作為字符串讀取,然后您可以檢查輸入是否等於“ QUIT”,如果不是,則可以使用Integer.parseInt從讀取的字符串中解析Integer

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM