Creating a loop from Java input - java

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
}
}
}

Related

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

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;
}
}
}
}

How to go back to the beginning of a code without ending it?

I want to go back to the beginning of my code in order to print multiple things and allow people to add multiple “drawings” to a picture without ending the code
Here’s my code:
package com.company;
import java.util.Scanner;
public class Art {
public static void main(String[] args) {
System.out.println("What would you like your scene to contain?");
Scanner userInput = new Scanner(System.in);
String response = userInput.nextLine();
System.out.println("How many " + response + " would you like?");
int number = userInput.nextInt();
if (response.equals("trees") || response.equals("Trees")) {
Scanner scan = new Scanner(System.in);
System.out.println("What kind of trees would you like?");
String variation = scan.nextLine();
if (variation.equals("Pine") || variation.equals("pine")) {
for (int i = 1; i <= number; i++) {
System.out.println(" /\\");
System.out.println(" / \\");
System.out.println(" / \\");
System.out.println(" /______\\");
System.out.println(" [] ");
System.out.println(" ");
}
} else if (variation.equals("oak") || variation.equals("Oak")) {
for (int i = 1; i <= number; i++) {
System.out.println(" \\ ||- \\/-");
System.out.println(" -\\/|| -/");
System.out.println(" \\||-/");
System.out.println(" -[] ");
System.out.println(" []- ");
}
} else if (variation.equals("christmas") || variation.equals("Christmas")) {
for (int i = 1; i <= number; i++) {
System.out.println(" o ");
System.out.println(" .'.'. ");
System.out.println(" .*.'.*. ");
System.out.println(" *.'.*.'.* ");
System.out.println(" .'*.'.*.'.*'. ");
System.out.println("*.''.*.'.*.''.*");
System.out.println(" [ ] ");
}
}
}
System.out.println("Would you like to add more?");
Scanner scan1 = new Scanner(System.in);
String response1 = scan1.nextLine();
}
}
Use a do-while loop to go inside the loop at least once.
You are asking at the end if he wants to add more, you should give the User a choice like type in 'Y' for more.
The 'Y' is here just a dummy value you can replace it with anything you want this should just be an example.
Then you compare the typed in value in the condition of your while()
When the value you are asking for was typed in then go ahead and loop through it again.
import java.util.*;
public class MyClass {
public static void main(String[] args){
String response1;
do{
System.out.println("What would you like your scene to contain?");
Scanner userInput = new Scanner(System.in);
String response = userInput.nextLine();
System.out.println("How many " + response + " would you like?");
int number = userInput.nextInt();
if (response.equals("trees") || response.equals("Trees")) {
Scanner scan = new Scanner(System.in);
System.out.println("What kind of trees would you like?");
String variation = scan.nextLine();
if (variation.equals("Pine") || variation.equals("pine")) {
for (int i = 1; i <= number; i++) {
System.out.println(" /\\");
System.out.println(" / \\");
System.out.println(" / \\");
System.out.println(" /______\\");
System.out.println(" [] ");
System.out.println(" ");
}
} else if (variation.equals("oak") || variation.equals("Oak")) {
for (int i = 1; i <= number; i++) {
System.out.println(" \\ ||- \\/-");
System.out.println(" -\\/|| -/");
System.out.println(" \\||-/");
System.out.println(" -[] ");
System.out.println(" []- ");
}
} else if (variation.equals("christmas") || variation.equals("Christmas")) {
for (int i = 1; i <= number; i++) {
System.out.println(" o ");
System.out.println(" .'.'. ");
System.out.println(" .*.'.*. ");
System.out.println(" *.'.*.'.* ");
System.out.println(" .'*.'.*.'.*'. ");
System.out.println("*.''.*.'.*.''.*");
System.out.println(" [ ] ");
}
}
}
System.out.println("Would you like to add more?");
Scanner scan1 = new Scanner(System.in);
response1 = scan1.nextLine();
}while(response1.equals("Y"));
}
}
Surround your code with while(true)
while (true)
{
// add your code here
}
You can break the loop by using 'break;'

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 do I end the loop completely after I input "q"?

The program does not stop after I input "q"; it still prints the random number and the sum of it. I want the program to completely stop right after I input "q".
import java.util.Scanner;
import java.util.Random;
public class lab7
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Random rand = new Random();
String letter = " ";
int num = 0;
System.out.print("Push your luck");
*/the program prints push your luck!
while(!letter.equals("q")){
int sum = rand.nextInt(12);
System.out.println(" ");
letter = input.nextLine();
*/ the program should not print random number or sum when input "q"
*/but in this case it does
System.out.println("Random number: " + sum);
System.out.println("Updated number: " + num);
num = num + sum;
}
}
}
First give your variables meaningful names. So num should be sum and sum shoud be num.
Next rearrange your code inside the loop like this:
Scanner input = new Scanner(System.in);
Random rand = new Random();
String letter = " ";
int sum = 0;
System.out.print("Push your luck");
while (!letter.equals("q")) {
int num = rand.nextInt(12);
System.out.println(" ");
letter = input.nextLine();
if (!letter.equals("q")) {
sum = sum + num;
System.out.println("Random number: " + num);
System.out.println("Updated number: " + sum);
}
}
The if statement inside the loop prevents any further code from being executed when entered q.
Looks like you want to do:
letter = input.nextLine();
while(!letter.equals("q")) {
int sum = rand.nextInt(12);
System.out.println(" ");
System.out.println("Random number: " + sum);
System.out.println("Updated number: " + num);
num = num + sum;
letter = input.nextLine();
}
Just move the input to the last line of the loop, and add an input just before. That way your loop condition is always checked immediately after the input has been received.
letter = input.nextLine();
while(!letter.equals("q")){
int sum = rand.nextInt(12);
System.out.println(" ");
System.out.println("Random number: " + sum);
System.out.println("Updated number: " + num);
num = num + sum;
letter = input.nextLine();
}
A for loop should do.
for(String aletter = input.nextLine();!aletter.equals("q");aletter=input.nextLine()) {
int sum = rand.nextInt(12);
System.out.println(" ");
System.out.println("Random number: " + sum);
System.out.println("Updated number: " + num);
num = num + sum;
}
And well as you dont use the input it can be simplified:
while(!input.nextLine().equals("q")) {
int sum = rand.nextInt(12);
System.out.println(" ");
System.out.println("Random number: " + sum);
System.out.println("Updated number: " + num);
num = num + sum;
}
And if you wanted at least one output before you are able to stop it with "q":
do {
int sum = rand.nextInt(12);
System.out.println(" ");
System.out.println("Random number: " + sum);
System.out.println("Updated number: " + num);
num = num + sum;
}while(!input.nextLine().equals("q"));
You can make an if clause which checks if q was entered and use the break; statement to stop it. The continue statement would also work for this case.

how to recognise capital letters and not just lower case

Hi i have done this program it works fine except if the user tries to write in capital letters i tried .toUpperCase but it still closes the program if you try to use capital letter to search can anyone help please thank you
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class database
{
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//my arrays
static String country [] = new String[1000];
static String capital [] = new String[1000];
static double population [] = new double[1000];
static List<String> countriesList = Arrays.asList (country); //a new array for user to add data to
public static void main (String args [])throws IOException
{
// now i am adding data to the arrays
country[0] = "Barbados";
capital[0] = "Bridgetown";
population[0] = 65.3;
country[1] = "france";
capital[1] = "paris";
population[1] = 315.8;
country[2] = "nigeria";
capital[2] = "abuja";
population[2] = 170.1;
country[3] = "USA";
capital[3] = "washington";
population[3] = 2840;
country[4] = "japan";
capital[4] = "tokoyo";
population[4] = 126.7;
int option = 0;
System.out.println("WELCOME TO MY COUNTRY DATABASE\n");
while(option!= 5){ //Only five options
options();
option = Integer.parseInt(br.readLine());
if(option > 5 || option < 1)
{
System.out.println("Wrong input! Try Again");
System.out.println("CHOOSE FROM 1 - 5 \n ");
}
if(option == 1) {
addCountry();
}
else if(option == 2){
searchCountry(); //Search from an array
}
else if(option == 3){
ListCountry();
}
else if(option == 4){
getFare(); //show fare to travel
}
else if(option == 5) {
System.out.print("\n Thank you and Goodbye ");
}
}
}
public static void options()
{
System.out.println("Main menu");
System.out.println("=========");
System.out.println("1. Add a new country");
System.out.println("2. Search for a country");
System.out.println("3. Show list of countries available");
System.out.println("4. Get fare from London to countries listed");
System.out.println("5. Exit");
System.out.print("\n Choose an option from 1 - 5: ");
}
public static void addCountry()throws IOException
{
System.out.println("\n Adding a country");
System.out.println("===================");
System.out.print("Enter name of country: ");
String countryInput = br.readLine();
System.out.print("Enter Capital: ");
String capitalInput = br.readLine();
System.out.print("Enter population: ");
String populationInput = br.readLine();
int spareSlot = -1;
for (int i = 0; i < country.length; i++) // loop so data can be added to arraylist
{
if(country[i] == null)
{
spareSlot = i;
break;
}
}
country[spareSlot] = countryInput;
capital[spareSlot] = capitalInput;
population[spareSlot] = Double.parseDouble(populationInput);
System.out.println("\n You added the country " + countryInput + ", the capital is " + capitalInput + ", with a population of " + populationInput + "\n" );
//System.out.println("================================================================================================================");
}
public static void searchCountry() throws IOException
{
Scanner in = new Scanner (System.in);//Scanner to obtain input from command window
String output;
int size, i;
System.out.println("\n Searching countries");
System.out.println("========================= \n");
System.out.print("Search a Country: ");
output = br.readLine();
boolean found = false;
//A loop to search from the array
for(i = 0; i < country.length; i++)
if(output.equals(country[i]))
{
found = true;
break;
}
if (found)
System.out.println(output + " is found at index " + i +"\n");
else
System.out.println(output + ": This country is not found, choose option 1 to Add country \n");
if (output == country[0])
{
System.out.println("The capital of "+ output + "is " + capital[1] + " with a population of " + population[3]);
}
if(output == country[1]) {
System.out.println("The capital is" + capital[4]);
}
if(output == country[2]) {
System.out.println("The capital is" + capital[1]);
}
if(output == country[3]) {
System.out.println("The capital is " + capital[2]);
}
if(output == country[4]) {
System.out.println("The capital is " + capital[3]);
}
}
public static void ListCountry()throws IOException
{
for (String c : countriesList)
{
if(c!=null)
System.out.println("\n" + c +"\n"); // to list all countries so far in the array
}
}
public static void getFare()
{
Scanner input = new Scanner (System.in);
String destination;
int fare;
System.out.println("\n Get a fare:");
System.out.println("============== \n");
System.out.print("Select destination by entering number from 1 -5: \n");
System.out.println("1 Caribbean");
System.out.println("2 Europe");
System.out.println("3 Africa");
System.out.println("4 America");
System.out.println("5 Japan");
destination = input.nextLine(); //get destination from user
fare = Integer.parseInt(destination);
switch(fare)
{
case 1: System.out.println("To travel to the Carribbean the fare is from £600 \n");
break;
case 2: System.out.println("To travel to Europe the fare is from £199 \n");
break;
case 3: System.out.println("To travel to Africa the fareis from £500 \n");
break;
case 4: System.out.println("To travel to America the fare is from £290 \n");
break;
case 5: System.out.println("To travel to Japan the fare is from £550 \n");
break;
default: System.out.println("INVALID ACTION START AGAIN \n");
System.out.println("======================================");
}
}
}
You have one comparison reading
if(output.equals(country[i]))
If you want this to be case-insensitive, you want to change that to
if(output.equalsIgnoreCase(country[i]))
Later in your code, you have lines similar to
if (output == country[0])
which compares object identity rather than string equality. You want to change all these to at least properly compare strings, and possibly to be case-insensitive as above.

Categories

Resources