2017-08-26 45 views
0

我已經嘗試輸入其他與我所需要的東西無關的東西,它會提示else if語句要求我再次輸入..但爲什麼當我輸入正確的東西時仍然要求我再次選擇?爲什麼?爲什麼我的循環不會停止,即使我輸入正確

這裏是我的代碼部分:

public static void choose() 
{ 

    Scanner read=new Scanner(System.in); 
    String shape = ""; 


    do{ 

    System.out.println("which shape you would like to choose"); 
    shape=read.nextLine();  
    if(shape.equals("rectangle")) 
    { 
     System.out.println("enter width"); 
     width=Double.parseDouble(read.nextLine()); 
     System.out.println("enter length"); 
     length=Double.parseDouble(read.nextLine()); 
     System.out.println("enter color"); 
     String color = read.nextLine(); 


    } 
    else if (shape.equals("box")) 
    { 
     System.out.println("enter width"); 
     width=Double.parseDouble(read.nextLine()); 
     System.out.println("enter length"); 
     length=Double.parseDouble(read.nextLine()); 
     System.out.println("enter height"); 
     height=Double.parseDouble(read.nextLine()); 
     System.out.println("enter color"); 
     String color = read.nextLine(); 


    } 
    else 
    { 
     System.out.println("please enter only rectangle and box"); 

    } 

    }while((shape !="rectangle" && shape !="box")); 

這裏我跑:

which shape you would like to choose 
abc 
please enter only rectangle and box 
which shape you would like to choose 
box 
enter width 
9 
enter length 
8 
enter height 
8 
enter color 
    blue 
which shape you would like to choose 
+0

*** shape!=「rectangle」***永遠不會在java中使用字符串... –

回答

1

您必須在循環條件中使用equals方法,而不是運算符!=。所以,正確的版本是:由別人說

} while(!"rectangle".equals(shape) && !"box".equals(shape)); 
+0

謝謝你的工作 – sozai

1

變化

shape !="rectangle" && shape !="box" 

!shape.equals("rectangle") && !shape.equals("box") 

出於與在if條件下使用它相同的原因。

+1

謝謝你的工作 – sozai

0

你在while聲明測試是不正確的。

但是你可以通過在每塊的末尾添加break;刪除它(除了一個再次要求輸入):

do{ 

System.out.println("which shape you would like to choose"); 
shape=read.nextLine();  
if(shape.equals("rectangle")) 
{ 
    System.out.println("enter width"); 
    width=Double.parseDouble(read.nextLine()); 
    System.out.println("enter length"); 
    length=Double.parseDouble(read.nextLine()); 
    System.out.println("enter color"); 
    String color = read.nextLine(); 

    break; // Exit loop here 
} 
else if (shape.equals("box")) 
{ 
    System.out.println("enter width"); 
    width=Double.parseDouble(read.nextLine()); 
    System.out.println("enter length"); 
    length=Double.parseDouble(read.nextLine()); 
    System.out.println("enter height"); 
    height=Double.parseDouble(read.nextLine()); 
    System.out.println("enter color"); 
    String color = read.nextLine(); 

    break; // Exit loop here 
} 
else 
{ 
    System.out.println("please enter only rectangle and box"); 

} 

}while(true); 

如果您有少數病例和/或測試耗時,這是一個可行的選擇,因爲您只測試一次每個值。

相關問題