edit:
adding the one of the methods called below, just in case the problem is with the method, not the loop.
Below is a switch menu, there are several cases in the switch. Each case calls a a public void method form another class, and completes successfully, is supposed to displays the menu method (method that prints menu options) and allow the user to select another option. Currently, after completing one case, the program showMenu() again, then breaks at instantly:
String menu = in.nextLine();
on the second iteration of the menu and sends back
java.util.NoSuchElementException: No line found
Question: I need the program to pause or something similar after showMenu(); to let the user input a menu selection, currently the menu displays and the program crashes instantly
Cheers
public class Menu {
public static char selection;
public static String quitting = "you dun son";
public static String errorMessage = "THAAAAATSS A menu WRRRAAAAAPPP";
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
try {
do {
showMenu();
String menu = in.nextLine();
if (menu.length() > 0) {
selection = menu.toLowerCase().charAt(0); // extract the first char of the line read
} else {
selection = '\0';
System.out.println("invalid input:\t" + selection);
System.out.println("Press enter to continue...");
}
switch (selection) {
case 'f':
FuelConsole fuelObject = new FuelConsole();
fuelObject.fuelCalc();
break;
case 'g':
GameConsole gameObject = new GameConsole();
gameObject.gameCalc();
break;
case 'q':
System.out.println("\nEnding Now\n");
System.exit(0);
break;
default:
System.out.println("Instruction is invalid");
}
} while (selection != 'Q' && selection != 'q');
{
System.out.println(quitting);
System.exit(0);
}
}catch (Exception e) {
System.out.println(errorMessage);
}
}
a test method:
public class FuelConsole {
public static String errorMessage = "THAAAAATSS A fuel calc WRRRRAAAAAPPPPPPPPPPPP";
public static Double acceptableCentsPerLitre = 16.00;
Scanner scan = new Scanner(System.in);
public void fuelCalc() {
try {
System.out.println("\nyou selected option 'f' --- here you will enter some information and find average fuel for ONE trip. ");
System.out.println("please enter the amount of fuel in litres:\n ");
float fuel = scan.nextFloat();
System.out.println("please enter the price of fuel in cents (not dollars and cents, only CENTS (lulz)):\n ");
int cent = scan.nextInt();
System.out.println("please enter the number of kilometers travelled on the tank:\n ");
float kilo = scan.nextFloat();
float returnAFC = afc(fuel, kilo);
float returnAC = ac(returnAFC, cent);
System.out.println("average consumption: \t" + returnAFC);
System.out.println("average cost: \t\t" + returnAC);
if (returnAC > acceptableCentsPerLitre) {
System.out.println("Average fuel is above 16c per litre");
} else {
System.out.println("Average fuel is below 16c per litre");
}
} catch (Exception e) {
System.out.println(errorMessage);
e.printStackTrace();
} finally {
scan.close();
}
}
public static float afc(float x, float z) {
float result = x / z;
return result;
}
public static float ac(float x, int y) {
float result = x * y;
return result;
}
}
I think the problem is that you create a new Scanner in the FuelConsole Class.
And you also close it in the finally block.
But when you call close() on scanner it also closes the underlaying InputStream too. (System.in in this case) And because your top-level Scanner uses the same InputStream, it cannot catch any more input from it.
The solution could be if you pass the top level scanner as an argument to other objects:
case 'f':
FuelConsole fuelObject = new FuelConsole();
fuelObject.fuelCalc(in);
break;
case 'g':
GameConsole gameObject = new GameConsole();
gameObject.gameCalc(in);
break;
and
public void fuelCalc(Scanner scan) {
try {
...
and delete the finally block
Related
//Inventory Items classs
import java.util.Scanner;
public class InventoryItems {
public int sackrice = 4;
public int animalfeed = 12;
public int trayeggs = 15;
public int bottlemilk = 9;
ItemSupplier supple = new ItemSupplier();
public void inventoryItem() {
System.out.println("\nAvailable items:\n");
sackrice = sackrice + supple.getRice();
System.out.println("Sack of rice: " + sackrice);
if(sackrice < 10)
System.out.println("Sack of rice low, please restock");
System.out.println();
System.out.println("Animal feed: " + animalfeed);
if(animalfeed < 10)
System.out.println("Animal feed low, please restock");
System.out.println();
System.out.println("Tray of eggs: " + trayeggs);
if(trayeggs < 15)
System.out.println("Tray of eggs low, please restock");
System.out.println();
System.out.println("Bottle of milk: " + bottlemilk);
if(bottlemilk < 15)
System.out.println("Bottle of milk low, please restock");
System.out.println();
press();
}
public static void press(){
Scanner input = new Scanner(System.in);
System.out.println("Press Enter to continue...");
String enter = input.nextLine();
}
}
//Item Supplier class
import java.util.Scanner;
public class ItemSupplier {
public int z;
Scanner scan = new Scanner(System.in);
public void ricesupplier() {
System.out.println("How many sacks of rice would you like to
order?");
z = scan.nextInt();
}
public int getRice() {
return z;
}
public void feedsupplier() {
}
public void eggsupplier() {
}
public void milksupplier() {
}
}
import java.util.Scanner;
public class InventoryManager{
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int x;
int y;
do {
System.out.println("Input option:\n" + "\n1. Check inventory" + "\n2. Search item supplier" + "\n3. Exit\n");
x = scan.nextInt();
switch(x) {
case 1:
InventoryItems items = new InventoryItems();
items.inventoryItem();
break;
case 2:
ItemSupplier supply = new ItemSupplier();
do {
System.out.println("\nChoose supplier:\n" + "\n1. Rice supplier\n" + "2. Animal feed supplier\n" + "3. Egg supplier\n" + "4. Milk supplier\n" + "5. Back\n");
y = scan.nextInt();
switch(y) {
case 1:
supply.ricesupplier();
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
default:
System.out.println("Invalid option");
break;
}
break;
} while (y != 5);
break;
case 3:
System.out.println("Program closed");
System.exit(0);
default:
System.out.println("Invalid option");
break;
}
} while(x != 3);
}
}
The "z" I get from getRice() is 0. It only takes the declared but initialized z. How do I get the "z" that was inputed in ricesupplier() method? Specifically, here: System.out.println("How many sacks of rice would you like to order?") and here z = scan.nextInt().
I'm really just a beginner. A lot of parts are still incomplete. I need to finish this problem first before I can proceed.
This won't be a direct answer to your question but here's some hints in order to improve your code and eventually solve your problem.
You should not make a new InventoryItems every time the user's input is 1. This will result into printing the initial inventory items, thus making your user order an item is useless
You should not make a new ItemSupplier every time the user's input is 2.
You don't need ItemSupplier in your InventoryItems
You don't need the variable z in ItemSupplier, you can directly return the input of the user in ricesupplier() method
thus if the user's input is 2 then you can just call ricesupplier() method and add it's return to the current items.sackrice
my question is short and sweet. I do not understand why my program infinitely loops when catching an error. I made a fresh try-catch statement but it looped and even copied, pasted and modified the appropriate variables from a previous program that worked. Below is the statement itself and below that will be the entire program. Thank you for your help!
try {
input = keyboard.nextInt();
}
catch(Exception e) {
System.out.println("Error: invalid input");
again = true;
}
if (input >0 && input <=10)
again = false;
}
Program:
public class Blanco {
public static int input;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
nameInput();
}
/**
*
* #param name
*/
public static void nameInput() {
System.out.println("What is the name of the cartoon character : ");
Scanner keyboard = new Scanner(System.in);
CartoonStar star = new CartoonStar();
String name = keyboard.next();
star.setName(name);
typeInput(keyboard, star);
}
public static void typeInput(Scanner keyboard, CartoonStar star) {
boolean again = true;
while(again){
System.out.println("What is the cartoon character type: 1 = FOX,2 = CHICKEN,3 = RABBIT,4 = MOUSE,5 = DOG,\n"
+ "6 = CAT,7 = BIRD,8 = FISH,9 = DUCK,10 = RAT");
try {
input = keyboard.nextInt();
}
catch(Exception e) {
System.out.println("Error: invalid input");
again = true;
}
if (input >0 && input <=10)
again = false;
}
switch (input) {
case 1:
star.setType(CartoonType.FOX);
break;
case 2:
star.setType(CartoonType.CHICKEN);
break;
case 3:
star.setType(CartoonType.RABBIT);
break;
case 4:
star.setType(CartoonType.MOUSE);
break;
case 5:
star.setType(CartoonType.DOG);
break;
case 6:
star.setType(CartoonType.CAT);
break;
case 7:
star.setType(CartoonType.BIRD);
break;
case 8:
star.setType(CartoonType.FISH);
break;
case 9:
star.setType(CartoonType.DUCK);
break;
case 10:
star.setType(CartoonType.RAT);
break;
}
popularityNumber(keyboard, star);
}
public static void popularityNumber(Scanner keyboard, CartoonStar star) {
System.out.println("What is the cartoon popularity number?");
int popularity = keyboard.nextInt();
star.setPopularityIndex(popularity);
System.out.println(star.getName() + star.getType() + star.getPopularityIndex());
}
}
Your program runs forever because calling nextInt without changing the state of the scanner is going to cause an exception again and again: if the user did not enter an int, calling keyboard.nextInt() will not change what the scanner is looking at, so when you call keyboard.nextInt() in the next iteration, you'll get an exception.
You need to add some code to read the garbage the user entered after servicing an exception to fix this problem:
try {
...
} catch(Exception e) {
System.out.println("Error: invalid input:" + e.getMessage());
again = true;
keyboard.next(); // Ignore whatever is entered
}
Note: you do not need to rely on exceptions in this situation: rather than calling nextInt(), you could call hasNextInt(), and check if the scanner is looking at an integer or not.
I am having an issue where it isn't checking the validity of user input correctly. It breaks if I input a letter or string as a choice instead of looping through and asking again. I'm pretty sure that I have my functions, isDouble and isInt, correct and it's more a matter of placement. Advice?
public class Main
{
static Scanner scan = new Scanner(System.in);
public static void main(String[] args)
{
displayMenu();
int entryChoice = scan.nextInt();
while (entryChoice != 9)
{
System.out.println(userSelection(entryChoice));
displayMenu();
isInt(entryChoice);
entryChoice = scan.nextInt();
}
scan.close();
System.exit(0);
}
public static boolean isDouble(double x)
{
double userInput = x;
try
{
userInput = Double.parseDouble(scan.next());
return true;
}
catch (NumberFormatException ignore)
{
System.out.println("Invalid input. Try again.");
return false;
}
}
public static boolean isInt(int x)
{
int userInput = x;
try
{
userInput = Integer.parseInt(scan.next());
return true;
}
catch (NumberFormatException ignore)
{
System.out.println("Invalid input");
return false;
}
}
public static void displayMenu()
{
System.out.println("Please select from the following choices:");
System.out.println();
System.out.println("1) Addition");
System.out.println("2) Subtraction");
System.out.println("3) Multiplication");
System.out.println("4) Division");
System.out.println("5) Raise to a Power");
System.out.println("6) Square Root");
System.out.println("7) Store a Number");
System.out.println("8) Recall Stored Number");
System.out.println("9) Exit Program");
System.out.println();
System.out.println("Enter your choice here: ");
}
public static double userSelection(int entryChoice)
{
double result = 0;
double x = 0;
double y = 0;
if (entryChoice == 6)
{
System.out.println("Enter one number: ");
x = scan.nextDouble();
}
else
{
System.out.println("Enter two numbers seperated by a space");
x = scan.nextDouble();
y = scan.nextDouble();
}
switch (entryChoice)
{
case 1:
result = x + y;
break;
case 2:
result = x - y;
break;
case 3:
result = x * y;
break;
case 4:
if (y == 0)
{
System.out.println("Can't divide by zero. Please enter another number.");
y = scan.nextDouble();
result = x / y;
}
else
{
result = x / y;
}
break;
case 5:
result = Math.pow(x, y);
break;
case 6:
result = Math.sqrt(x);
break;
case 7:
//store a number
break;
case 8:
//recall a stored number
break;
case 9:
result = 0;
break;
default:
}
return result;
}
}
I'm pretty sure that I have my functions, isDouble and isInt, correct and it's more a matter of placement.
You don't.
Your isInt() method ignores its parameter, reads a new value from the scanner and checks to see if it's a number, and doesn't return the new value, whether or not it's a number.
In any case, the Scanner class you are using to collect user input already does this sort of validation for you. You started in the correct direction with
int entryChoice = scan.nextInt();
but it's dangerous to try to get a token from a Scanner without first checking to see if it has one for you to get.
If you look at the API docs for Scanner, you'll see a whole list of nextFoo() and hasNextFoo() methods. These are meant to be used together.
Generally what you want is a loop which prompts the user for the desired input until they give it, like this:
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a number");
while (!scan.hasNextInt()) {
scan.next(); // throw away non-numeric input
System.out.println("Please enter a number");
}
System.out.println("User entered: " + scan.nextInt());
This will end up re-prompting the user until they give you a number:
Please enter a number
apple
Please enter a number
fox
Please enter a number
bear
Please enter a number
42
User entered: 42
Here is your code,However i did many changes.Wish this help you little.
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
static Scanner scan = new Scanner(System.in);
static int entryChoice = 0;
static boolean tester = true;
static double result;
public static void main(String[] args) {
displayMenu();
boolean check = isInt(entryChoice);
while (check && entryChoice != 9) {
result = userSelection(entryChoice);
System.out.print(result == 0 && !tester ? "" : result + "\n");
if (!tester)
break;
}
scan.close();
System.exit(0);
}
/*
* public static boolean isDouble(double x) {
*
* try { x = Double.parseDouble(scan.next()); return true; } catch
* (NumberFormatException ignore) { System.out.println(
* "Invalid input. Try again.");
*
* return false; } }
*/
public static boolean isInt(int x) {
try {
x = Integer.parseInt(scan.next());
entryChoice = x;
return true;
} catch (NumberFormatException ignore) {
System.out.println("Invalid input");
System.err.println("program will be terminated!");
tester = false;
return false;
}
}
public static void displayMenu() {
System.out.println("Please select from the following choices:");
System.out.println();
System.out.println("1) Addition");
System.out.println("2) Subtraction");
System.out.println("3) Multiplication");
System.out.println("4) Division");
System.out.println("5) Raise to a Power");
System.out.println("6) Square Root");
System.out.println("7) Store a Number");
System.out.println("8) Recall Stored Number");
System.out.println("9) Exit Program");
System.out.println();
System.out.println("Enter your choice here: ");
}
public static double userSelection(int entryChoice) {
double result = 0;
double x = 0;
double y = 0;
if (entryChoice == 6) {
try {
System.out.println("Enter one number: ");
x = scan.nextDouble();
} catch (InputMismatchException ignore) {
System.out.println("Invalid input");
}
} else {
try {
System.out.println("Enter two numbers seperated by a space");
x = scan.nextDouble();
y = scan.nextDouble();
} catch (InputMismatchException ignore) {
System.err.println("Invalid input,program will be terminated !");
tester = false;
// return ;
}
}
switch (entryChoice) {
case 1:
result = x + y;
break;
case 2:
result = x - y;
break;
case 3:
result = x * y;
break;
case 4:
if (y == 0 && tester) {
System.out.println("Can't divide by zero. Please enter another number.");
try {
y = scan.nextDouble();
} catch (InputMismatchException ex) {
System.err.println("invalid input, program will be terminated");
tester = false;
}
result = x / y;
} else if (tester) {
result = x / y;
}
break;
case 5:
result = Math.pow(x, y);
break;
case 6:
result = Math.sqrt(x);
break;
case 7:
// store a number
break;
case 8:
// recall a stored number
break;
case 9:
result = 0;
break;
default:
}
return result;
}
}
my question is short and sweet. I do not understand why my program infinitely loops when catching an error. I made a fresh try-catch statement but it looped and even copied, pasted and modified the appropriate variables from a previous program that worked. Below is the statement itself and below that will be the entire program. Thank you for your help!
try {
input = keyboard.nextInt();
}
catch(Exception e) {
System.out.println("Error: invalid input");
again = true;
}
if (input >0 && input <=10)
again = false;
}
Program:
public class Blanco {
public static int input;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
nameInput();
}
/**
*
* #param name
*/
public static void nameInput() {
System.out.println("What is the name of the cartoon character : ");
Scanner keyboard = new Scanner(System.in);
CartoonStar star = new CartoonStar();
String name = keyboard.next();
star.setName(name);
typeInput(keyboard, star);
}
public static void typeInput(Scanner keyboard, CartoonStar star) {
boolean again = true;
while(again){
System.out.println("What is the cartoon character type: 1 = FOX,2 = CHICKEN,3 = RABBIT,4 = MOUSE,5 = DOG,\n"
+ "6 = CAT,7 = BIRD,8 = FISH,9 = DUCK,10 = RAT");
try {
input = keyboard.nextInt();
}
catch(Exception e) {
System.out.println("Error: invalid input");
again = true;
}
if (input >0 && input <=10)
again = false;
}
switch (input) {
case 1:
star.setType(CartoonType.FOX);
break;
case 2:
star.setType(CartoonType.CHICKEN);
break;
case 3:
star.setType(CartoonType.RABBIT);
break;
case 4:
star.setType(CartoonType.MOUSE);
break;
case 5:
star.setType(CartoonType.DOG);
break;
case 6:
star.setType(CartoonType.CAT);
break;
case 7:
star.setType(CartoonType.BIRD);
break;
case 8:
star.setType(CartoonType.FISH);
break;
case 9:
star.setType(CartoonType.DUCK);
break;
case 10:
star.setType(CartoonType.RAT);
break;
}
popularityNumber(keyboard, star);
}
public static void popularityNumber(Scanner keyboard, CartoonStar star) {
System.out.println("What is the cartoon popularity number?");
int popularity = keyboard.nextInt();
star.setPopularityIndex(popularity);
System.out.println(star.getName() + star.getType() + star.getPopularityIndex());
}
}
Your program runs forever because calling nextInt without changing the state of the scanner is going to cause an exception again and again: if the user did not enter an int, calling keyboard.nextInt() will not change what the scanner is looking at, so when you call keyboard.nextInt() in the next iteration, you'll get an exception.
You need to add some code to read the garbage the user entered after servicing an exception to fix this problem:
try {
...
} catch(Exception e) {
System.out.println("Error: invalid input:" + e.getMessage());
again = true;
keyboard.next(); // Ignore whatever is entered
}
Note: you do not need to rely on exceptions in this situation: rather than calling nextInt(), you could call hasNextInt(), and check if the scanner is looking at an integer or not.
Okay, first off I am very, very new to java. For this project I need to design a program that takes a product number, an amoutn sold, calculates the total, and then displays it. However, I need to to display when I select option 2, which is a seperate private class, to be honest I don't even know where to begin. Any help would be appreciated.
import java.util.Scanner;
public class Attempt1
{
//method to pause until a key is pressed
public static void pause()
{
try
{
System.out.print("Press <Enter> to continue...");
System.in.read();
}
catch (Exception e)
{
System.err.printf("Error %s%c\n",e.getMessage(),7);
}
}//end pause
public static void main(String[] args)
{
//variables to capture keyboard input
Scanner keyBd = new Scanner( System.in );
char selection;
//int selection;
do{//display menu
System.out.println("\n--------------");
System.out.println("Retail Sales\n");
System.out.println("1. Enter Products Sold");
System.out.println("2. Display Total Retail Sales");
System.out.println("3. Exit\n");
System.out.print ("Selection: ");
//get menu selection
selection = keyBd.next().charAt(0);
//selection = keyBd.nextInt();
//process menu selection
switch (selection){
case '1':
enterProducts();
break;
case '2':
displaySales();
break;
case '3':
//recognize as valid selection but do nothing
break;
default :
//System.out.printf("%c\n",7);
System.out.println("Invalid Selection");
}//end switch
}while( selection != '3');
}//end main()
private static void enterProducts()
{
Scanner inp = new Scanner(System.in);
int product,quantity;
double total = 0.00;
System.out.print("Enter product #(1-5)(0 to stop): ");
product=inp.nextInt();
while(product !=0)
{
System.out.print("Enter quantity: ");
quantity=inp.nextInt();
switch( product ){
case 1:total+=quantity*2.98;
break;
case 2:total+=quantity*4.50;
break;
case 3:total+=quantity*3.98;
break;
case 4:total+=quantity*4.49;
break;
case 5:total+=quantity*6.87;
break;
default:System.out.println("Invalid Product Number");
System.out.println("Product Number Does not Exist");
if(product<0 && product>=6)
{
System.out.print("Enter product #(1-5)(0 to stop): ");
product=inp.nextInt();
System.out.print("Enter quantity: ");
quantity=inp.nextInt();
}
break;
}
System.out.print("Enter product #(1-5)(0 to stop): ");
product=inp.nextInt();
}
pause();
}
private static void displaySales()
{
System.out.println( "The total retail value was: " + total );
pause();
}
}//end MenuDemo
Here is an algorithm for improving your code:
At the beginning of your your main add a variable total and initialize it with 0: double total=0;
Change the enterProducts method's return type to double: private static double enterProducts() and return the local variable total at the end from this method after the call to pause: return total;
In the case for the input of 1 add the returned value from enterProducts to the current value of total (it's the total inside your main): total += enterProducts();
Add to the method displaySales an double argument: private static void displaySales(double total) and change the call to it in the main's case for 2 to displaySales(total);
I think you mean private method. You could pass the total like so:
private static void displaySales(double total) {
...
total is defined in enterProducts but not in the main method where the loop is displayed, so you could return this:
double enterProducts() {
...
return total;
}
so that you can pass it to displaySales.
The problem with the code is that you're trying to access a local variable, declared in the static enterProducts() method, inside of the static displaySales() method.
The code below solves that "problem".
With that being said, I recommend that you work through some Java tutorials to understand why the code now works... Have a look at Variable Scope.
public class Attempt1
{
//use a static variable to store the total
static double total = 0.00;
//method to pause until a key is pressed
public static void pause()
{
try
{
System.out.print("Press <Enter> to continue...");
System.in.read();
}
catch (Exception e)
{
System.err.printf("Error %s%c\n",e.getMessage(),7);
}
}//end pause
public static void main(String[] args)
{
//variables to capture keyboard input
Scanner keyBd = new Scanner( System.in );
char selection;
//int selection;
do{//display menu
System.out.println("\n--------------");
System.out.println("Retail Sales\n");
System.out.println("1. Enter Products Sold");
System.out.println("2. Display Total Retail Sales");
System.out.println("3. Exit\n");
System.out.print ("Selection: ");
//get menu selection
selection = keyBd.next().charAt(0);
//selection = keyBd.nextInt();
//process menu selection
switch (selection){
case '1':
enterProducts();
break;
case '2':
displaySales();
break;
case '3':
//recognize as valid selection but do nothing
break;
default :
//System.out.printf("%c\n",7);
System.out.println("Invalid Selection");
}//end switch
}while( selection != '3');
}//end main()
private static void enterProducts()
{
Scanner inp = new Scanner(System.in);
int product,quantity;
System.out.print("Enter product #(1-5)(0 to stop): ");
product=inp.nextInt();
while(product !=0)
{
System.out.print("Enter quantity: ");
quantity=inp.nextInt();
switch( product ){
case 1:total+=quantity*2.98;
break;
case 2:total+=quantity*4.50;
break;
case 3:total+=quantity*3.98;
break;
case 4:total+=quantity*4.49;
break;
case 5:total+=quantity*6.87;
break;
default:System.out.println("Invalid Product Number");
System.out.println("Product Number Does not Exist");
if(product<0 && product>=6)
{
System.out.print("Enter product #(1-5)(0 to stop): ");
product=inp.nextInt();
System.out.print("Enter quantity: ");
quantity=inp.nextInt();
}
break;
}
System.out.print("Enter product #(1-5)(0 to stop): ");
product=inp.nextInt();
}
pause();
}
private static void displaySales()
{
System.out.println( "The total retail value was: " + total );
pause();
}
}//end MenuDemo