Calling a method to try and rerun through a block of code - java

I'm trying to compare the cost of a user's phone usage under plans from three
different providers. I can get as far as entering the usage details but once entered I try to call the method to rerun from the if statement but it just displays the main menu again and stops. I want it to run through the entire if statement from the start again
import java.util.Scanner;
public class MainMenuSelection {
public static int menuSel() {
int menuSel ;
System.out.println("ENTER USAGE DETAILS MENU\n");
System.out.println("Please select an option from the menu:");
System.out.println("1.Phone Call");
System.out.println("2.SMS ");
System.out.println("3.Data usage");
System.out.println("4. Return to main menu");
Scanner in = new Scanner(System.in);
System.out.println("Enter selection: ");
menuSel = in.nextInt();
while (menuSel < 1 || menuSel >4){
System.out.println("Value must bebetween 1 and 4, plese try again.");
System.out.println("Enter your selection: ");
menuSel = in.nextInt();
}
return menuSel;
}
public static int mainMenuSelection() {
System.out.println("MAIN MENU\n");
System.out.println("Please select from the menu:");
System.out.println("1. Enter Usage details");
System.out.println("2. Display Cost under provider 1");
System.out.println("3. Display Cost under provider 2");
System.out.println("4. Display Cost under provider 3");
System.out.println("5. Clear usage details");
System.out.println("6. Exit System");
int mainMenuSelection;
Scanner userInput = new Scanner(System.in);
System.out.println("Enter your selection: ");
mainMenuSelection = userInput.nextInt();
//return mainMenuSelection;
while (mainMenuSelection < 1 || mainMenuSelection >6){
System.out.println("Value must bebetween 1 and 6, plese try again.");
System.out.println("Enter your selection: ");
mainMenuSelection = userInput.nextInt();
}
System.out.println("You chose selection " + mainMenuSelection + "\n");
return mainMenuSelection;
}
public static void main(String[] args) {
System.out.println("Hello World!");
int callLength = 0;
int numSMS = 0;
int numberOfMB = 0;
int numberofCalls;
int callTime;
int totalcallTime = 0;
int mainMenuSelection = mainMenuSelection();
if (mainMenuSelection == 1) {
int menuSel = menuSel();
if (menuSel == 1) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of phone call you have made? ");
numberofCalls = in.nextInt();
for (int i = 0; i < numberofCalls; i++) {
Scanner callInput = new Scanner(System.in);
System.out.println("How long was the call in seconds?");
callTime = callInput.nextInt();
totalcallTime = callTime + totalcallTime;
}
System.out.println("Your total number of calls is " + numberofCalls);
System.out.println("Your total call time is " + totalcallTime + " seconds" + "\n");
} else if (menuSel == 2) {
System.out.println("Enter the number of SMS messages: ");
//int numSMS;
Scanner userNumSMS = new Scanner(System.in);
numSMS = userNumSMS.nextInt();
System.out.println("Your number of SMSs is " + numSMS + "\n");
} else if (menuSel == 3) {
System.out.println("Enter the amount of data in MB: ");
//int numberOfMB;
Scanner userNumMB = new Scanner(System.in);
numberOfMB = userNumMB.nextInt();
System.out.println("Your amount of data in MB is " + numberOfMB + "\n");
} else {
mainMenuSelection(); // go back to main menu
}
} else if (mainMenuSelection == 2) {
//Display cost under provider 1
double callCost = 0.03 * totalcallTime;
double smsCost = 0.10 * numSMS;
double dataCost = 0.02 * numberOfMB;
double totalCostProvider1 = callCost + smsCost + dataCost;
System.out.println(totalCostProvider1);
} else if (mainMenuSelection == 3) {
//Display cost under provider 2
double callCost2 = 0.04 * totalcallTime;
double smsCost2 = 0.12 * numSMS;
double dataCost2 = 0.04 * numberOfMB;
double totalCostProvider2 = callCost2 + smsCost2 + dataCost2;
System.out.println(totalCostProvider2);
} else if (mainMenuSelection == 4) {
//Display cost under provider 3
double callCost3 = 0.05 * totalcallTime;
double smsCost3 = 0.11 * numSMS;
double dataCost3 = 0.03 * numberOfMB;
double totalCostProvider3 = callCost3 + smsCost3 + dataCost3;
System.out.println(totalCostProvider3);
} else if (mainMenuSelection == 5) {
//clear usage details
} else {
System.out.println("Exiting System");
System.exit(0);
}
mainMenuSelection = mainMenuSelection();
}
}

Codes run from top to bottom. Therefore, after the int mainMenuSelection = mainMenuSelection(); and the if-else statement is run, the code would run once again for the mainMenuSelection = mainMenuSelection() and ends, as there is nothing left in the block.
A fairly simple solution would be using a while or do-while loop with a boolean checking if the user entered the number 6 to exit the system.
You can try this example:
public static void main(String[] args) {
/*
* Your variables here
*/
boolean isExit = false;
while(!isExit) {
int mainMenuSelection = mainMenuSelection();
if (mainMenuSelection == 1) {
// menuSel codes here
} else if (mainMenuSelection == 2) {
// Display cost under provider 1
} else if (mainMenuSelection == 3) {
// Display cost under provider 2
} else if (mainMenuSelection == 4) {
// Display cost under provider 3
} else if (mainMenuSelection == 5) {
// Clear usage details
} else {
System.out.println("Exiting System");
isExit = true;
}
}
Hopes this answer helps you well.

It looks like you need a loop. Your main method has an exit condition so you can essentially loop forever by wrapping the code in your main method with a while loop:
public static void main(String[] args) {
while(true) {
// your main method code in here
}
}

By the way, you need to edit your code above in good formatting.
I have added a while loop in your main. Also, whenever any unwanted number the loop will exit using a break; and that in turn stops the program.
mainMenuSelection = mainMenuSelection();
I have deleted the above line from the code so you just need to call it once at the beginning of the code.
Let me know if you need sth else!
import java.util.Scanner;
public class MainMenuSelection {
public static int menuSel() {
int menuSel;
System.out.println("ENTER USAGE DETAILS MENU\n");
System.out.println("Please select an option from the menu:");
System.out.println("1.Phone Call");
System.out.println("2.SMS ");
System.out.println("3.Data usage");
System.out.println("4. Return to main menu");
Scanner in = new Scanner(System.in);
System.out.println("Enter selection: ");
menuSel = in.nextInt();
while (menuSel < 1 || menuSel > 4) {
System.out.println("Value must bebetween 1 and 4, plese try again.");
System.out.println("Enter your selection: ");
menuSel = in.nextInt();
}
return menuSel;
}
public static int mainMenuSelection() {
System.out.println("MAIN MENU\n");
System.out.println("Please select from the menu:");
System.out.println("1. Enter Usage details");
System.out.println("2. Display Cost under provider 1");
System.out.println("3. Display Cost under provider 2");
System.out.println("4. Display Cost under provider 3");
System.out.println("5. Clear usage details");
System.out.println("6. Exit System");
int mainMenuSelection;
Scanner userInput = new Scanner(System.in);
System.out.println("Enter your selection: ");
mainMenuSelection = userInput.nextInt();
//return mainMenuSelection;
while (mainMenuSelection < 1 || mainMenuSelection > 6) {
System.out.println("Value must bebetween 1 and 6, plese try again.");
System.out.println("Enter your selection: ");
mainMenuSelection = userInput.nextInt();
}
System.out.println("You chose selection " + mainMenuSelection + "\n");
return mainMenuSelection;
}
public static void main(String[] args) {
int callLength = 0;
int numSMS = 0;
int numberOfMB = 0;
int numberofCalls;
int callTime;
int totalcallTime = 0;
while (true) {
int mainMenuSelection = mainMenuSelection();
if (mainMenuSelection == 1) {
int menuSel = menuSel();
if (menuSel == 1) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of phone call you have made? ");
numberofCalls = in.nextInt();
for (int i = 0; i < numberofCalls; i++) {
Scanner callInput = new Scanner(System.in);
System.out.println("How long was the call in seconds?");
callTime = callInput.nextInt();
totalcallTime = callTime + totalcallTime;
}
System.out.println("Your total number of calls is " + numberofCalls);
System.out.println("Your total call time is " + totalcallTime + " seconds" + "\n");
} else if (menuSel == 2) {
System.out.println("Enter the number of SMS messages: ");
//int numSMS;
Scanner userNumSMS = new Scanner(System.in);
numSMS = userNumSMS.nextInt();
System.out.println("Your number of SMSs is " + numSMS + "\n");
} else if (menuSel == 3) {
System.out.println("Enter the amount of data in MB: ");
//int numberOfMB;
Scanner userNumMB = new Scanner(System.in);
numberOfMB = userNumMB.nextInt();
System.out.println("Your amount of data in MB is " + numberOfMB + "\n");
}
} else if (mainMenuSelection == 2) {
//Display cost under provider 1
double callCost = 0.03 * totalcallTime;
double smsCost = 0.10 * numSMS;
double dataCost = 0.02 * numberOfMB;
double totalCostProvider1 = callCost + smsCost + dataCost;
System.out.println(totalCostProvider1);
} else if (mainMenuSelection == 3) {
//Display cost under provider 2
double callCost2 = 0.04 * totalcallTime;
double smsCost2 = 0.12 * numSMS;
double dataCost2 = 0.04 * numberOfMB;
double totalCostProvider2 = callCost2 + smsCost2 + dataCost2;
System.out.println(totalCostProvider2);
} else if (mainMenuSelection == 4) {
//Display cost under provider 3
double callCost3 = 0.05 * totalcallTime;
double smsCost3 = 0.11 * numSMS;
double dataCost3 = 0.03 * numberOfMB;
double totalCostProvider3 = callCost3 + smsCost3 + dataCost3;
System.out.println(totalCostProvider3);
} else if (mainMenuSelection == 5) {
//clear usage details
} else {
System.out.println("Exiting System");
System.exit(0);
break;
}
}
}
}

Related

How do you create a continuous loop for a Coin tossing game in Java?

I am having issues trying to make my code loop back and do the program over again until the user asks them to stop by inputting zero. I have tried a while statement but I am not sure if I implemented it correctly since all I got back was errors. I appreciate any and all the help that can be given. I have included my code below.
public class CoinTossing {
public static void main(String[] args) {
//Scanner method
Scanner input = new Scanner(System.in);
int choice;
System.out.println("Welcome to the Coin Toss Program.");
//Variables for the count of heads and tails.
int headCount = 0;
int tailCount = 0;
System.out.println("How many coin flips do you want to do?");
int number = input.nextInt();
for (int i = 1; i <= number; i++) {
Random rand = new Random();
// Simulate the coin tosses.
for (int count = 0; count < number; count++) {
if (rand.nextInt(2) == 0) {
tailCount++;
} else {
headCount++;
}
}
System.out.println("Times head was flipped:" + headCount);
System.out.println("Times tail was flipped:" + tailCount);
return;
}
}
}
Your main method could look something like this:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Coin Toss Program.");
//Variables for the count of heads and tails.
while (true) {
int headCount = 0;
int tailCount = 0;
System.out.println("How many coin flips do you want to do?");
int number = input.nextInt();
if (number == 0) { break; }
Random rand = new Random();
// Simulate the coin tosses.
for (int i = 0; i < number; i++) {
if (rand.nextInt(2) == 0) {
tailCount++;
} else {
headCount++;
}
}
System.out.println("Times head was flipped:" + headCount);
System.out.println("Times tail was flipped:" + tailCount);
}
}
Here, the while loop is entered after the welcome message and will only exit the simulation when the user inputs a 0.
After the user input is retrieved, it will check if the user input 0. If the user inputs 0, it will break the while loop before the program simulates flipping the coin:
if (number == 0) { break; }
Place your code into a while loop with the exception of these two lines:
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Coin Toss Program.");
At the end of the Coin Toss Game the natural order of things would be to ask the User if he/she wants to play again. This allows the User to quit the application rather than being stuck in a continuous loop:
String yn = "y";
while (yn.equalsIgnoreCase("y")) {
int headCount = 0;
int tailCount = 0;
int number = 0;
String num = null;
while (num == null) {
System.out.print("How many coin flips do you want to do? --> ");
num = input.nextLine();
if (!num.matches("\\d+")) {
System.err.println("Invalid Integer Number Supplied ("
+ num + ")! Try Again...");
System.out.println();
num = null;
}
}
number = Integer.valueOf(num);
// Simulate the coin tosses.
for (int i = 1; i <= number; i++) {
if (rand.nextInt(2) == 0) {
tailCount++;
}
else {
headCount++;
}
}
System.out.println("Times head was flipped:" + headCount);
System.out.println("Times tail was flipped:" + tailCount);
System.out.println();
while (yn.equalsIgnoreCase("y")) {
System.out.print("Do you want to play again? (y/n) --> ");
yn = input.nextLine();
if (yn.matches("[yYnN]")) {
System.out.println();
break;
}
else {
System.err.println("Invalid response (" + yn + ")! 'y' or 'n' only!");
System.out.println();
yn = "y";
}
}
}
The whole application may look something like this:
public class CoinTossing {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
java.util.Random rand = new java.util.Random();
System.out.println("Welcome to the Coin Toss Program");
System.out.println("================================");
System.out.println();
String yn = "y";
while (yn.equalsIgnoreCase("y")) {
int headCount = 0;
int tailCount = 0;
int number = 0;
String num = null;
while (num == null) {
System.out.print("How many coin flips do you want to do? --> ");
num = input.nextLine();
if (!num.matches("\\d+")) {
System.err.println("Invalid Integer Number Supplied ("
+ num + ")! Try Again...");
System.out.println();
num = null;
}
}
number = Integer.valueOf(num);
// Simulate the coin tosses.
for (int i = 1; i <= number; i++) {
if (rand.nextInt(2) == 0) {
tailCount++;
}
else {
headCount++;
}
}
System.out.println("Times head was flipped:" + headCount);
System.out.println("Times tail was flipped:" + tailCount);
System.out.println();
while (yn.equalsIgnoreCase("y")) {
System.out.print("Do you want to play again? (y/n) --> ");
yn = input.nextLine();
if (yn.matches("[yYnN]")) {
System.out.println();
break;
}
else {
System.err.println("Invalid response (" + yn + ")! 'y' or 'n' only!");
System.out.println();
yn = "y";
}
}
}
}
}

How can I quit the game whenever e is pressed at any time?

If someone presses e, I want my game to stop at any time in the game.
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int points = 0;
int multiply;
System.out.println("press e to exit the game at any time! ");
System.out.println("please enter a number");
int yourNumber = input.nextInt();
for (multiply = 0; multiply<= 10; multiply++){
int yourAnswer = yourNumber * multiply;
System.out.println(yourNumber + " x " + multiply + " = ? ");
int theAnswer = input.nextInt();
for (int tries = 1; tries<= 4; tries++){
if (theAnswer == yourAnswer){
points = points + 5;
System.out.println("you have " + points + " points");
break;
}
else{
System.out.println("Your answer : " + theAnswer + " is wrong, please try again. Attempts : " + tries + " out of 4");
theAnswer = input.nextInt();
points--;
if (tries == 4){
System.out.println("sorry maximum attempts!!! moving to the next question");
tries++;
break;
}
}
}
}
}
}
Instead of just "int theAnswer = input.nextInt();" write this:
String nextIn = input.next();
int theAnswer = 0;
if (nextIn.equal("e")) {
System.out.println("Exiting the game...")
break;
}
else {
theAnswer = Integer.parseInt(nextIn);
}
I obviously haven't accounted for exceptions, but you can if you want.
So altogether it looks like this:
public class Game{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int points = 0;
int multiply;
System.out.println("press e to exit the game at any time!");
System.out.println("please enter a number");
int yourNumber = input.nextInt();
for (multiply = 0; multiply<= 10; multiply++){
int yourAnswer = yourNumber * multiply;
System.out.println(yourNumber + " x " + multiply + " = ? ");
//new part:
String nextIn = input.next();
int theAnswer = 0;
if (nextIn.equals("e")) {
System.out.println("Exiting the game...")
break;
} else {
theAnswer = Integer.parseInt(nextIn);
}
for (int tries = 1; tries<= 4; tries++){
if (theAnswer == yourAnswer){
points = points + 5;
System.out.println("you have " + points + " points");
break;
}
else{
System.out.println("Your answer : " + theAnswer + " is wrong, please try again. Attempts : " + tries + " out of 4");
theAnswer = input.nextInt();
points--;
if (tries == 4){
System.out.println("sorry maximum attempts!!! moving to the next question");
tries++;
break;
}
}
}
}
}
}

redirect a loop within a loop for only "else"

I'm a total beginner and am working on a practice assignment. I need to be able to re-print the same addition problem if the user has answered incorrectly, but I'm not sure how to do that. All my attempts have lead to a new random addition problem appearing or adding another new random to the original, which is also not desired. I'm sure it's simple, but I am lost. Thanks in advance for any tips!
package ov3uppgift8;
import java.util.Scanner;
import java.util.Random;
public class Ov3uppgift8 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random ();
System.out.println("*****************");
System.out.println("* MATH TRAINING *");
System.out.println("*****************");
System.out.println("Enter 0 to close program.");
int ans;
do {
int a = rand.nextInt(10) + 1;
int b = rand.nextInt(10) + 1;
System.out.print(a + " + " + b +" = ");
ans = input.nextInt();
if (ans==(a+b)) {
System.out.println("CORRECT!");
} else if (ans==0) {
System.out.println("Good bye!");
} else if (ans!=(a+b)) {
System.out.println("Incorrect, try again.");
}
} while (ans!=0);
}
}
Just simplify your code a little bit, don't overthink. You generate answers every time you get into the loop, generate your numbers outside so they stay consistent, also, a do-while, isn't necessary, just break your loop if the answer is correct or they placed 0. Also, you need to make sure that the user entered a number, so a try-catch should be placed while getting the input.
Scanner input = new Scanner(System.in);
Random rand = new Random ();
System.out.println("*****************");
System.out.println("* MATH TRAINING *");
System.out.println("*****************");
System.out.println("Enter 0 to close program.");
int a = rand.nextInt(10) + 1;
int b = rand.nextInt(10) + 1;
int ans;
while (true) {
System.out.printf("%d + %d = ?%n", a, b);
try {
ans = Integer.parseInt(input.next());
} catch (NumberFormatException e) {
System.out.println("Please enter a number!");
continue;
}
if (ans == 0) {
System.out.println("Goodbye!");
break;
} else if (ans == a + b) {
System.out.println("Correct!");
break;
} else {
System.out.println("Incorrect!");
}
}
Please see modification inline:
package ov3uppgift8;
import java.util.Scanner;
import java.util.Random;
public class Ov3uppgift8 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random ();
System.out.println("*****************");
System.out.println("* MATH TRAINING *");
System.out.println("*****************");
System.out.println("Enter 0 to close program.");
int ans;
do
{
int a = rand.nextInt(10) + 1;
int b = rand.nextInt(10) + 1;
System.out.print(a + " + " + b +" = ");
ans = input.nextInt();
if (ans==(a+b))
{
System.out.println("CORRECT!");
}
else if (ans==0)
{
System.out.println("Good bye!");
}
else if (ans!=(a+b))
{
// here you keep asking the user over and over
//until they give the right result
do{
System.out.println("Incorrect, try again.");
//show again the equation to the user
System.out.print(a + " + " + b +" = ");
ans = input.nextInt();
}while(ans!=(a+b));
}
}
while (ans!=0);
}
}
Use this simple source code and similar to you (minor change):
try (Scanner input = new Scanner(System.in)) {
Random rand = new Random();
System.out.println("*****************");
System.out.println("* MATH TRAINING *");
System.out.println("*****************");
System.out.println("Enter 0 to close program.");
int ans, a, b;
ans = a = b = 0;
do {
a = rand.nextInt(10) + 1;
b = rand.nextInt(10) + 1;
System.out.print(a + " + " + b + " = ");
try{
//Getting input as String and casting to Integer
ans = Integer.parseInt(input.nextLine());
if (ans == 0) {
System.out.println("Good bye!");
} else if (ans == (a + b)) {
System.out.println("CORRECT!");
} else if (ans != (a + b)) {
System.out.println("Incorrect, try again.");
}
}catch (NumberFormatException nfe){
System.out.println(nfe);
}
} while (ans != 0);
}
class generateNum{
Random rand = new Random ();
int a=rand.nextInt(10)+1;
int b=rand.nextInt(10)+1;
public void generate(){
System.out.print(a + " + " + b +" = ");
}
public int getsum(){
return a+b;
}
}
public class Test02 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("*****************");
System.out.println("* MATH TRAINING *");
System.out.println("*****************");
System.out.println("Enter 0 to close program.");
int ans;
generateNum gnum = new generateNum();
gnum.generate();
ans = input.nextInt();
int com=gnum.getsum();
do
{
if (ans==com)
{
System.out.println("CORRECT!");
gnum = new generateNum();
gnum.generate();
ans = input.nextInt();
com=gnum.getsum();
}
else if (ans==0)
{
System.out.println("Good bye!");
}
else if (ans!=com)
{
System.out.println("Incorrect, try again.");
gnum.generate();
ans = input.nextInt();
}
}
while (ans!=0);
}
}
There are few changes in your condition. Update your else-if(ans!=(a+b)) block.
import java.util.Random;
import java.util.Scanner;
public class Test2 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Random rand = new Random ();
System.out.println("*****************");
System.out.println("* MATH TRAINING *");
System.out.println("*****************");
System.out.println("Enter 0 to close program.");
int ans;
do
{
int a = rand.nextInt(10) + 1;
int b = rand.nextInt(10) + 1;
System.out.print(a + " + " + b +" = ");
ans = input.nextInt();
if (ans==(a+b))
{
System.out.println("CORRECT!");
}
else if (ans==0)
{
System.out.println("Good bye!");
}
else if (ans!=(a+b))
{
boolean flag = false;
do{
System.out.println("Incorrect, try again.(0 for skip)");
int againAns = input.nextInt();
if(againAns == (a+b)){
System.out.println("CORRECT!");
flag = true;
}else if(againAns == 0){
System.out.println("You skip the answer..");
flag = true;
}
}while(flag != true);
}
}while (ans!=0);
}
}

I need help getting the user to enter 10 currencies instead of 1

I have got the code below that when the user Enters 1-5 from the keyboard it converts GBP to one of the selected currencies. At the moment it takes 1 user input and converts it, but I need it too take 10 user inputs and convert all 10 to the currency the user selects. I believe a for loop is needed something like
for( int i = 0; i < 10; i++ )
is needed. Can anyone help??
Here is the code I have so far:
public class test {
public static void main(String[] args) {
currency();
}
public static void currency(){
int input;
#SuppressWarnings("resource")
Scanner keyboard = new Scanner(System.in);
System.out.println("1. Euros");
System.out.println("2. USD ");
System.out.println("3. Yen");
System.out.println("4. Rupees");
System.out.println("5. Exit ?");
input = keyboard.nextInt();
if(input == 1){
float XEUR = (float) 1.19;
System.out.println("Enter 10 GBP values to be converted to EUR:");
System.out.println("EUR: " + keyboard.nextFloat() * XEUR);
}else if(input == 2){
float XUSD = (float) 1.26;
System.out.println("Enter 10 GBP values to be converted to USD:");
System.out.println("USD: " + keyboard.nextFloat() * XUSD);
} else if (input == 3){
float XYEN = (float) 145.02;
System.out.println("Enter 10 GBP values to be converted to Yen:");
System.out.println("YEN: " + keyboard.nextFloat() * XYEN);
}else if(input == 4){
float XRUP = (float) 84.86;
System.out.println("Enter 10 GBP values to be converted to Rupees:");
System.out.println("USD: " + keyboard.nextFloat() * XRUP);
}else if(input == 5){
System.out.println("Exiting");
}
}
}
You can store all the inputs in array and process like this:
int input = keyboard.nextInt();
if (input < 1 || input > 5) {
System.out.println("Invalid input");
return;
}
if (input == 5) {
System.out.println("Exiting");
return;
}
float[] vals = new float[10];
for(int i=0; i<10;i++) {
System.out.println("Enter "+ (i+1) +" value");
vals[i] = keyboard.nextFloat();
}
switch(input) {
case 1:
// process the vals in loop:
for(int v : vals) {
// do conversion here
}
break;
// handle other cases
}

Getting Java to recognize user input

I'm trying to make a virtual store program. Synopsis is if at any time the user enters 'q', the program should quit.
Once the user enters 'c', ask the user to enter a 2-character state such as CA, NV, WA. If a code other
than these three is entered, it falls under "other". Then display what is in their cart and the calculated
total price based on discounts and include the tax.
The problem is that the program would ask user for item and quantity once, then it goes into checkout mode. Whenever I put 'q', it goes to the next line.
Here is the code:
import java.util.Scanner;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Random;
import java.io.*;
public class virtualStore {
public static void main(String [] args) throws IOException{
/* If the user enters an item number, the program should ask the user to enter how many of that item
they want, and then print the menu again. If at any time the user enters 'q', the program should quit.
Once the user enters 'c', ask the user to enter a 2-character state such as CA, NV, WA. If a code other
than these three is entered, it falls under "other". Then display what is in their cart and the calculated
total price based on discounts and include the tax. You should use the Math.round() and
System.out.printf methods to round numbers and to display to 2 decimal places. */
Scanner keyboard = new Scanner (System.in);
String input;
char c = ' ';
char q = ' ';
//tax rates
double CAtaxRate = .09;
double NVtaxRate = .07;
double WAtaxRate = .065;
double other = .06;
double tax = 0;
//checkout
double checkout = 0;
double total;
double cash = 0;
double change = 0;
//items
double mushrooms = 0.3;
double onions = 0.6;
double watermelon = 2.5;
double cookies = 1;
int item = 0;
//number of items
int numMushrooms = 0;
int numOnions = 0;
int numWatermelon = 0;
int numCookies = 0;
DecimalFormat dollar = new DecimalFormat("#,##0.00");
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to Alex's Store."
+ " Here is the menu. "
+ "\nEnter the item number to add it to your cart,"
+ " enter \'c\' to checkout or \'q\' to quit. ");
while(true)
//while(c != 'c' && c != 'q')
{
for (item = 1; item < 4; item ++){
System.out.println("Item\t\t\tPrice\t\t\tQuantity");
System.out.println("---------------------------------------------------------");
System.out.println("1. Mushrooms\t\t($0.30/$0.25)\t\t" + numMushrooms);
System.out.println("2. Onions\t\t($0.60/$0.50)\t\t" + numOnions );
System.out.println("3. Watermelon\t\t($2.50/$2.00)\t\t" + numWatermelon);
System.out.println("4. Cookies\t\t($1.00/$0.75)\t\t" + numCookies);
System.out.println("---------------------------------------------------------");
System.out.println("Enter item number between 1 through 4");
System.out.println("or enter 'c' for checkout or 'q' for quit.");
input = keyboard.nextLine();
item = Integer.parseInt(input);
if (input.equals("1"))
{
System.out.println("Enter how many items you want.");
String m = keyboard.nextLine();
numMushrooms = Integer.parseInt(m);
}
else if (input.equals("2"))
{
System.out.println("Enter how many items you want.");
String o = keyboard.nextLine();
numOnions = Integer.parseInt(o);
}
else if (input.equals("3"))
{
System.out.println("Enter how many items you want.");
String w = keyboard.nextLine();
numWatermelon = Integer.parseInt(w);
}
else if(input.equals("4"))
{
System.out.println("Enter how many items you want.");
String co = keyboard.nextLine();
numCookies = Integer.parseInt(co);
}
}
if (numMushrooms > 10)
{
mushrooms = 0.25;
}
else if (numOnions > 10)
{
onions = 0.5;
}
else if (numWatermelon > 10)
{
watermelon = 2;
}
else if (numCookies > 10)
{
cookies = .75;
}
// quit option
String quit = scanner.nextLine();
q = quit.charAt(0);
if (quit.equalsIgnoreCase("q"))
{
System.out.println("Goodbye");
scanner.close();
System.exit(0);
}
// checkout option
String ch = scanner.nextLine();
c = ch.charAt(0);
if (ch.equalsIgnoreCase("c"))
{
//checkout
checkout = numMushrooms * mushrooms + numOnions * onions + numWatermelon * watermelon + numCookies * cookies;
//tax
total = tax * checkout + checkout;
System.out.print("Enter state abbreviations: ");
input = keyboard.nextLine();
PrintWriter outputfile = new PrintWriter("receipt.txt");
outputfile.println("Your cart: ");
outputfile.println("Sub total:$ " + dollar.format(checkout));
if (input.equalsIgnoreCase("CA"))
{
total = CAtaxRate * checkout + checkout;
outputfile.println("Tax Rate: " + CAtaxRate);
outputfile.println("Tax: $" + dollar.format(CAtaxRate * checkout));
outputfile.println("Total is: $" + dollar.format(total));
}
else if (input.equalsIgnoreCase("NV"))
{
total = NVtaxRate * checkout + checkout;
outputfile.println("Tax Rate: " + NVtaxRate);
outputfile.println("Tax: $" + dollar.format(NVtaxRate * checkout));
outputfile.println("Total is: $" + dollar.format(total));
}
else if (input.equalsIgnoreCase("WA"))
{
total = WAtaxRate * checkout + checkout;
outputfile.println("Tax Rate: " + WAtaxRate);
outputfile.println("Tax: $" + dollar.format(WAtaxRate * checkout));
outputfile.println("Total is: $" + dollar.format(total));
}
else if (input.equalsIgnoreCase(input))
{
total = other * checkout + checkout;
outputfile.println("Tax Rate: " + other);
outputfile.println("Tax: $" + dollar.format(other * checkout));
outputfile.println("Total is: $" + dollar.format(total));
}
outputfile.println("-----------------------------------------------------");
input = keyboard.nextLine();
cash = Integer.parseInt(input);
outputfile.println("Enter amount of cash: $" + dollar.format(cash));
change = cash - total;
outputfile.println("Change due: $" + dollar.format(change));
outputfile.println("Thank you for shopping at Alex's store!");
outputfile.close();
FileWriter fw = new FileWriter("receipt.text", true);
PrintWriter pw = new PrintWriter(fw);
pw.println("C:\\Desktop\\Receipt.txt ");
pw.close();
}
}
}
}
You're using the wrong model to get user input.
Try doing something that looks like:
while(true) {
// Print the menu messages
String input = scanner.readLine();
if(input.equals("c")) {
// Read in and handle state abbreviation
} else if(input.equals("q")) {
System.exit(0);
} else {
int itemNumber = Integer.parseInt(input);
// Parse and handle item number
}
}

Categories

Resources