java循环困难

eufgjt7s  于 2021-06-29  发布在  Java
关注(0)|答案(3)|浏览(291)

这个问题在这里已经有答案了

java错误的用户输入循环直到正确(3个答案)
12天前关门了。
从建议问题的答案中获得一些信息,并编辑了我的代码。现在我得到一个| |运算符的错误。那里怎么了?写这篇文章的正确方法是什么。

public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String shapeName;

        do {
            System.out.println("Please identify the shape");
            System.out.print("Rectangle (Press R) / Circle (Press C): ");

            shapeName = input.next();

        } while (!shapeName.equals("R") || !shapeName.equals("C"));
nue99wik

nue99wik1#

好的,你有这样一个概念“要求选择一个选项,如果没有一个可用的选项被选择,告诉用户,然后再次提示”。
那是一堆工作。所以,制定一个方法。

public static String pick(Scanner scanner, String prompt, String... options) {
    while (true) {
        System.out.println(prompt);
        String choice = scanner.next();
        for (String option : options) {
            if (option.equals(choice)) return choice;
        }
        System.out.println("Error - that is not an available choice.");
    }
}

以及使用:

String choice = pick(scanner,
  "Please identify the shape\nRectangle (R) / Circle (C): ",
  "R", "C");
aoyhnmkz

aoyhnmkz2#

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
      char ch2;
  do{
      char choice;
      System.out.println("Please identify the shape"); 
      System.out.print("Rectangle (Press R) / Circle (Press C): ");
      choice=input.next().charAt(0);
switch(choice){
    case 'R':
       System.out.println("Do first operation bla bla bla");
      break;
  case 'C':
    System.out.println("Do second operation bla bla bla");
    break;
  default:
       System.out.println("ERROR");
       break;
}
System.out.println("do u want to continue enter y/n");
 ch2=input.next().charAt(0);
}
while((ch2!='n')&& (ch2!='N'));
}
rvpgvaaj

rvpgvaaj3#

在代码中 while 这种说法是错误的。
代替

while (!shapeName.equals("R") || !shapeName.equals("C"));

具有

while (!(shapeName.equals("R") || shapeName.equals("C")));

--或者--

while (!shapeName.equals("R") && !shapeName.equals("C"));

如果条件结合使用 || ,此组合中的下一个条件仅在条件的计算结果为时被选中 false i、 一旦情况发展到 true ,则组合中的下一个条件不被选中,并且组合的计算结果为 true .
如果条件结合使用 && ,此组合中的下一个条件仅在条件的计算结果为时被选中 true i、 一旦情况发展到 false ,则组合中的下一个条件不被选中,并且组合的计算结果为 false .

你的情况怎么了?

让我们看看你的条件是如何产生一个不理想的结果。
当用户进入 R ,您的病情评估如下

while (!shapeName.equals("R") || !shapeName.equals("C")); => while (false ||  !shapeName.equals("C")); => while (false ||  true); => while (true);

当用户进入 C ,您的病情评估如下

while (!shapeName.equals("R") || !shapeName.equals("C")); => while (true ||  !shapeName.equals("C")); => while (true);

因此,使用您的条件,尽管用户输入了所需的输入 while 情况迫使它返回。
现在,试着用同样的方法做同样的练习 while 我在回答中提出的条件。

相关问题