This question already has an answer here:
Scanner objects in methods and NoSuchElementException [duplicate]
(1 answer)
Closed 7 years ago.
So I have a menu for the user using switch case.
public static void app() {
Scanner sc = new Scanner(System.in);
List list = list.read(file.txt);
StringBuilder menu;
int choice = 0;
do {
System.out.println(menu.toString());
choice = sc.nextInt();
switch (choice) {
case 1:
option1();
break;
case 2:
option2();
break;
case 3:
option3(list);
break;
case 4:
option4(list);
break;
case 5:
break;
default:
break;
}
} while (choice != 5);
}
The first 2 options are just methods(outside this class) that allow me to add another object to the list and I don't have any trouble with those 2. Options 3/4 also work, but it causes some issue with the switch case menu.
For options 3/4 I have to ask a certain max of the user, which I do by using a Scanner, but the same int is then also used by the switch case which leads to an error.
I get an exception in the thread "main"(which is where I call the app method) which gets printed right before the menu gets printed strangely enough and I also get a NoSuchElementException at the choice=sc.nextInt() line.
I had thought about closing the scanner right before I call the methods and reopening it afterwards, but that isn't possible.
public static void option3(list input) {
Scanner sc = new Scanner(System.in);
System.out.println(question);
int max = sc.nextInt();
int size = input.size();
if (size > 0) {
if (max == 0) {
print entire list
} else {
print list below max
}
}
sc.close();
}
You should use only one scanner for the same stream (in your case System.in). You can pass your scanner to the method and use it there:
public static void option3(list input, Scanner sc) {
System.out.println(question);
int max = sc.nextInt();
int size = input.size();
if (size > 0) {
if (max == 0) {
print entire list
} else {
print list below max
}
}
}
in your app() method:
case 3:
option3(list, sc);
break;
Related
This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
Closed 2 years ago.
I'm fairly new to programming and I'm having trouble with my program continuously looping when I try to handle a InputMisMatch exception.
I have a menu which takes in user input and then uses a switch statement to deal with the input. I am trying to make my program handle two exceptions. First is making sure that the input is actually an integer and secondly make sure the integer is within the range for the menu. I used the NextInt() method inside a try block. Inside the try block is the switch statement which uses the default case to deal with the input not being in range
However the catch block for when the user types in an input other than an integer keeps looping over and over. It seems I have not updated the user input inside the loop somewhere but I am confused as to where to update it.
For now, I'm not concerned with what is in the switch cases (although I want to implement the same looping feature inside of them as well), It's just the logic for the outer loop.
Here's my code:
Any guidance would be much appreciated. Thanks!
public class Main {
// set up scanner for user input
public static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
// welcome message
welcome();
//declare user choice variables
int menuSelection;
int discSelection;
boolean isInputValid = true ;
do { // keep looping until user input is valid
try {
/*
We can expect an error from user input
1. Input is not an integer
2. Input is not in range
*/
isInputValid = true;
displayMainMenu();
menuSelection = keyboard.nextInt();
System.out.println(); //print new line
//Menu Logic
switch (menuSelection) {
case 0: { // Exit Application
break;
}
case 1: { // Search
searchDiscMenu(); //Display the search menu
discSelection = keyboard.nextInt(); // get user choice
if (discSelection == 1) {
System.out.println("Disc.Music.searchMusic()");
} else if (discSelection == 2) {
System.out.println("Disc.Game.searchGame()");
}
break;
}
case 2: { // Add
addDiscMenu(); //Display add menu
discSelection = keyboard.nextInt(); // get user choice
if (discSelection == 1) {
System.out.println("Disc.Music.addMusic()");
} else if (discSelection == 2) {
System.out.println("Disc.Game.addGame();");
}
break;
}
case 3: { // Remove
removeDiscMenu(); //Display remove menu
discSelection = keyboard.nextInt(); // get user choice
if (discSelection == 1) {
System.out.println("Disc.Music.removeMusic();");
} else if (discSelection == 2) {
System.out.println("Disc.Game.removeGame();");
}
break;
}
case 4: { // View
viewDiscMenu(); //Display view menu
discSelection = keyboard.nextInt(); // get user choice
if (discSelection == 1) {
System.out.println("Disc.Music.viewMusic();");
} else if (discSelection == 2) {
System.out.println("Disc.Music.viewMusic();");
}
break;
}
case 5: { // Sort
sortDiscMenu(); //Display sort menu
discSelection = keyboard.nextInt(); // get user choice
if (discSelection == 1) {
System.out.println("Disc.Music.viewMusic();");
} else if (discSelection == 2) {
System.out.println("Disc.Music.viewMusic();");
}
break;
}
case 6: { // Write
writeDiscMenu(); //Display write menu
discSelection = keyboard.nextInt(); // get user choice
if (discSelection == 1) {
System.out.println("Disc.Music.viewMusic();");
} else if (discSelection == 2) {
System.out.println("Disc.Game.writeGameFile();");
}
break;
}
case 7: { // Read
readDiscMenu(); //Display read menu
discSelection = keyboard.nextInt(); // get user choice
if (discSelection == 1) {
System.out.println("Disc.Music.readMusicFile();");
} else if (discSelection == 2) {
System.out.println("Disc.Game.readGameFile();");
}
break;
}
default: { // Handle exception
isInputValid = false;
System.out.println("Error: Selection Not In Range"); // If the input is an int but not in range
break;
}
}
} catch (InputMismatchException e) { // Handles user typing in a char, double etc. instead of int
isInputValid = false;
System.out.println("Error: Unrecognised Input");
}
} while (!isInputValid);
// Exit application safely
System.out.println("Finished"); // temporary message
}
This can happen since the nextInt() doesn't consume the new line character inserted in the buffer when pressed enter to type something in the console.
To overcome this you can add keyboard.nextLine() to the catch block so you can consume that new line character inserted in the buffer and clear it to the next input.
As others said you should wrap your input hadling in a method since you have louds of nextInt that won't be catched by your InputMismatchException. Said method should call the nextInt() catch the exception if needed and clear the buffer for new line characteres with the nextLine() if not returns the input by the user.
That way you're guarantee that you will always catching that error.
It would be better if you use a method like this to check your input :
public int rangeInt(int lower_boundary, int upper_boundary) {
int inp = -1;
try {
Scanner in = new Scanner(System.in);
inp = in.nextInt();
in.nextLine();
if (inp < lower_boundary || inp > upper_boundary) {
throw new InputMismatchException();
}
} catch (InputMismatchException e) {
System.err.println("Please enter integer between " + lower_boundary + " and " + upper_boundary);
inp = rangeInt(lower_boundary, upper_boundary);
}
return inp;
}
This method handles InputMismatchException and returns an integer between the to ints you pass
first post here.
I was instructed to change my code to loop back to the beginning of the array and ask the user for input again after they input something invalid (Like 0 or 5 for example).
If someone could point me in the right direction, I would be thankful.
package lepackage;
import java.util.Scanner;
public class SwitchItUp {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter menu item:");
int input = scanner.nextInt();
String inputString;
switch (input) {
case 1: inputString = "User want to Enter data";
break;
case 2: inputString = "User want to Display sata";
break;
case 3: inputString = "User want to Print data";
break;
case 4: inputString = "User want to Exit";
break;
default: inputString = "Invalid Number";
break;
}
System.out.println(inputString);
}
}
I'd surround it with a do...while loop
do {
//your code here
} while (!(input > 0 && input < 5));
See it online!
how about using a label here. though It's not the cleaner approach compare to do.. while. see the code . Also don't forget to close the scanner !!
Scanner scanner = new Scanner(System.in);
int input;
badinput: while (true) {
System.out.println("Enter menu item:");
input = scanner.nextInt();
String inputString;
if ((!(input > 0 && input < 5)))
continue badinput;
else {
switch (input) {
//switch case
}
System.out.println(inputString);
break;
}
}
scanner.close();
I am attempting to work through a hackerrank algorithm challenge which will predict the height of a tree after a series of alternating weather patterns. I'm not sure why my logic isn't working. Java says that the break points in my switch statement are not working. I have pasted the code below in full.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt(); // user input how many test cases
System.out.println("test cases set.");
int[] cycles = new int[i];
for (int x = 0; x < i; x++) {
cycles[x] = scan.nextInt(); // user input test cycles
}
for (int x = 0; x < i; x++) {
System.out.println(cycles[x]);
int temp = predictor(cycles[x]);
System.out.println(temp);
}
}
public static int predictor(int cycles) {
// determines the remainder to find even or odd cycle year
int heightRemainder = cycles % 2;
switch (heightRemainder) {
case 0:
System.out.println("Even number");
return cycles; // UNREACHABLE, cycles is a temp variable to check functionality
break;
case 1:
System.out.println("Odd number");
return cycles; // UNREACHABLE, same here
break;
}
return -1;
}
}
Yes, it will not work because your break statement is after return statement, execution control will not go to break statement.
Instead of returning in switch case use variable to store value of cycles and then return that variable at end of method, like this
public static int predictor(int cycles) {
// determines the remainder to find even or odd cycle year
int heightRemainder = cycles % 2;
int r=-1;
switch (heightRemainder) {
case 0:
System.out.println("Even number");
r =cycles;
break;
case 1:
System.out.println("Odd number");
r=cycles
break;
}
return r;
}
}
in the predictor method: remove the break; statement... that is dead code because you are returning the cycle values
switch (heightRemainder) {
case 0:
System.out.println("Even number");
return cycles; // UNREACHABLE, cycles is a temp variable to check functionality
case 1:
System.out.println("Odd number");
return cycles; // UNREACHABLE, same here
}
I am having some logic difficulties when trying to use a do-while loop. In my main() method. I am trying to prompt user again and again if they entered anything larger than 6:
do{
System.out.println("select your option: ");
System.out.println("1.option1");
System.out.println("2.option2");
System.out.println("3.option3");
System.out.println("4.option4");
System.out.println("5.option5");
System.out.println("6.Quit");
optionChoice = sc.nextInt();
switch (optionChoice) {
case 1:
option1Method();
break;
}
} while (optionChoice > 6);
Then inside my option1Method(), I have another do while loop:
do {
System.out.println("select your option: ");
System.out.println("1.opt1 method1");
System.out.println("2.opt2 method2");
System.out.println("3.opt3 method3");
System.out.println("4.Back");
optOption = sc.nextInt();
switch (optOption ) {
case 1: //do stuffs, same for case 2 and 3
break;
case 4: return;
default: break;
}
} while (optOption > 4);
For this method, I am trying to prompt user the choice again and again as long as they entered anything larger than 4. Then, when they entered 4, it should go back to the do while loop in main() method.
However, for the second do-while loop, when I entered 4, the program itself is just terminated. Any ideas?
Thanks in advance.
In the main method set the condition as:
optionChoice != 6
I am not sure if this is what you want, but I have written the following for you:
import java.util.Scanner;
public class Answer {
static Scanner sc = new Scanner(System.in);
static int optionChoice;
public static void main(String[] args) {
do{
System.out.println("select your option: ");
System.out.println("1.option1");
System.out.println("2.option2");
System.out.println("3.option3");
System.out.println("4.option4");
System.out.println("5.option5");
System.out.println("6.Quit");
optionChoice = sc.nextInt();
switch (optionChoice) {
case 1:
option1Method();
break;
}
} while (optionChoice > 6);
}
public static void option1Method() {
int optOption;
do {
System.out.println("select your option: ");
System.out.println("1.opt1 method1");
System.out.println("2.opt2 method2");
System.out.println("3.opt3 method3");
System.out.println("4.Back");
optOption = sc.nextInt();
switch (optOption ) {
case 1: //do stuffs, same for case 2 and 3
break;
case 4:
optionChoice = 7; // you have to make this value greater than 6 if you want to continue in the loop
return;
default: break;
}
} while (optOption > 4);
}
}
The problem when you enter 4 is that you go back to the main method, and the value you entered for optionChoice is 1 which makes false the condition of the while loop.
EDIT:
In response to #Timeout who is totally right by claiming I am assuming that optionChoice is a "global variable".
To keep your functionality I guess you should just have the following condition in the do-while loop of the main() method:
optionChoice > 6 || optionChoice == 1
EDIT:
what if you add as a condition in the second while loop
optOption != 4
so that you will remain in that loop until the user enters 4
EDIT TO HANDLE optionXMethod where X is a number:
do{
System.out.println("select your option: ");
System.out.println("1.option1");
System.out.println("2.option2");
System.out.println("3.option3");
System.out.println("4.option4");
System.out.println("5.option5");
System.out.println("6.Quit")
optionChoice = sc.nextInt();
switch (optionChoice) {
case 1:
option1Method();
break;
case 2:
option2Method();
break;
case X:
optionXMethod();
break;
}
} while (optionChoice != 6);
void option1Method() {
int optOption;
do {
System.out.println("select your option: ");
System.out.println("1.opt1 method1");
System.out.println("2.opt2 method2");
System.out.println("3.opt3 method3");
System.out.println("4.Back");
optOption = sc.nextInt();
switch (optOption ) {
case 1: //do stuffs, same for case 2 and 3
break;
// you do not need the case 4: because when optOptiontakes the value of 4 it leaves the loop
default: break;
}
} while (optOption != 4);
}
....
General case:
void optionXMethod() {
int optOption;
do {
System.out.println("select your option: ");
System.out.println("1.opt1 method1");
System.out.println("2.opt2 method2");
System.out.println("3.opt3 method3");
System.out.println("4.opt4 method4");
// more options
System.out.println("X.Back"); // where X is the number option of Back
optOption = sc.nextInt();
switch (optOption ) {
case 1: //do stuffs, same for case 2 and 3
break;
// you do not need the case 4: because when optOptiontakes the value of 4 it leaves the loop
default: break;
}
} while (optOption != X); // whatever the value of X is should be consider for this condition
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm new to stack overflow and I'm trying to help a friend with their programming homework.
So far we have this
package range;
import java.util.Arrays;
import java.util.Scanner;
public class Range
{
static int[] series = new int[100];
static int seriesLength = 0;
public static void main(String[] args)
{
Scanner t = new Scanner(System.in);
boolean run = true;
while(run)
{
int option;
System.out.println("1. Loading a range of up to 100 numbers");
System.out.println("2. Showing the range of given(loaded) numbers");
System.out.println("3. Determination of the middle value of the series");
System.out.println("4. Determination of the biggest element of the series");
System.out.println("5. Determination of the smallest element of the series\n");
System.out.println("Enter the number of the option you want (1-5), or 0 to end");
option = t.nextInt();
switch(option)
{
case 1:
{
System.out.println("Please input a number from 1 -100");
seriesLength = t.nextInt();
System.out.println(seriesLength);
if((seriesLength < 1) || (seriesLength > 100))
{
System.out.println("Invalid input, series must be between 1 and 100.\nPress any key to try again.\n");
break;
}
for(int i = 0; i < seriesLength; i++)
{
series[i] = i+1;
}
break;
}
case 2:
{
System.out.println(seriesLength);
if(seriesLength == 0)
{
System.out.println("You must first load a series of numbers\n");
break;
}
showSeries(series, seriesLength);
break;
}
case 3:
{
if(seriesLength == 0)
{
System.out.println("You must first load a series of numbers\n");
break;
}
middleNum(series, seriesLength);
break;
}
case 4:
{
if(seriesLength == 0)
{
System.out.println("You must first load a series of numbers\n");
break;
}
biggestNum(series, seriesLength);
break;
}
case 5:
{
if(seriesLength == 0)
{
System.out.println("You must first load a series of numbers\n");
break;
}
smallestNum(series, seriesLength);
break;
}
case 0:
{
System.out.println("BYE, DOBRO DOBRO.");
run = false;
break;
}
default:
{
System.out.println("Invalid input");
break;
}
}
}
}
public static void showSeries(int[] input, int range)
{
for(int i = 0; i < range; i++)
{
System.out.println(input[i]);
}
}
public static void biggestNum(int[] input, int range)
{
Arrays.sort(input);
System.out.println(input[0]);
}
public static void middleNum(int[] input, int range)
{
int Middle = input.length / 2;
if ((input.length % 2) > 0)
{
System.out.println(input[Middle]);
}
else
{
System.out.println((input[Middle-1] + input[Middle]) / 2.0);
}
}
public static void smallestNum(int[] input, int range)
{
Arrays.sort(input);
for(int i = 0; i < range; i++)
{
System.out.println(input[i]);
}
}
}
The task was to write a program which works with an array of numbers using a menu
with few options. But also the task of each option needs to be a separate method and the main method needs to only show the menu and call for each method depending on the number(option) chosen. Also needs to check users errors, example if option 2 is chosen before option 1 or the chosen option doesn't exist and etc.
I'm confused on how to proceed as I'm no expert in java. How would this be done considering that the only things can be used are defined by the task
Maybe you want something more like this, Where the show series method actually sets the array, so the other methods can use the array
static int[] series = new int[100];
static int seriesLength = 0;
...
// Get the input for range
public static void showSeries(int range)
{
seriesLength = range;
series = new int[seriesLength];
for (int i = 0; i < series.legnth; i++) {
series[i] = i;
System.out.print(series[i] + " ");
}
}
Because this first method needs to be the first one called before anything, the array will be set. Then the other methods shouldn't have to take any arguments, as the array is already set, and they can just use the static array.