簡體   English   中英

Java代碼突然停止

[英]Java code suddenly stop

我遇到了一個問題。我是Java的新手,我從今天開始:D)..我之前已經編程過,所以我有點了解,但是我是Java的新手。 這是我的代碼:

public class Tutorial {

public static void main(String[] args) {
    double num1,num2;
    String operacia;
    Scanner in=new Scanner (System.in);
    System.out.println("Write 2 numbers");
    num1=in.nextDouble();
    num2=in.nextDouble();
    System.out.println("Choose the operation");
    operacia=in.nextLine();
    if (operacia.equals("+")){
        System.out.println("Your result is "+(num1+num2))   ;
    }
    else if (operacia.equals("-")){
        System.out.println("Your result is  "+(num1-num2))  ;
    }
    else if (operacia.equals("/")){
        System.out.println("Your result is  "+(num1/num2))  ;
    }
    else if (operacia.equals("*")){
        System.out.println("Your result is  "+(num1*num2))  ;
    }




}
}` 

它需要我輸入2個數字,我寫了它們,並且寫了“選擇操作”及其結束。不再輸入。非常感謝:)

您的問題很簡單。

只需將代碼替換為next()而不是nextLine()。有效地,您的代碼正在返回的行是空白行。 因此,當它到達條件語句時,它具有一個空字符串並終止。

next()
Finds and returns the next complete token from this scanner.

nextLine()
Advances this scanner past the current line and returns the input that was skipped.

您的代碼應通過簡單的更改來修復。

public static void main(String[] args) {
    double num1,num2;
    String operacia;

    Scanner in=new Scanner (System.in);
    System.out.println("Write 2 numbers");

    num1=in.nextDouble();
    num2=in.nextDouble();

    System.out.println("Choose the operation");
    operacia=in.next();

    if (operacia.equals("+")){
        System.out.println("Your result is "+(num1+num2))   ;
    }
    else if (operacia.equals("-")){
        System.out.println("Your result is  "+(num1-num2))  ;
    }
    else if (operacia.equals("/")){
        System.out.println("Your result is  "+(num1/num2))  ;
    }
    else if (operacia.equals("*")){
        System.out.println("Your result is  "+(num1*num2))  ;
    }
}

Scanner#nextDouble()僅使用下一個令牌作為輸入的double。 輸入兩個數字時,它不會占用您使用鍵盤上的Enter鍵鍵入的新行。 當執行到達operacia=in.nextLine(); ,此新行將被占用,從不讓用戶有機會鍵入操作字符串。

要解決此問題,您需要使用Scanner#nextLine()閱讀整行並將其轉換為double:

String input = in.nextLine();
num1 = Double.parseDouble(input);
input = in.nextLine();
num2 = Double.parseDouble(input);

我相信in.nextLine(); 該操作僅讀取到您輸入2個數字的行的末尾。 如果要讓程序僅考慮下一行,則必須先清除當前行。

試試這個,它應該可以工作:

System.out.println("Choose the operation");
in.nextLine(); //clear the current line
operacia=in.nextLine();

暫無
暫無

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

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