2017-08-26 134 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); 

如果您有少数病例和/或测试耗时,这是一个可行的选择,因为您只测试一次每个值。

相关问题