为什么即使输入正确

时间:2017-08-26 11:02:36

标签: java

我尝试输入与我想要的东西无关的其他东西,如果声明要求我再次输入,它会提示其他..但为什么当我输入正确的东西时它仍然要求我再次选择???为什么?

这是我的代码的一部分:

 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

3 个答案:

答案 0 :(得分:1)

更改

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

if

与您在{{1}}条件中使用它的原因相同。

答案 1 :(得分:1)

您必须在循环条件中使用equals方法,而不是运算符!=。所以正确的版本是:

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

答案 2 :(得分: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);

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