I am having trouble using this try/catch statement. I am trying to use it to throw an error message that says, "Please enter an integer!" if the user enters a letter. The first one I used worked, but it ends up taking 2 lines of user input rather than just one, so it essentially skips over a question that was supposed to be asked. After that, none of the other ones work at all, they just get completely skipped. I also need to do the same thing for user input where if a user enters an integer where a letter should be, it throws an error message that says "Please enter a string!". I know I am pretty close!
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean validInput = false;
int val = 0;
System.out.print("Enter your first name: ");
String firstName = input.nextLine();
System.out.print("Enter your last name: ");
String lastName = input.nextLine();
System.out.print("Enter your address: ");
String address = input.nextLine();
System.out.print("Enter your city: ");
String city = input.nextLine();
System.out.print("Enter your state: ");
String state = input.nextLine();
System.out.print("Enter your zip code + 4: ");
String zip = input.nextLine();
while(!validInput) {
try {
val = input.nextInt();
validInput = true;
} catch(Exception e) {
System.out.println("Please enter an integer!");
input.nextLine();
}
}
System.out.print("Enter amount owed: ");
String amount = input.nextLine();
while(!validInput) {
try {
val = input.nextInt();
validInput = true;
} catch(Exception e) {
System.out.println("Please enter an integer!");
input.next();
}
}
System.out.print("Enter your payment amount: ");
String payment = input.nextLine();
while(!validInput) {
try {
val = input.nextInt();
validInput = true;
} catch(Exception e) {
System.out.println("Please enter an integer!");
input.next();
}
}
System.out.print("Enter the date of payment: ");
String date = input.nextLine();
while(!validInput) {
try {
val = input.nextInt();
validInput = true;
} catch(Exception e) {
System.out.println("Please enter an integer!");
input.next();
}
}
System.out.println("\t\t\t\t\t" + "XYZ Hospital");
System.out.println();
System.out.println("Name Information" + "\t\t\t\t" + "Address" + "\t\t\t\t\t\t" + "Payment");
System.out.println();
System.out.println("Last" +"\t"+ "First" + "\t\t\t" + "Address Line 1" + "\t" + "City" + "\t" + "State" + "\t" + "Zip" + "\t" + "Amount Owed" + "\t" + "Payment Amount" + "\t" + "Payment Date");
System.out.println();
System.out.println(lastName + " " + firstName + "\t" + address + " " + city + ", " + state + " " + zip + "\t" + amount + "\t\t" + payment +"\t\t"+ date);
System.out.print("Would you like to enter abother patient? Type Yes or No: ");
String userInput = input.nextLine();
if (userInput.equals("Yes")) {
while (userInput.equals("Yes")) {
System.out.print("Enter your first name: ");
String firstName2 = input.nextLine();
System.out.print("Enter your last name: ");
String lastName2 = input.nextLine();
System.out.print("Enter your address: ");
String address2 = input.nextLine();
System.out.print("Enter your city: ");
String city2 = input.nextLine();
System.out.print("Enter your state: ");
String state2 = input.nextLine();
System.out.print("Enter your zip code + 4: ");
String zip2 = input.nextLine();
System.out.print("Enter amount owed: ");
String amount2 = input.nextLine();
System.out.print("Enter your payment amount: ");
String payment2 = input.nextLine();
System.out.print("Enter the date of payment: ");
String date2 = input.nextLine();
System.out.println("\t\t\t\t\t" + "XYZ Hospital");
System.out.println();
System.out.println("Name Information" + "\t\t\t\t" + "Address" + "\t\t\t\t\t\t" + "Payment");
System.out.println();
System.out.println("Last" +"\t"+ "First" + "\t\t\t" + "Address Line 1" + "\t" + "City" + "\t" + "State" + "\t" + "Zip" + "\t" + "Amount Owed" + "\t" + "Payment Amount" + "\t" + "Payment Date");
System.out.println();
System.out.println(lastName2 + " " + firstName2 + "\t" + address2 + " " + city2 + ", " + state2 + " " + zip2 + "\t" + amount2 + "\t\t" + payment2 +"\t\t"+ date2);
System.out.print("Would you like to enter another patient? Type Yes or No: ");
userInput = input.nextLine();
}
}
else if (userInput.equals("No")) {
System.out.println("Goodbye");
}
You don't reset validInput to False after your first while loop. So it doesn't enter the next.
You should take input in catch block comment input.nextLine() in catch block then it should work properly
I have added explanation in the code itself
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean validInput = false;
int val = 0;
System.out.print("Enter your first name: ");
String firstName = input.nextLine();
System.out.print("Enter your last name: ");
String lastName = input.nextLine();
System.out.print("Enter your address: ");
String address = input.nextLine();
System.out.print("Enter your city: ");
String city = input.nextLine();
System.out.print("Enter your state: ");
String state = input.nextLine();
System.out.print("Enter your zip code + 4: ");
String zip = input.nextLine();
while (!validInput) {
try {
val = input.nextInt();
validInput = true; //if exception occurs this line wont be executed
} catch (Exception e) {
System.out.println("Please enter an integer!");
// input.nextLine(); --remove this line
}
}
System.out.print("Enter amount owed: ");
String amount = input.nextLine();
//reset the value of validInput
//validInput will true after the execution of above while loop
validInput = false;
while (!validInput) {
try {
val = input.nextInt();
validInput = true; //if exception occurs this line wont be executed
} catch (Exception e) {
System.out.println("Please enter an integer!");
// input.next(); -- remove this line
}
}
}
A quick solution maybe, I've used Scanner.hasNextInt to check what the next token is before getting required ints:
import java.util.Scanner;
public class java_so {
private static int privateGetInt(String request, Scanner input) {
// cant be false, but we return when done.
while (true) {
// print the question
System.out.println(request);
// check what the next token is, if an int we can then retrieve
if (input.hasNextInt() == true) {
int out = input.nextInt();
input.nextLine(); // clear line, as nextInt is token orientated, not line,
return out;
} else {
// else for when not an int, clear line and try again
input.nextLine();
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter your first name: ");
System.out.println(input.nextLine());
// call function above
System.out.println(privateGetInt("enter an Int", input));
System.out.print("Enter your last name: ");
System.out.println(input.nextLine());
System.out.print("Enter your address: ");
System.out.println(input.nextLine());
}
}
It seems a bit like the problem may have been after a call to input.nextInt you haven't got rid of the rest of the line (which is probably just "\n") so the next call to input.getLine() only gets that, jumping on one. Following input.getInt with input.getLine clears this.
Related
//Choice of choosing a dog or a cat
String pet = input.next();
switch (pet.charAt(0)) {
case 'a' -> {
System.out.println("What is your dog's name? ");
String dogsName = input.next();
System.out.println("Your Character's Name is: " + playerName + "\nYour Pet's Name is: " + dogsName);
}
case 'b' -> {
System.out.println("What is your cat's name? ");
String catsName = input.next();
System.out.println("Character Name: " + playerName + "\nPet Name: " + catsName);
}
default -> System.out.println("That is not a valid option. Please choose again.");
}
input.close();
}
I can't find a loop to use that would bring it back to case a and repeatedly until the user answers using one of the choices, Any help would be awesome! Thanks
Using do while loop is a simple way to solve it.
I used a variable repeat to check, If I need to ask for the input again or not
Also, note that now even If I add another case(say case 'c') I don't need to modify condition for my do while loop
boolean repeat;
do {
String pet = input.next();
repeat = false;
switch (pet.charAt(0)) {
case 'a' -> {
System.out.println("What is your dog's name? ");
String dogsName = input.next();
System.out.println("Your Character's Name is: " + playerName + "\nYour Pet's Name is: " + dogsName);
}
case 'b'-> {
System.out.println("What is your cat's name? ");
String catsName = input.next();
System.out.println("Character Name: " + playerName + "\nPet Name: " + catsName);
}
default: System.out.println("That is not a valid option. Please choose again.");
repeat = true;
}
} while(repeat);
input.close();
Looping is good solution but you can also use the Recessive methods in java.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(" Welcome To The Choices Game... ");
System.out.println("Please enter your name: " );
String playerName = input.nextLine();
System.out.println("What is " + playerName + "'s" + " favorite pet?");
System.out.println("a. Dog \nb. Cat");
//Choice of choosing a dog or a cat
method();
input.close();
}
public void method()
{
String pet = input.next();
switch (pet.charAt(0)) {
case 'a' -> {
System.out.println("What is your dog's name? ");
String dogsName = input.next();
System.out.println("Your Character's Name is: " + playerName + "\nYour Pet's Name is: " + dogsName);
}
case 'b' -> {
System.out.println("What is your cat's name? ");
String catsName = input.next();
System.out.println("Character Name: " + playerName + "\nPet Name: " + catsName);
}
default -> System.out.println("That is not a valid option. Please choose again.");
method();
}
}
To loop the entire switch-case section, you can try putting it in a do-while loop. As for the condition to use with the do-while block you could try:-
do {...}while(pet.charAt(0)!='a' || pet.charAt(0)!='b');
I am providing you with a possible solution below:-
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(" Welcome To The Choices Game... ");
System.out.println("Please enter your name: " );
String playerName = input.nextLine();
System.out.println("What is " + playerName + "'s" + " favorite pet?");
System.out.println("a. Dog \nb. Cat");
//Choice of choosing a dog or a cat
do{
String pet = input.next();
switch (pet.charAt(0)) {
case 'a' -> {
System.out.println("What is your dog's name? ");
String dogsName = input.next();
System.out.println("Your Character's Name is: " + playerName + "\nYour Pet's Name is: " + dogsName);
break;}
case 'b' -> {
System.out.println("What is your cat's name? ");
String catsName = input.next();
System.out.println("Character Name: " + playerName + "\nPet Name: " + catsName);
break;}
default -> System.out.println("That is not a valid option. Please choose again.");
}
}while(pet.charAt(0)!='a' && pet.charAt(0)!='b');
input.close();
}
I can't find a loop to use that would bring it back to the beginning of the switch case and repeatedly until the user answers using one of the choices, Any help would be awesome! Thanks. (I have also tried using a do-while loop that someone suggested but it just seems to spam the default.) ((which I left in the code))
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(" Welcome To The Choices Game... ");
System.out.println("Please enter your name: ");
String playerName = input.nextLine();
System.out.println("What is " + playerName + "'s" + " favorite pet?");
System.out.println("a. Dog \nb. Cat");
//Choice of choosing a dog or a cat
String pet = input.next();
do {
switch (pet.charAt(0)) {
case 'a' -> {
System.out.println("What is your dog's name? ");
String dogsName = input.next();
System.out.println("Your Character's Name is: " + playerName + "\nYour Pet's Name is: " + dogsName);
break;
}
case 'b' -> {
System.out.println("What is your cat's name? ");
String catsName = input.next();
System.out.println("Character Name: " + playerName + "\nPet Name: " + catsName);
break;
}
default -> System.out.println("That is not a valid option. Please choose again.");
}
} while (pet.charAt(0) != 'a' && pet.charAt(0) != 'b');
input.close();
}
You need to take the input for Cat/Dog (option a or option b) inside the do loop so that after wrong input code can ask for updated input. As below:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(" Welcome To The Choices Game... ");
System.out.println("Please enter your name: ");
String playerName = input.nextLine();
System.out.println("What is " + playerName + "'s" + " favorite pet?");
System.out.println("a. Dog \nb. Cat");
// Here is change in code
String pet = null;
do {
// Choice of choosing a dog or a cat
// Here is change in code
pet = input.next();
switch (pet.charAt(0)) {
case 'a': {
System.out.println("What is your dog's name? ");
String dogsName = input.next();
System.out.println("Your Character's Name is: " + playerName + "\nYour Pet's Name is: " + dogsName);
break;
}
case 'b': {
System.out.println("What is your cat's name? ");
String catsName = input.next();
System.out.println("Character Name: " + playerName + "\nPet Name: " + catsName);
break;
}
default: {
System.out.println("That is not a valid option. Please choose again.");
}
}
} while (pet.charAt(0) != 'a' && pet.charAt(0) != 'b');
input.close();
}
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
}
}
}
My problem is that when I run this program I have to press 2 twice, or 3 three times to get the else if statements to run. I have tried switching the input to string and it has the same issues. (you can ignore all the code except the (sc.nextInt()==1)/(sc.nextInt()==2)/(sc.nextInt()==3)) Those are where I'm having problems. Thanks
Scanner sc = new Scanner(System.in);
int running = 0;
do
{
System.out.println("What would you like to do?");
System.out.println("(1)Enter hourly employee");
System.out.println("(2)Enter commissionary employee");
System.out.println("(3)Terminate program");
System.out.println();
if (sc.nextInt()==1){
System.out.println("Enter their first name. \n");
hour.firstName= sc.next();
System.out.println("Enter their last name. \n");
hour.lastName= sc.next();
System.out.println("Enter their Id #. \n");
hour.id= sc.nextInt();
System.out.println("Enter their wage amount. \n");
hour.wage= sc.nextInt();
System.out.println("Enter how many hours they will be working. \n");
hour.hrs= sc.nextInt();
System.out.println("employee "+ hour.id + "'s name is " + hour.firstName + " "+ hour.lastName + " their id is "+ hour.id);
System.out.println("employee "+ hour.id + "'s wage is " + hour.wage + "$ and will be working "+ hour.hrs +" hours per week.");
running++;
}
//have to type 2 twice here
else if (sc.nextInt()== 2){
System.out.println("Enter their first name. \n");
com.firstName= sc.next();
System.out.println("Enter their last name. \n");
com.lastName= sc.next();
System.out.println("Enter their Id #. \n");
com.id= sc.nextInt();
System.out.println("Enter their base salary. \n");
bcom.baseSalary= sc.nextInt();
System.out.println("Enter their wage commission rate. \n");
com.cRate= sc.nextInt();
System.out.println("Enter their expected gross sales goal. \n");
com.gSales= sc.nextInt();
System.out.println("employee "+ com.id + "'s name is " + com.firstName + " "+ com.lastName + " their id is "+ com.id);
System.out.println("employee "+ com.id + "'s base salary is "+ bcom.baseSalary + "$ their commission rate is \n" + com.cRate + "% and is estimated to make "+ com.gSales +"$ in gross sales.");
running++;
}
//have to type 3 three times here
else if (sc.nextInt()== 3)
{
running++;
}
}while(running < 1);
Scanner sc = new Scanner(System.in);
int running = 0;
do
{
System.out.println("What would you like to do?");
System.out.println("(1)Enter hourly employee");
System.out.println("(2)Enter commissionary employee");
System.out.println("(3)Terminate program");
System.out.println();
int i = sc.nextInt();
if (i==1){
System.out.println("Enter their first name. \n");
hour.firstName= sc.next();
System.out.println("Enter their last name. \n");
hour.lastName= sc.next();
System.out.println("Enter their Id #. \n");
hour.id= sc.nextInt();
System.out.println("Enter their wage amount. \n");
hour.wage= sc.nextInt();
System.out.println("Enter how many hours they will be working. \n");
hour.hrs= sc.nextInt();
System.out.println("employee "+ hour.id + "'s name is " + hour.firstName + " "+ hour.lastName + " their id is "+ hour.id);
System.out.println("employee "+ hour.id + "'s wage is " + hour.wage + "$ and will be working "+ hour.hrs +" hours per week.");
running++;
}
//have to type 2 twice here
else if (i== 2){
System.out.println("Enter their first name. \n");
com.firstName= sc.next();
System.out.println("Enter their last name. \n");
com.lastName= sc.next();
System.out.println("Enter their Id #. \n");
com.id= sc.nextInt();
System.out.println("Enter their base salary. \n");
bcom.baseSalary= sc.nextInt();
System.out.println("Enter their wage commission rate. \n");
com.cRate= sc.nextInt();
System.out.println("Enter their expected gross sales goal. \n");
com.gSales= sc.nextInt();
System.out.println("employee "+ com.id + "'s name is " + com.firstName + " "+ com.lastName + " their id is "+ com.id);
System.out.println("employee "+ com.id + "'s base salary is "+ bcom.baseSalary + "$ their commission rate is \n" + com.cRate + "% and is estimated to make "+ com.gSales +"$ in gross sales.");
running++;
}
//have to type 3 three times here
else if (i== 3)
{
running++;
}
}while(running < 1);
because each time u write nextInt(), it will wait for input from User. So, just try to catch 1 input from User, then just check whats the input is.
You are reading a 2nd time from sc.nextInt() in your 'else'.
Read once before the 'if', then test the value.
Whenever you call nextInt(), the process waits and reads your input once.
So, the first if(sc.nextInt()==1) reads your input once, and you need to type the second time to reach else if (sc.nextInt()==2).
To solve this, try following structure:
int input = sc.nextInt();
if (input == 1) {
} else if (input == 2) {
} else if (input == 3) {
}
How would I get this code to keep on asking for "student number" until a student number is entered correctly starting with the character 'X' and then continue on with the program?
import java.util.Scanner;
public class SDevCA2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
//inputs
//Option 1
String userName;
String passWord1;
String passWord2;
String eol;
String userInput;
int loopVal =0;
char firstLetter = 'X';
int userOption;
final double FULLGRANT = 3000;
final double GRANTSEVENTYFIVE = 2250;
final double GRANTFIFTY = 1500;
double softWareGrade =0;
double mathsGrade =0;
double systemGrade =0;
double computerArchGrade =0;
double gradeCount;
final double SUBJECT_COUNT = 4;
double averageGrade;
int overallAverageResults;
int feesOwedPercent;
double feesOwedEuros;
//Option 2
double feesPaidByGrant =0;
double feesNotPaidByGrant =0;
int totalStudentsProcessed =0;
int totalStudentsRecievedGrant =0;
//Option 3
int studentsWith100Paid =0;
int studentsWith75Paid =0;
int studentsWith50Paid =0;
int studentsWithNoGrant =0;
int categoryMostStudents;
//End of Inputs
boolean run = true;
while ( run ) {
Scanner in = new Scanner (System.in);
//input of data
//input of data
System.out.println("Please enter your username: ");
userName = in.nextLine();
System.out.print("Please enter your password: ");
passWord1 = in.nextLine();
System.out.print("Please re-enter your password: ");
passWord2 = in.nextLine();
while (!passWord1.equals(passWord2))
{
System.out.println("Incorrect! Please try re-entering password ");
System.out.print("Please enter your password: ");
passWord1 = in.nextLine();
System.out.print("Please re-enter your password: ");
passWord2 = in.nextLine();
}
//ABC Grant Menu.
System.out.println("\n --------------------------------");
System.out.println ("Welcome to the ABC College Grant System \n 1. Calculate Grant \n 2. Fee Statistics \n 3. Grant Category Information \n 4. Exit");
userOption = in.nextInt();
//if Invalid Entry Error Message with the ABC Menu again
//Option 1
switch ( userOption ) {
case 1:
String studentName;
String studentNumber;
System.out.println ("Please Enter your Student Name: ");
studentName = in.next();
System.out.println ("Please Enter your Student Number: ");
userInput = in.next();
while ( userInput.charAt(0) == firstLetter) {
System.out.println("Correct");
break;
}
while ( userInput.charAt(0) != firstLetter)
{
System.out.println("No match, Student Numbr must begin with character capital X ");
}
{
//Error message if Student Number doesn't start with X
System.out.println ("What was your Grade in Software Development");
softWareGrade = in.nextDouble();
System.out.println ("What was your Grade in Maths");
mathsGrade = in.nextDouble ();
System.out.println("What was your Grade in Systems Analasys");
systemGrade = in.nextDouble ();
System.out.println("What was your Grade in Computer Archetecture");
computerArchGrade = in.nextDouble();
//Formula
gradeCount = softWareGrade + mathsGrade + systemGrade + computerArchGrade;
averageGrade = gradeCount / SUBJECT_COUNT;
//100% FEES PAID
if (averageGrade >=80 && averageGrade <=100) {
feesOwedPercent = 0;
feesOwedEuros = 0;
totalStudentsProcessed ++;
totalStudentsRecievedGrant ++;
studentsWith100Paid ++;
feesPaidByGrant = feesPaidByGrant + FULLGRANT;
System.out.println ("Student Name: " + studentName);
System.out.println ("Student Number: " + userInput);
System.out.println ("Average Grade: " +averageGrade);
System.out.println("Fees Owed: " +feesOwedPercent);
System.out.println("Fees not paid " + feesOwedEuros);
}
if (averageGrade >=60 && averageGrade <80 ) {
feesOwedPercent = 25;
feesOwedEuros = 750;
totalStudentsProcessed ++;
totalStudentsRecievedGrant ++;
studentsWith75Paid ++;
feesPaidByGrant = feesPaidByGrant + GRANTSEVENTYFIVE;
feesNotPaidByGrant = feesNotPaidByGrant + feesOwedEuros;
System.out.println ("Student Name: " + studentName);
System.out.println ("Student Number: " + userInput);
System.out.println ("Average Grade" +averageGrade);
System.out.println("Fees Owed: " +feesOwedPercent);
System.out.println("Fees not paid " + feesOwedEuros );
}
if (averageGrade >=40 && averageGrade <60) {
feesOwedPercent = 50;
feesOwedEuros = 1500;
totalStudentsProcessed ++;
totalStudentsRecievedGrant ++;
studentsWith50Paid ++;
feesPaidByGrant = feesPaidByGrant + GRANTFIFTY;
feesNotPaidByGrant = feesNotPaidByGrant + feesOwedEuros;
System.out.println ("Student Name: " + studentName);
System.out.println ("Student Number: " + userInput);
System.out.println ("Average Grade" +averageGrade);
System.out.println("Fees Owed: " +feesOwedPercent);
System.out.println("Fees not paid " + feesOwedEuros );
}
if ( averageGrade <40 ) {
feesOwedPercent = 100;
feesOwedEuros = 3000;
totalStudentsProcessed ++;
studentsWithNoGrant ++;
feesNotPaidByGrant = feesNotPaidByGrant + feesOwedEuros;
System.out.println ("Student Name: " + studentName);
System.out.println ("Student Number: " + userInput);
System.out.println ("Average Grade" +averageGrade);
System.out.println("Fees Owed: " +feesOwedPercent);
System.out.println("Fees not paid " + feesOwedEuros );
break;
}
switch ( userOption) {
case 2:
System.out.println("The overall fess paid by the grant: €" +feesPaidByGrant );
System.out.println("The overall fees not paid by the grant: €" +feesNotPaidByGrant );
System.out.println("The total number of students processed is: " +totalStudentsProcessed );
System.out.println("The total number of students who recieved a grant is: " +totalStudentsRecievedGrant );
break;
}
switch ( userOption ) {
case 3:
System.out.print("How many stduents are given grants in the following catergory");
System.out.println("100% Paid: " +studentsWith100Paid );
System.out.println("75% Paid: " +studentsWith75Paid );
System.out.println("50% Paid: " +studentsWith50Paid );
System.out.println("No Grant Paid: " +studentsWithNoGrant );
break;
}
switch ( userOption) {
case 4:
System.out.print("The number of stduents that are given grants in the following catergories: ");
System.out.println("\n");
System.out.println("100% Paid: " +studentsWith100Paid );
System.out.println("75% Paid: " +studentsWith75Paid );
System.out.println("50% Paid: " +studentsWith50Paid );
System.out.println("No Grant Paid: " +studentsWithNoGrant );
System.out.print("\n");
System.out.print("\n");
System.out.print("The catergory from which most grants are paid is: ");
run=false;
break;
default:
}
}
}
}
}
}
Your code for prompting the user for their student number and then accepting their input must be inside your while loop. Try something like this:
boolean validNumber = false;
while (!validNumber) {
System.out.println ("Please Enter your Student Number: ");
userInput = in.next();
if (userInput.charAt(0) == firstLetter) {
validNumber = true;
} else {
System.out.println("No match, Student Numbr must begin with character capital X ");
}
}