做的同时永远循环

时间:2013-12-11 20:49:41

标签: java while-loop do-while

我遇到了这种方法的问题,我永远坚持“对不起你必须指定一个Deeppan或瘦基地,再试一次:”即使我输入jimmy,harry,deeppan,thin,Thin ..等等我键入deeppan或thin,我希望String存储在变量“size”中并返回

我缺少什么想法?

 public String Input(){


    String size;

    Scanner sc = new Scanner(System.in);
    System.out.println("thin or thick: ");

    do {
        size = scan.next();
        if ( !size.equalsIgnoreCase( "thick") || !size.equalsIgnoreCase( "thin" )) {
            System.out.print("Sorry you must specify a thick or thin base, try again: ");
        } else {
            break;
        }
    } while ( true );

    return size;
} 

7 个答案:

答案 0 :(得分:9)

更改你的||为了&&在if条件下。如果你键入'thin',条件将成立,因为它不是deeppan,反之亦然。

答案 1 :(得分:5)

if中的陈述始终为true

你应该使用

!size.equalsIgnoreCase( "Deeppan") && !size.equalsIgnoreCase( "thin" )

!(size.equalsIgnoreCase( "Deeppan") || size.equalsIgnoreCase( "thin" ))

答案 2 :(得分:2)

while(true)将使你的循环无限,因为它始终是真的

原因是你正在进行||操作

答案 3 :(得分:2)

原因:

!size.equalsIgnoreCase( "Deeppan") || !size.equalsIgnoreCase( "thin" )

size不能同时“Deeppan”和“thin”: - )

尝试:

  do {
        size = scan.next();
        if (size.equalsIgnoreCase( "Deeppan") || size.equalsIgnoreCase( "thin" )) {
            break;
        }
        else {
            System.out.print("Sorry you must specify a Deeppan or thin base, try again: ");
        }
    } while ( true );

PS。 “size”不是最好的变量名......

答案 4 :(得分:1)

没有理由使用do-while,尝试这样while,条件检查变得更加直接:

while (true) {
    size = scan.next();
    if (size.equalsIgnoreCase("deeppan") || size.equalsIgnoreCase("thin"))
         return size;
    System.out.println("Sorry you must specify a Deeppan or Thin base, try again:");
}

答案 5 :(得分:0)

永远是真的,因此永远不会到达else

示例1:尺寸为“Deeppan”:
!size.equalsIgnoreCase(“Deeppan”)|| !size.equalsIgnoreCase(“thin”)
=!true || !假
= false ||真正
= true

示例2:大小为“foo”:
  !size.equalsIgnoreCase(“Deeppan”)|| !size.equalsIgnoreCase(“thin”)
 =!false || !假
 = true ||真正
 = true

答案 6 :(得分:0)

Yuor声明

if(!size.equalsIgnoreCase(“Deeppan”)||!size.equalsIgnoreCase(“thin”))

总是如此。