Issue with logic and Loop in Java -


i started coding small program in java. wanted exercise try-catch block, did not come part , got stuck on loop part. know basic loop issue, guess caught myself in simple logical problem. need program if user press 1, jump switch statement , execute proper case. if user press 1 or 2, go menuloop function , execute again until pressed correct number (1 or 2). used while loop control. here 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 number 1");     system.out.println("2. check number 2");     system.out.print("please enter choice... ");     choice = input.nextint();     while (choice != 1 || choice != 2) {         system.out.println("invalid entry, press 1 or 2");         menuloop();     }    //isn't logical @ point loop skipped ,           // go switch if 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 number 1  2. check number 2  please enter choice... 1  invalid entry, press 1 or 2  1. check number 1  2. check number 2  please enter choice... 2  invalid entry, press 1 or 2  1. check number 1  2. check number 2  please enter choice... 5  invalid entry, press 1 or 2  1. check number 1  2. check number 2  please enter choice...  

you need logical , (not or) here

while (choice != 1 || choice != 2) {     system.out.println("invalid entry, press 1 or 2");     menuloop(); }  

should like

while (choice != 1 && choice != 2) {     system.out.println("invalid entry, press 1 or 2");     menuloop(); }  

or (using de morgan's laws) like

while (!(choice == 1 || choice == 2)) {     system.out.println("invalid entry, press 1 or 2");     menuloop(); }  

Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -