Java中的逻辑和循环问题

我开始用Java编写小程序。 我想练习try-catch块,但我甚至没有达到那个部分并且卡在循环部分。 我知道这是一个非常基本的循环问题,但我想我陷入了一个非常简单的逻辑问题。 我需要的是这个程序,如果用户按1,然后跳转到switch语句并执行正确的大小写。 如果用户按下除1或2之外的任何内容,则返回MenuLoopfunction并再次执行,直到按下正确的数字(1或2)。 我用While循环来控制。 这是代码。

import java.util.Scanner; public class TryCatchExercise { public static void MenuLoop() { Scanner input = new Scanner(System.in); int choice; System.out.println("1. Check for Number 1"); System.out.println("2. Check for Number 2"); System.out.print("Please enter your choice... "); choice = input.nextInt(); while (choice != 1 || choice != 2) { System.out.println("Invalid entry, press 1 or 2"); MenuLoop(); } //Isn't it logical at this point for loop to be skipped and // go to Switch if a user pressed 1 or 2.?? switch (choice) { case 1: System.out.println("Pressed 1"); break; case 2: System.out.println("Pressed 2"); break; default: System.out.println("Invalid number"); } } public static void main(String[] args) { MenuLoop(); } } OUTPUT 1. Check for Number 1 2. Check for Number 2 Please enter your choice... 1 Invalid entry, press 1 or 2 1. Check for Number 1 2. Check for Number 2 Please enter your choice... 2 Invalid entry, press 1 or 2 1. Check for Number 1 2. Check for Number 2 Please enter your choice... 5 Invalid entry, press 1 or 2 1. Check for Number 1 2. Check for Number 2 Please enter your choice... 

你需要一个逻辑和(不是或)这里

 while (choice != 1 || choice != 2) { System.out.println("Invalid entry, press 1 or 2"); MenuLoop(); } 

应该是这样的

 while (choice != 1 && choice != 2) { System.out.println("Invalid entry, press 1 or 2"); MenuLoop(); } 

(使用德摩根定律 )之类的

 while (!(choice == 1 || choice == 2)) { System.out.println("Invalid entry, press 1 or 2"); MenuLoop(); } 

也许您可以尝试以下代码。 在您的代码中,不需要使用迭代。

 choice = input.nextInt(); while (choice != 1 && choice != 2) { System.out.println("Invalid entry, press 1 or 2"); choice = input.nextInt(); } 

部分问题是您从menuLoop中递归调用menuLoop

如果你在main有一个while循环,那么如果没有按下正确的键你就可以返回。

所以主要是这样的

 while (!menuLoop () { System.out.println("Invalid entry, press 1 or 2"); } 

menuLoop将返回一个布尔值

 public static boolean MenuLoop() { .... System.out.println("1. Check for Number 1"); System.out.println("2. Check for Number 2"); System.out.print("Please enter your choice... "); choice = input.nextInt(); if(choice != 1 && choice != 2) { // and NOT or return false; } switch (choice) { case 1: System.out.println("Pressed 1"); break; case 2: System.out.println("Pressed 2"); break; default: System.out.println("Invalid number"); } return true; 

另请注意, scanner.nextInt不会吞下可能会或可能不会按下的Enter键。

这是一个逻辑问题,“选择”值应该是1或2.在你的(while)语句中,你检查“choice”与1没有区别,但是“choice”与2没有区别。这个条件永远不会达到,因为“选择”可以是1或2,但不能同时是两个值。 这只是对情况的解释。