Java中的逻辑和循环问题 [英] Issue with logic and Loop in Java
问题描述
我开始用Java编写小程序.我想练习try-catch块,但我什至没有来到那部分而陷入循环部分.我知道这是一个非常基本的循环问题,但我想我陷入了一个非常简单的逻辑问题.我需要从该程序中获得帮助,如果用户按1,则跳转到switch语句并执行适当的大小写.如果用户按下1或2以外的任何键,则返回MenuLoop功能并再次执行它,直到按下正确的数字(1或2)为止.我使用While循环进行控制.这是代码.
I started coding small program in Java. I wanted to exercise try-catch block, but i did not even come to that part and got stuck on loop part. I know this is very basic loop issue, but i guess i caught myself in a very simple logical problem. What I need from this program is if a user press 1, then to jump to switch statement and execute proper case. If a user press anything but 1 or 2, to go back to the MenuLoop function and execute it again until pressed correct number (1 or 2). I used While loop for control. Here is the code.
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...
推荐答案
这是一个逻辑问题,"choice"值应为1或2. 在您的(while)语句中,您正在检查选择"是否与1相同 而且选择"与2相同.永远不会达到此条件,因为选择"可以是1或2,但不能同时是两个值.这只是对情况的解释.
This is a logical problem, the "choice" value should be either 1 or 2. In your (while) statement you are checking that "choice" is not different from 1 but also that "choice" is not different from 2. This condition is never reached because "choice" can be either 1 or 2 but not both values at the same time. This is only an explanation of the situation.
这篇关于Java中的逻辑和循环问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!