+ 1

User input in switch case statements

In switch case statements while finding the day in a week how can we take user input? In the written code the "day" variable is assigned value 3 but if the user wants to give another value then?

16th Jun 2019, 9:30 AM
Aishwarya Nigam
Aishwarya Nigam - avatar
2 ответов
+ 2
To take user input in java, you have to use Scanner. import java.util.Scanner; public class Input { public static vour main(String[] args) { Scanner sc = new Scanner(System.in); int day = sc.nextInt(); sc.close(); switch (day) { //code goes here } } } (The nextInt method reads the next integer of the Scanner. To get a string input, use the next method) You can read more about the Scanner class here: https://www.sololearn.com/learn/Java/2220/?ref=app
16th Jun 2019, 9:34 AM
Airree
Airree - avatar
0
// if you need read int in loop (enter empty for break) import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int day; while (true) { System.out.print("Enter number of day in week: "); try { // empty line for break day = Integer.parseInt( sc.nextLine() ); } catch(NumberFormatException e) { break; } System.out.println(day); //if you are on sololearn //switch (day) ... } } }
16th Jun 2019, 7:22 PM
zemiak