+ 1

How to put switches into loops?

I wonder how i could recounter the day when n is larger than 7? import java.util.Scanner; class Mozer{ public static void main(String [] args){ Scanner day = new Scanner (System.in); System.out.println("Enter a number:"); int n=day.nextInt(); while (n>0){ switch (n){ case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; case 4: System.out.println("Thursday"); break; case 5: System.out.println("Friday"); break; case 6: System.out.println("Saturday"); break; case 7: System.out.println("Sunday"); break; } } } }

21st Jun 2017, 4:46 PM
Mozer
Mozer - avatar
4 Respostas
0
Here you go :) Inputs from 1-7 1 is Monday 7 is Sunday https://code.sololearn.com/cX1En4CnL2aT/?ref=app
21st Jun 2017, 5:05 PM
Limitless
Limitless - avatar
0
Why the dislike? I mean he literally asked: "I wonder how I could recounter the day when n is larger than 7?" I want an honest reply from the dislike
21st Jun 2017, 5:22 PM
Limitless
Limitless - avatar
- 2
So you'll need to add the readInt() Inside the while loop. And if the person enters the wrong integer try limiting it like: if(input > 7){ input = 7; }else if(input < 1){ input = 0; } or input = input%7 + 1;
21st Jun 2017, 4:50 PM
Limitless
Limitless - avatar
- 2
There's really no point in having the switch inside the while loop in this case. Unless you really want to do your error checking with the default case. It looks like what you really want is a do while loop for the input, so you can loop until you get a valid int and then to run the switch case. import java.util.Scanner; class Mozer{ public static void main(String [] args){ Scanner day = new Scanner (System.in); int n; do { System.out.println("Enter a number:"); n=day.nextInt(); if (n < 1 || n > 7) { System.out.println("Invalid input. Must be greater than 0 and less than 8."); } } while (n < 1 || n > 7); switch (n){ case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; case 4: System.out.println("Thursday"); break; case 5: System.out.println("Friday"); break; case 6: System.out.println("Saturday"); break; case 7: System.out.println("Sunday"); break; } } }
21st Jun 2017, 5:16 PM
ChaoticDawg
ChaoticDawg - avatar