Java switch results (needing to print the values) - java

I cannot figure this out, I have created a switch in Java for a user to enter specific details. I have created a print statement inside the case to print the result that has been entered. What I want to happen is for a separate print statement to display the combined details of the values entered (after say a few loops). Any help will be greatly appreciated.
Thanks in advance.
Here is my code
import java.util.Scanner;
public class Stage3Check {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Setup an exit statement
boolean quit = false;
while (!quit){
System.out.println("Enter one of the following commands:");
System.out.println("1 - Damage Repair");
System.out.println("2 - Traffic Infringement");
System.out.println("3 - Exit Menu");
int choiceEntry = Integer.parseInt(input.nextLine());
//Create switch
if (choiceEntry <1){
System.out.println("Please enter a valid menu command (1-3)");
}
else if (choiceEntry >3){
System.out.println("Please enter a valid menu command (1-3)");
}
double damageCost = 0;
switch (choiceEntry){
case 1: System.out.print("Enter a description of the damage:");
String damageDetail = input.nextLine();
System.out.print("Enter the damage cost:");
damageCost = Integer.parseInt(input.nextLine());
System.out.print("The damage is: " + damageDetail + "\n");
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
break;
case 2: System.out.print("Enter a description of the traffic infringement:");
String trafficDetail = input.nextLine();
System.out.print("Enter the traffic infringement cost:");
double trafficCost = Integer.parseInt(input.nextLine());
break;
case 3: quit = true;
System.out.println("Menu entry has been terminated.");
break;
}
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
}
}
}

You could try adding the option to an arraylist.
List<String> listOfEntries=new ArrayList<String>(); // Add strings like damage repair,etc
//Or you could try
List<Integer> listOfOptions=new ArrayList<Integer>();// Add option here, like 1,2
You can add the user chosen options and at any point of time, you can retreive the options chosen by the user and display the values to the user.
Hope this helps!

This would work:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Setup an exit statement
boolean quit = false;
double dCost=0;
double tCost=0;
StringBuilder dDetail= new StringBuilder("The Damage Details are :" );
StringBuilder tDetail= new StringBuilder("The Traffic details are: " );
while (!quit){
System.out.println("Enter one of the following commands:");
System.out.println("1 - Damage Repair");
System.out.println("2 - Traffic Infringement");
System.out.println("3 - Exit Menu");
int choiceEntry = Integer.parseInt(input.nextLine());
//Create switch
if (choiceEntry <1){
System.out.println("Please enter a valid menu command (1-3)");
}
else if (choiceEntry >3){
System.out.println("Please enter a valid menu command (1-3)");
}
double damageCost = 0;
switch (choiceEntry){
case 1: System.out.print("Enter a description of the damage:");
String damageDetail = input.nextLine();
System.out.print("Enter the damage cost:");
damageCost = Integer.parseInt(input.nextLine());
System.out.print("The damage is: " + damageDetail + "\n");
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
dDetail.append(damageDetail+"\n");
dCost=dCost+damageCost;
break;
case 2: System.out.print("Enter a description of the traffic infringement:");
String trafficDetail = input.nextLine();
System.out.print("Enter the traffic infringement cost:");
double trafficCost = Integer.parseInt(input.nextLine());
tDetail.append( trafficDetail+"\n");
tCost=tCost+trafficCost;
break;
case 3: quit = true;
System.out.println("Menu entry has been terminated.");
System.out.println("the Total traffic cost is "+tCost);
System.out.println("the Total Damage cost is "+dCost);
System.out.println(tDetail);
System.out.println(dDetail);
break;
}
}
}

Use StringBuilder to append your data. PFB updated code :
import java.util.Scanner;
public class Stage3Check {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Setup an exit statement
boolean quit = false;
StringBuilder sb = new StringBuilder();
outer: while (!quit) {
System.out.println("Enter one of the following commands:");
System.out.println("1 - Damage Repair");
System.out.println("2 - Traffic Infringement");
System.out.println("3 - Exit Menu");
int choiceEntry = Integer.parseInt(input.nextLine());
// Create switch
if (choiceEntry < 1 || choiceEntry > 3)
continue outer;
double damageCost = 0;
switch (choiceEntry) {
case 1:
System.out.print("Enter a description of the damage:");
String damageDetail = input.nextLine();
System.out.print("Enter the damage cost:");
damageCost = Integer.parseInt(input.nextLine());
sb.append("The damage is: " + damageDetail + "\n");
sb.append("The damage cost is: " + "$" + damageCost + "\n");
break;
case 2:
System.out
.print("Enter a description of the traffic infringement:");
String trafficDetail = input.nextLine();
System.out.print("Enter the traffic infringement cost:");
double trafficCost = Integer.parseInt(input.nextLine());
sb.append("The traffic infringement is: " + trafficDetail
+ "\n");
sb.append("The traffic infringement cost is: " + "$"
+ trafficCost + "\n");
break;
default:
quit = true;
System.out.println("Menu entry has been terminated.");
break;
}
}
System.out.println(sb.toString());
}
}

1- The print statement should be placed outside the while loop:
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
2- Declare the damageCost variable globally i.e outside the while loop.
3- Change the statement:
double trafficCost = Integer.parseInt(input.nextLine());
to
damageCost = damageCost + Integer.parseInt(input.nextLine());

Related

Java Scanner nextInt problem, need to stop error when entering a string and loop back

private static int getNumberOfPlayers() {
System.out.println("Please enter number of players ");
Scanner sc = new Scanner(System.in);
int numOfPlayers = sc.nextInt();
System.out.println("You have selected " + numOfPlayers + " Players");
// controlling input, at least 2 - at most 4 players can play the game
while (numOfPlayers < MIN_NUM_PLAYERS || numOfPlayers > MAX_NUM_PLAYERS) {
System.out.print("Please enter a number between 2 and 4: ");
numOfPlayers = sc.nextInt();
System.out.println("You have selected " + numOfPlayers + " players");
}
return numOfPlayers;
}
When the player enters anything other than and int here the game crashes. I would like a sout message to tell the user and loop back so they can try again instead of crashing. Could someone please help me modify this method to implement this functionality. Any help would be greatly appreciated.
Simply use exception handeling like this. This might be what you want:
private static int getNumber() {
System.out.println("Please enter number of players ");
Scanner sc = new Scanner(System.in);
int numOfPlayers = sc.nextInt();
System.out.println("You have selected " + numOfPlayers + " Players");
int newNumOfPlayers;
// controlling input, at least 2 - at most 4 players can play the game
while(true){
if (numOfPlayers < MIN_NUM_PLAYERS || numOfPlayers > MAX_NUM_PLAYERS) {
System.out.print("Please enter a number between 2 and 4: ");
try{
newNumOfPlayers = sc.nextInt();
}catch(Exception ex){
System.out.println("Please select a number only");
sc.next();
continue;
}
numOfPlayers = newNumOfPlayers;
System.out.println("You have selected " + numOfPlayers + " players");
return numOfPlayers;
}
}
}

How to fix exception handling issue in switch case statement?

I am working on project for class, where we were tasked to design a calculator program with a menu containing 5 options. I am facing an issue when I am trying to code to catch if the user inputs a choice that is not between 1 and 5. Currently if the user inputs a number between 6 to 9. The exception will be caught the first time and an error message which says to enter a choice between 1 and 5 will be displayed and a message to re enter will appear. However if the user continues to enter a number between 6 to 9, the error message is not displayed and the main menu appears. I am also trying to catch when a string is entered as input instead of a choice between 1 and 5 and display a different error message saying the user has entered an invalid input and then ask the user to re enter, however when a string is entered as the choice I get an input mismatch exception error but when a string is entered instead of a float after the operation has been chosen, then the correct error message is displayed.
I am a beginner to Java and am open to all suggestions but if it is possible I would like to keep my code somewhat similar to way it is written currently.
static void promptEnterKey() {
System.out.println("Press enter key to continue ...");
Scanner scanner = new Scanner(System.in);
scanner.nextLine();
}
public static void main(String[] args) {
float Firstnum, Secondnum, Solution;
int choice;
Scanner scan = new Scanner(System.in);
do {
System.out.printf("Welcome to Paul's Handy Calculator\n\n (1) Addition\n "
+ "(2) Subtraction\n (3) Multiplication\n (4) Division\n (5) Exit\n\n");
System.out.printf("What would you like to do? ");
choice = scan.nextInt();
try {
if (choice < 1 || choice > 5) {
System.out.printf("You have not entered a number between 1 and 5. "
+ "Try again.\n");
System.out.printf("Enter your choice between 1 and 5 only: \n");
choice = scan.nextInt();
continue;
}
switch (choice) {
case 1:
System.out.print("Please enter two floats to add, "
+ "separated by a space: ");
Firstnum = scan.nextFloat();
Secondnum = scan.nextFloat();
Solution = Firstnum + Secondnum;
System.out.println("Result of adding " + Firstnum + " and "
+ Secondnum + " is " + Solution + "\n");
promptEnterKey();
break;
case 2:
System.out.println("Please enter two floats to subtract, "
+ "separated by a space: ");
Firstnum = scan.nextFloat();
Secondnum = scan.nextFloat();
Solution = Firstnum - Secondnum;
System.out.println("Result of subtracting " + Firstnum
+ " and " + Secondnum + " is " + Solution + "\n");
promptEnterKey();
break;
case 3:
System.out.print("Please enter two floats to multiply, "
+ "separated by a space: ");
Firstnum = scan.nextFloat();
Secondnum = scan.nextFloat();
Solution = Firstnum * Secondnum;
System.out.print("Result of multiplying " + Firstnum + " and "
+ Secondnum + " is " + Solution + "\n");
promptEnterKey();
break;
case 4:
System.out.print("Please enter two floats to divide, "
+ "separated by a space: ");
Firstnum = scan.nextFloat();
Secondnum = scan.nextFloat();
if (Secondnum == 0) {
System.out.println("You cannot divide by zero, "
+ "please enter another number to divide by");
Secondnum = scan.nextFloat();
}
Solution = Firstnum / Secondnum;
System.out.println("Result of dividing " + Firstnum + " and "
+ Secondnum + " is " + Solution + "\n");
promptEnterKey();
break;
case 5:
System.out.println("Thank You for using Paul's Handy Calculator");
System.exit(0);
break;
default:
}
} catch (InputMismatchException ex) {
System.out.println("You have entered an invalid choice. Try again. ");
String flush =scan.next();
}
} while (choice != 5);
}
You just need to move your welcome message outside of the do-while, move your initial scan.nextInt() call inside the try block, and remove your scan.nextInt() call inside your if statement:
// Moved welcome message outside of do-while
System.out.printf("Welcome to Paul's Handy Calculator\n\n (1) Addition\n "
+ "(2) Subtraction\n (3) Multiplication\n (4) Division\n (5) Exit\n\n");
System.out.printf("What would you like to do? ");
do {
try {
// Moved scan.nextInt inside of try block
choice = scan.nextInt();
if (choice < 1 || choice > 5) {
System.out.printf("You have not entered a number between 1 and 5. " + "Try again.\n");
System.out.printf("Enter your choice between 1 and 5 only: \n");
// Removed nextInt call
continue;
}
...

Creating a loop from Java input

I need to create a loop from user input. For example they have to enter how many times they want to shuffle the cards. And then it will run the loop of the cards being drawn as many times as the user input states. I will apply my entire code.
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
public class stringVariables {
private static boolean isValid;
public static void main (String[]args) throws NumberFormatException, IOException {
//user inputs their name in this section
Scanner user_input = new Scanner (System.in);
String first_name;
System.out.print("Enter Your First Name: ");
first_name = user_input.next ();
String last_name;
System.out.print("Enter Your Last Name: ");
last_name = user_input.next ();
String full_name;
full_name = first_name + " " + last_name;
System.out.println( full_name + " Is Now Playing");
//this is the shuffle portion as well as something to see if a number is not inputed
boolean testing = false;
String pos = "";
while(true)
{
testing = false;
Scanner sc = new Scanner(System.in);
System.out.println("How many times do you want the numbers shuffled: ");
pos = sc.next();
for(int i=0; i<pos.length();i++)
{
if(!Character.isDigit(pos.charAt(i)))
testing = true;
}
if(testing == true)
{
System.out.print("Enter only numbers.. ");
continue;
}
else
{
int key = Integer.parseInt(pos);
break;
// here is going to be the loop for shuffles
// we are now going to generate their random number and add a delay after completing their name fields
delay(2000);
System.out.println(" You will be given a hand of 3 random numbers between 7-13");
delay(2000);
System.out.println(" Then, the computer will add the random numbers and if it is equal to 31, you win.");
/* end of explanation of the game, next i will create a new screen
with the user's name and numbers */
delay(4000);
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println("User playing: " + full_name);
System.out.println("Your lucky numbers are...");
// random number generator
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Random rn = new Random();
int ch=1;
while(ch==1){
// get two random numbers between 7 and 13
Random r = new Random();
int num1 =7 + (int)(Math.random()*(7));
int num2 = 7 + (int)(Math.random()*(7));
int num3 = 7 + (int)(Math.random()*(7));
System.out.println(num1 + " + " + num2 + " + " + num3+ " = " + (num1 + num2 + num3 ));
int i = 0 ;
{
System.out.println( num1 + num2 + num3 );
i++ ;
}
if(num1 + num2 + num3 == 31){
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
}
else
System.out.println("Better Luck Next Time");
//the play again menu. this blocks any input besides 1 or 0
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Want To Play Again ? ANY # = YES, ANY LETTER = NO");
String input = sc.next();
int intInputValue = 0;
try {
intInputValue = Integer.parseInt(input);
break;
} catch (NumberFormatException ne) {
System.out.println("Input is not a number, type 1 to continue, or any letter to quit");
ch=Integer.parseInt(br.readLine());
}
}}
}
//delay field
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
//delay field
}
}
}
what I need to do is loop the user input from
boolean testing = false;
String pos = "";
while(true)
{
testing = false;
Scanner sc = new Scanner(System.in);
System.out.println("How many times do you want the numbers shuffled: ");
pos = sc.next();
for(int i=0; i<pos.length();i++)
{
if(!Character.isDigit(pos.charAt(i)))
testing = true;
}
if(testing == true)
{
System.out.print("Enter only numbers.. ");
continue;
}
else
{
int key = Integer.parseInt(pos);
break;
And make it replay this loop
// random number generator
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Random rn = new Random();
int ch=1;
while(ch==1){
// get two random numbers between 7 and 13
Random r = new Random();
int num1 =7 + (int)(Math.random()*(7));
int num2 = 7 + (int)(Math.random()*(7));
int num3 = 7 + (int)(Math.random()*(7));
System.out.println(num1 + " + " + num2 + " + " + num3+ " = " + (num1 + num2 + num3 ));
int i = 0 ;
{
System.out.println( num1 + num2 + num3 );
i++ ;
}
To make it loop to the desired user input after the completion of their name
Although it's not entirely clear what you're trying to achieve I have tried to modify your code from your original post to make it more readable and function the way you want. Please see my comments in the code below, I tried to prefix all of my comments with "EDIT" so you could easily identify which are mine.
//EDIT: added new import to help with validating user input
import java.util.InputMismatchException;
import java.util.Scanner;
//EDIT: removed import that is no longer needed, see code changes below
//import java.io.BufferedReader;
import java.io.IOException;
//EDIT: removed import that is no longer needed, see code changes below
//import java.io.InputStreamReader;
import java.util.Random;
//EDIT: changed class name to java standard naming convention using uppercase for first letter.
public class StringVariables {
// EDIT: this variable is not used, I removed it
// private static boolean isValid;
public static void main(String[] args) throws NumberFormatException,
IOException {
// user inputs their name in this section
Scanner user_input = new Scanner(System.in);
String first_name;
System.out.print("Enter Your First Name: ");
first_name = user_input.next();
String last_name;
System.out.print("Enter Your Last Name: ");
last_name = user_input.next();
String full_name;
full_name = first_name + " " + last_name;
System.out.println(full_name + " Is Now Playing");
// this is the shuffle portion as well as something to see if a number
// is not inputed
// EDIT: removed this variable as it is no longer used in the code that
// follows.
// boolean testing = false;
// EDIT: Removed this variable in favor of using Scanner.nextInt() in
// the code below
// String pos = "";
// EDIT: Added this variable and initialized to an invalid value so that
// we can loop until a valid value is entered.
int numShuffles = -1;
while (numShuffles < 0) {
// EDIT: This variable is not needed with the new logic
// testing = false;
// EDIT: This is not needed, you already have a Scanner object above
// called user_input
// Scanner sc = new Scanner(System.in);
System.out
.println("How many times do you want the numbers shuffled? ");
try {
// EDIT: modified the lines below to fix infinite loop, forgot
// about certain Scanner behavior so switched back to
// Integer.parseInt
String inputText = user_input.next();
numShuffles = Integer.parseInt(inputText);
} catch (NumberFormatException inputException) {
System.out.print("Please enter a valid number. ");
}
} // EDIT: added closing bracket here
// EDIT: none of the code commented out below is needed when using
// the new code above.
// for(int i=0; i<pos.length();i++)
// {
// if(!Character.isDigit(pos.charAt(i)))
// testing = true;
// }
// if(testing == true)
// {
// System.out.print("Enter only numbers.. ");
// continue;
// }
//
// else
// {
// int key = Integer.parseInt(pos);
//
//
// break;
// here is going to be the loop for shuffles
// we are now going to generate their random number and add a delay
// after completing their name fields
delay(2000);
System.out
.println(" You will be given a hand of 3 random numbers between 7-13");
delay(2000);
System.out
.println(" Then, the computer will add the random numbers and if it is equal to 31, you win.");
/*
* end of explanation of the game, next i will create a new screen with
* the user's name and numbers
*/
delay(4000);
// EDIT: rather than repeating the same code over and over just use a
// loop if you want to print 25 blank lines.
for (int i = 0; i < 25; i++)
System.out.println(" ");
// EDIT: see previous comment, removed duplicate code
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
System.out.println("User playing: " + full_name);
System.out.println("Your lucky numbers are...");
// random number generator
// EDIT: This BufferedReader is not needed with changes to code below
// BufferedReader br = new BufferedReader(new
// InputStreamReader(System.in));
Random random = new Random();
// EDIT: removed the following two lines to simplify the looping logic
// int ch = 1;
// while (ch == 1) {
while (true) {
// EDIT: your comment is wrong, you're creating 3 numbers here not 2
// get two random numbers between 7 and 13
// EDIT: no need to create a new Random inside the loop, you can
// re-use a single instance.
// Random r = new Random();
// EDIT: This approach is fine, but I think using the Random class
// is easier to read so I replaced your code with code that uses
// Random
// int num1 = 7 + (int) (Math.random() * (7));
// int num2 = 7 + (int) (Math.random() * (7));
// int num3 = 7 + (int) (Math.random() * (7));
// EDIT: based on your replies it seems like you want to give the user
// several changes for each run of the game and this is what you meant
// by "shuffle". I have implemented that feature below with the for loop.
boolean isWinner = false;
for (int i = 0; i < numShuffles; i++) {
int num1 = 7 + random.nextInt(7);
int num2 = 7 + random.nextInt(7);
int num3 = 7 + random.nextInt(7);
System.out.println(num1 + " + " + num2 + " + " + num3 + " = "
+ (num1 + num2 + num3));
// EDIT: you never use the variable i so I removed this code.
// int i = 0;
// {
// System.out.println(num1 + num2 + num3);
// i++;
// }
if (num1 + num2 + num3 == 31) {
isWinner = true;
System.out
.println("Congratulations !! You are the Lucky Winner !!!!");
break;
}
}
if (!isWinner)
System.out.println("Better Luck Next Time");
// the play again menu. this blocks any input besides 1 or 0
// EDIT: again, re-use the existing scanner
// Scanner sc = new Scanner(System.in);
// EDIT: There is a much simpler and easier-to-read way to do this
// so I have removed your code and added new code after.
// EDIT: Also this code does not work correctly, it fails to exit
// properly when the user enters a letter.
// while (true) {
// System.out.println("Want To Play Again ? ANY # = YES, ANY LETTER = NO");
// String input = user_input.next();
// int intInputValue = 0;
// try {
//
// intInputValue = Integer.parseInt(input);
// Integer.parseInt(input);
// break;
// } catch (NumberFormatException ne) {
// System.out.println("Input is not a number, type 1 to continue, or any letter to quit");
//
// ch = Integer.parseInt(br.readLine());
// }
//
// }
// EDIT: here is the new code, see previous comment.
System.out
.println("Do you want to play again? (If you do enter y or yes) ");
String input = user_input.next();
if (!"y".equalsIgnoreCase(input) && !"yes".equalsIgnoreCase(input)) {
break;
}
}
// EDIT: close the scanner when you're finished with it.
user_input.close();
}
// delay field
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
// delay field
}
}
}
Why not just use
while(true) {
try{
pos = sc.nextInt();
break;
} catch (InputMismatchException e) {
System.out.println("Use only numbers.");
}
}
for(int i = 0; i < pos; i++) {
//do the shuffling
}
I have done some altering in your code and I feel this is what you are looking for. Just copy paste the code and it should work ideally.
import java.util.InputMismatchException;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
public class StringVariables {
public static void main(String[] args) throws NumberFormatException, IOException {
//user inputs their name in this section
Scanner sc = new Scanner(System.in);
String first_name;
System.out.print("Enter Your First Name: ");
first_name = sc.next();
String last_name;
System.out.print("Enter Your Last Name: ");
last_name = sc.next();
String full_name;
full_name = first_name + " " + last_name;
System.out.println(full_name + " Is Now Playing");
//this is the shuffle portion as well as something to see if a number is not inputed
int ch = 1;
while (ch == 1) {
int pos = 0;
System.out.println("How many times do you want the numbers shuffled: ");
while (true) {
sc = new Scanner(System.in);
try {
pos = sc.nextInt();
break;
} catch (InputMismatchException e) {
System.out.println("Use only numbers.");
}
}
// we are now going to generate their random number and add a delay after completing their name fields
delay(2000);
System.out.println(" You will be given a hand of 3 random numbers between 7-13");
delay(2000);
System.out.println(" Then, the computer will add the random numbers and if it is equal to 31, you win.");
/* end of explanation of the game, next i will create a new screen
with the user's name and numbers */
delay(4000);
for (int i = 0; i < 100; i++) {
System.out.println(" ");
}
System.out.println("User playing: " + full_name);
System.out.println("Your lucky numbers are...");
// random number generator
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int num1 = 0, num2 = 0, num3 = 0;
boolean isWinner = false;
for (int j = 0; j < pos; j++) {
num1 = 7 + (int) (Math.random() * (7));
num2 = 7 + (int) (Math.random() * (7));
num3 = 7 + (int) (Math.random() * (7));
System.out.println(num1 + " + " + num2 + " + " + num3 + " = " + (num1 + num2 + num3));
if (num1 + num2 + num3 == 31) {
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
isWinner = true;
}
}
if(!isWinner){
System.out.println("Better Luck Next Time");
}
//the play again menu. this blocks any input besides 1 or 0
while (true) {
System.out.println("Want To Play Again ? ANY # = YES, ANY LETTER = NO");
String input = sc.next();
int intInputValue = 0;
try {
intInputValue = Integer.parseInt(input);
break;
} catch (NumberFormatException ne) {
System.out.println("Input is not a number, type 1 to continue, or any letter to quit");
ch = Integer.parseInt(br.readLine());
}
}
}
}
//delay field
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
//delay field
}
}
}

Calculator in Java: How to return to the main menu?

I've writter a calculator program in Java, after a user is done with work,
I want this to happen:
i'll ask if he wants to do more operations, if yes, the program should return to choice input. If no, break the program.
What lines should I add to the code? This is my calc program:
import java.util.*;
class calc
{
public static void main(String ar[])
{
char choice;
Scanner in = new Scanner(System.in);
System.out.println("WELCOME TO SHREYDAN'S CALC 1.0");
System.out.println(" ");
System.out.println("YOU CAN DO THE FOLLOWING:");
System.out.println("+: ADDITION");
System.out.println("-: SUBTRACTION");
System.out.println("*: PRODUCT");
System.out.println("/: QUOTIENT");
System.out.println("#: SQUARE ROOT");
System.out.println("^: POWER");
System.out.println("$: ROUND OFF");
System.out.println("!: FACTORIAL");
System.out.println(" ");
System.out.println("ENTER CHOICE");
choice=in.next().charAt(0);
switch(choice)
{
case '+':
System.out.println("ENTER 2 NUMBERS, USER");
double a=in.nextDouble();
double b=in.nextDouble();
System.out.println("SUM = "+(a+b));
break;
case '-':
System.out.println("ENTER 2 NUMBERS, USER");
double c=in.nextDouble();
double d=in.nextDouble();
System.out.println("SUBTRACTING "+d+" FROM "+c+" ... DIFFERENCE = "+(c-d));
break;
case '*':
System.out.println("ENTER 2 NUMBERS, USER");
double e=in.nextDouble();
double f=in.nextDouble();
System.out.println("PRODUCT = "+(e*f));
break;
case '/':
System.out.println("ENTER 2 NUMBERS, USER");
double g=in.nextDouble();
double h=in.nextDouble();
System.out.println("DIVIDING "+g+" BY "+h+" = "+(g/h));
break;
case '#':
System.out.println("ENTER NO. FOR SQAURE ROOT:");
double sqrt=in.nextDouble();
System.out.println("SQUARE ROOT OF "+sqrt+" = "+Math.sqrt(sqrt));
break;
case '^':
System.out.println("ENTER BASE, USER");
double base=in.nextDouble();
System.out.println("ENTER POWER, USER");
double power=in.nextDouble();
System.out.println(base+" RAISED TO POWER "+power+" = "+Math.pow(base,power));
break;
case '$':
System.out.println("ENTER DECIMAL VALUES TO ROUND OFF");
double deci=in.nextDouble();
System.out.println("THE NEAREST ROUND OFF = "+Math.round(deci));
break;
case '!':
System.out.println("ENTER A NO. FOR FACTORIAL:");
int fact=in.nextInt();
int factorial=1;
for(int i=fact; i>=1;i--)
factorial=factorial*i;
System.out.println(fact+"! = "+factorial);
break;
default:
System.out.println("WRONG CHOICE USER");
}
}
}
while loops are your best bet for this type of problem, just think of a condition which the user can choose to toggle the boolean condition.
for example if the user chooses no on the "continuing of operations" choice, then toggle the boolean to false and exit the while loop to end the program.
You need to wrap the program logic in a loop.
Try using a while loop
public static void main(String args[])
{
boolean doContinue = true;
while(doContinue){
char choice;
Scanner in = new Scanner(System.in);
//program logic
//when the user enters a command to end
// set continue=false
}
}
Maybe put the entire program inside a while loop with a continue to run bool condition which could be set false when they want to quit
You can try the following:
import java.util.*;
class calc {
public static void main(String ar[]) {
char choice;
Scanner in = new Scanner(System.in);
System.out.println("WELCOME TO SHREYDAN'S CALC 1.0");
System.out.println(" ");
boolean loop = true;
while (loop) {
System.out.println("YOU CAN DO THE FOLLOWING:");
System.out.println("+: ADDITION");
System.out.println("-: SUBTRACTION");
System.out.println("*: PRODUCT");
System.out.println("/: QUOTIENT");
System.out.println("#: SQUARE ROOT");
System.out.println("^: POWER");
System.out.println("$: ROUND OFF");
System.out.println("!: FACTORIAL");
System.out.println(" ");
System.out.println("ENTER CHOICE");
choice = in.next().charAt(0);
switch (choice) {
case '+':
System.out.println("ENTER 2 NUMBERS, USER");
double a = in.nextDouble();
double b = in.nextDouble();
System.out.println("SUM = " + (a + b));
break;
case '-':
System.out.println("ENTER 2 NUMBERS, USER");
double c = in.nextDouble();
double d = in.nextDouble();
System.out.println("SUBTRACTING " + d + " FROM " + c + " ... DIFFERENCE = " + (c - d));
break;
case '*':
System.out.println("ENTER 2 NUMBERS, USER");
double e = in.nextDouble();
double f = in.nextDouble();
System.out.println("PRODUCT = " + (e * f));
break;
case '/':
System.out.println("ENTER 2 NUMBERS, USER");
double g = in.nextDouble();
double h = in.nextDouble();
System.out.println("DIVIDING " + g + " BY " + h + " = " + (g / h));
break;
case '#':
System.out.println("ENTER NO. FOR SQAURE ROOT:");
double sqrt = in.nextDouble();
System.out.println("SQUARE ROOT OF " + sqrt + " = " + Math.sqrt(sqrt));
break;
case '^':
System.out.println("ENTER BASE, USER");
double base = in.nextDouble();
System.out.println("ENTER POWER, USER");
double power = in.nextDouble();
System.out.println(base + " RAISED TO POWER " + power + " = " + Math.pow(base, power));
break;
case '$':
System.out.println("ENTER DECIMAL VALUES TO ROUND OFF");
double deci = in.nextDouble();
System.out.println("THE NEAREST ROUND OFF = " + Math.round(deci));
break;
case '!':
System.out.println("ENTER A NO. FOR FACTORIAL:");
int fact = in.nextInt();
int factorial = 1;
for (int i = fact; i >= 1; i--)
factorial = factorial * i;
System.out.println(fact + "! = " + factorial);
break;
default:
System.out.println("WRONG CHOICE USER");
}
System.out.println("Want to calculate more?Y/N");
loop = in.next().charAt(0) == 'Y';
}
}
}

Use Loop to print out each monthly rent, Threshold [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Use a Loop to print out each monthly rental from the array that falls below the user entered threshold
This was a question I received from my lecturer, I require help because I simply have no idea where to even start. Here is my complete code for the Program, it is the last case.
import java.util.Scanner ;
public class jakeGrim {
public static void main(String[] args) {
// Local variable
int option;
String squareFootage="";
int noBed = 0;
double totalSum =0;
String propertyCode="";
String propertyType="";
String threshold="";
Scanner input = new Scanner( System.in );
Scanner user_input = new Scanner( System.in );
double[] array = new double[12];
do{
// Display menu graphics
System.out.println(" ");
System.out.println("| *****Rental Menu******* |");
System.out.println("| 1. Enter rental property Details ");
System.out.println("| 2. Enter monthly rent ( 12 Months ) ");
System.out.println("| 3. Display Annual Rent");
System.out.println("| 4. Display rental report ");
System.out.println("| 5. Display Monthly rents falling below a certain threshold ");
System.out.println(" ");
System.out.println(" Please Select an option: ");
option = input.nextInt();
{
switch (option) {
case 1:
System.out.println("Enter Rental Details: ");
System.out.println("Property Code: ");
propertyCode = user_input.next();
System.out.println("Property Type: ");
propertyType = user_input.next();
System.out.println("Square Footage: ");
squareFootage = user_input.next();
System.out.println("Number Of bedrooms ");
noBed = input.nextInt();
break;
case 2:
{
Scanner keyboardScanner = new Scanner(System.in);
for (int i = 0; i < 12; i++) {
System.out.println("Enter Rental for month[" +( i +1)+ "]");
array[i] = keyboardScanner.nextDouble();
}
//So now, we need to do something with that array and sum up all the values in that array.
for (int i = 0; i < array.length; i++){
System.out.println(array[i]);
totalSum += array[i];
}
}
break;
case 3:
System.out.println("The annual rent for propery code "+propertyCode+" is: " +(totalSum));
break;
case 4:
System.out.println(" Property Code: "+propertyCode);
System.out.println(" Property Type: "+propertyType);
System.out.println(" Square Footage: "+squareFootage);
System.out.println(" Number of Bedrooms: "+noBed);
System.out.println("");
System.out.println("");
for(int i = 0; i<12; i++)
System.out.println("Rental for month " + (i+1) + " : " + array[i]);
case 5:
Scanner user_input = new Scanner( System.in );
System.out.println("Enter the Rental Threshold: ");
threshold = user_input.next();
System.out.println("
break;
default:
System.out.println("Invalid selection");
break;
}
}
}while (option!=0);
}
}
Well,your program has several flaws which should be improved for better performance.
There is no need of braces before switch.So,delete the braces{ before the switch statement!
Again,there is no need of braces { in case 2 and } before break statement of case-2. You better leave it as it is.
Add these lines of code in your case 5: after deleting previous data into that.
case 5:
// Scanner user_input = new Scanner( System.in );
System.out.println("Enter the Rental Threshold: ");
threshold = user_input.next();
for(int i=0;i<array.length;i++){
if(Integer.valueOf(threshold)>array[i])
System.out.println("Month "+(i+1)+" has the rent falling below the threshold range as the rent is "+array[i]);
}
System.out.println("");
break;
Lastly,you simply need to edit do-while condition,set it as do{...}while(option>=1 && option<=5);
Also, as a matter of fact,try to indent your code properly to give it a better feel! It will make others go through your code and sincerely help you!
Correct working code :-
import java.util.Scanner;
public class jakeGrim {
public static void main(String[] args) {
int option;
String squareFootage="";
int noBed = 0;
double totalSum =0;
String propertyCode="";
String propertyType="";
String threshold="";
Scanner input = new Scanner( System.in );
Scanner user_input = new Scanner( System.in );
double[] array = new double[12];
do{
// Display menu graphics
System.out.println(" ");
System.out.println("| *****Rental Menu******* |");
System.out.println("| 1. Enter rental property Details ");
System.out.println("| 2. Enter monthly rent ( 12 Months ) ");
System.out.println("| 3. Display Annual Rent");
System.out.println("| 4. Display rental report ");
System.out.println("| 5. Display Monthly rents falling below a certain threshold ");
System.out.println(" ");
System.out.println(" Please Select an option: ");
option = input.nextInt();
switch (option){
case 1:
System.out.println("Enter Rental Details: ");
System.out.println("Property Code: ");
propertyCode = user_input.next();
System.out.println("Property Type: ");
propertyType = user_input.next();
System.out.println("Square Footage: ");
squareFootage = user_input.next();
System.out.println("Number Of bedrooms ");
noBed = input.nextInt();
break;
case 2:
Scanner keyboardScanner = new Scanner(System.in);
for (int i = 0; i < 12; i++) {
System.out.println("Enter Rental for month[" +( i +1)+ "]");
array[i] = keyboardScanner.nextDouble();
}
//So now, we need to do something with that array and sum up all the values in that array.
for (int i = 0; i < array.length; i++){
System.out.println(array[i]);
totalSum += array[i];
}
break;
case 3:
System.out.println("The annual rent for propery code "+propertyCode+" is: " +totalSum);
break;
case 4:
System.out.println(" Property Code: "+propertyCode);
System.out.println(" Property Type: "+propertyType);
System.out.println(" Square Footage: "+squareFootage);
System.out.println(" Number of Bedrooms: "+noBed);
System.out.println("");
System.out.println("");
for(int i = 0; i<12; i++)
System.out.println("Rental for month " + (i+1) + " : " + array[i]);
break;
case 5:
// Scanner user_input = new Scanner( System.in );
System.out.println("Enter the Rental Threshold: ");
threshold = user_input.next();
for(int i=0;i<array.length;i++){
if(Integer.valueOf(threshold)>array[i])
System.out.println("Month "+(i+1)+" has the rent falling below the threshold range as the rent is "+array[i]);
}
System.out.println("");
break;
default:
System.out.println("Invalid selection");
break;
}
} while (option>=1 && option<=5);
}
}

Categories

Resources