i have a program where user can enter their name and stuff. its isnised a big try bracket. then at the end it has a catch when the user enter letters instead of number therell be warning "invalid input" i wanna make it so if its invalid 3x, the program closes
so far i have this. i ommited some of the unnecesarry codes, but the important part is just the try, and do while loop
public static void main(String[] args) throws FileNotFoundException {
try{
Scanner input = new Scanner(System.in);
String input_option = "1";
// calling option method
print_options();
int attempt= 0;
boolean authenitcated = false;
do{
input_option = input.nextLine();
if (input_option.equals("0")) {
System.out.println("Enter your first name ");
String firstnameopt0 = input.nextLine();
System.out.println("Enter your last name ");
String lastnameopt0 = input.nextLine();
type.println("Annual Income: " + income);
type.println("Tax: " + opt0tax);
myfile.exists();
type.close();
}
else if (input_option.equals("1")) {
System.out.println("Enter your first name ");
String firstnameopt1 = input.nextLine();
type.close();
}
else if (input_option.equals("2")) {
System.out.println("Enter your first name ");
String firstnameopt2 = input.nextLine();
myfile.exists();
type.close();
}
//extra_options();
input.close();
catch(InputMismatchException exi){
System.out.println("you must enter a double");
attempt++;
}
}while(attempts < 3 && authenticated == false)
}
You need to add an else, at the bottom of your options select part.
Good practise would be to cast it to int, because user can enter zero with lead space, which is still valid.
Secondly close the file after the catch in finally block (close all closeable resources)
int attempt = 0;
boolean authenticated = false;
do {
input_option = input.nextLine();
try {
Integer option = Integer.valueOf(input_option);
switch (option) {
case 0:
System.out.println("Enter your first name ");
String firstnameopt0 = input.nextLine();
System.out.println("Enter your last name ");
String lastnameopt0 = input.nextLine();
break;
case 1:
System.out.println("Enter your first name ");
String firstnameopt1 = input.nextLine();
break;
case 2:
System.out.println("Enter your first name ");
String firstnameopt2 = input.nextLine();
break;
default:
attempt++;
System.out.println("you must enter a int");
}
} catch (Exception ex) {
System.out.println("you must enter a int");
attempt++;
}
} while (attempt < 3 && authenticated == false);
Related
I have a menu below and I want the menu to repeat when a String is enter instead of a interger.I know when a String is enter into "in/nextInt();" it crashes right away. I was wondering what I can do to stop that from where I am at right now.
Scanner in = new Scanner(System.in);
do{
System.out.println("");
System.out.println("Please choose from the following options. " );
System.out.println("");
System.out.println("1. Do you want to use the default rotor settings? ");
System.out.println("2. Do you want to use the custom rotor settings? ");
System.out.println("3. Start over. ");
System.out.println("");
menuOneAnwser = in.nextInt();
}while(menuOneAnwser < 0 || menuOneAnwser > 3);
try{
switch(menuOneAnwser){
case 1:
Enigma.defaultSwitch = true;
break;
case 2:
Enigma.defaultSwitch = false;
g.customRotor();
break;
case 3:
introduction();
break;
default:
break;
}
}catch(InputMismatchException e){
System.out.println("That is not a integer.... Please enter a interger between 1 and 2!" );
System.out.println("Please try again.." );
System.out.println("");
}
instead of callin scanned.nextInt directly, try to convert that string into an integer catching the exception menas the input is not valid and then set the
menuOneAnwser to -1
do{
System.out.println("");
System.out.println("Please choose from the following options. " );
System.out.println("");
System.out.println("1. Do you want to use the default rotor settings? ");
System.out.println("2. Do you want to use the custom rotor settings? ");
System.out.println("3. Start over. ");
System.out.println("");
try {
menuOneAnwser = Integer.parseInt(input);
} catch (NumberFormatException e) {
menuOneAnwser = -1;
}
}while(menuOneAnwser < 0 || menuOneAnwser > 3);
You can write your own version of tryParse (from C# Int32.TryParse) which will attempt to parse the input as an integer, but will alert you if it isn't (return null in this case), and then you can handle it as a String or whatever you would like:
public static Integer tryParseInteger(String input) {
try {
return Integer.parseInt(input);
} catch (NumberFormatException e) {
return null;
}
}
Try and catch approach:
menuOneAnwser = -1;
while (menuOneAnwser < 0 || menuOneAnwser > 3) {
try {
menuOneAnwser = in.nextInt();
} catch (Exception e) {
System.out.println("Please try again.." );
}
}
I'm trying to print a message saying "Wrong", followed by another chance to enter the value every time the user enters something that's not an int.
I have the following code:
do {
System.out.println("Enter last name: ");
lastName = input.next();
System.out.println("Enter first name: ");
firstName = input.next();
do {
System.out.println("Enter exam 1 score: ");
if (input.hasNextInt()) {
ex1 = input.nextInt();
System.out.println("Enter exam 2 score: ");
ex2 = input.nextInt();
System.out.println("Enter exam 3 score: ");
ex3 = input.nextInt();
valid = true;
} else {
System.out.println("Incorrect choice. Write the score in numbers." + "\n");
valid = false;
input.next(); // Prevents infinite loop
}
} while (!valid);
which seems to work fine only if the user makes a mistake for exam 1, but if they do it on exam 2 or 3, it gives me an error.
I'll appreciate your help.
Try not to write the same code again and again. Use a loop.
final int MAX_SCORES = 3;
while (true) {
System.out.println("Enter last name: ");
String lastName = input.next();
System.out.println("Enter first name: ");
String firstName = input.next();
int scores = new int[MAX_SCORES];
for (int i = 0; i < MAX_SCORES; ) {
System.out.printf("Enter exam %d score: ", i + 1);
if (input.hasNextInt()) {
scores[i++] = input.nextInt(); // increment 'i' after assignment
} else {
System.out.println("Incorrect choice. Write the score in numbers.\n");
// Loop will repeat at same value of 'i'
}
}
System.out.println("Again? (Y/N)");
if (input.next().equalsIgnoreCase("n")) break; // Prevents infinite loop
}
You've only made the check for input user 1. You need to do seperate if statements for each user.
if (input.hasNextInt()) {
ex1 = input.nextInt();
} else {
System.out.println("Incorrect choice. Write the score in numbers." + "\n");
valid = false;
input.next(); // Prevents infinite loop
}
System.out.println("Enter exam 2 score: ");
if (input.hasNextInt()) {
ex2 = input.nextInt();
} else {
System.out.println("Incorrect choice. Write the score in numbers." + "\n");
valid = false;
input.next(); // Prevents infinite loop
}
System.out.println("Enter exam 3 score: ");
if (input.hasNextInt()) {
ex3 = input.nextInt();
valid = true;
} else {
System.out.println("Incorrect choice. Write the score in numbers." + "\n");
valid = false;
input.next(); // Prevents infinite loop
}
It would be better to wrap up the else code in a method or something, but that's the idea.
I'm trying to make a text based rock paper scissors. I want the player to choose what they want to play to, for example "best (user response/2 + 1) out of (user response)" then it asks for verification if they would like to play to that number. If they say yes it continues the game with that score, if no it loops back up and lets them choose another number and I have an else that reminds them they can either select yes or no. When they are originally asked, letters don't effect and they are asked to try again. On the second loop around (when you say no) if you enter a String instead of an Int it crashes. Here what I have.
System.out.println("Best of:");
String line = userIn.nextLine();
while (true) {
if (line.length() > 0) {
try { //try catch to stop strings for a response
bestOf = Integer.parseInt(line);
break;
} catch (NumberFormatException e) {
}
}
System.out.println("Please enter a number");
line = userIn.nextLine();
}
System.out.println("Okay, so you want to play best " + (bestOf / 2 + 1) + " of " + bestOf + "?");
String response2 = userIn.nextLine();
while (true) {
if (response2.contains("n")) {
System.out.println("What do you wish to play to then, " + name + "?");
bestOf = userIn.nextInt();
response2 = "y";
} else if (response2.contains("y") || response2.contains("Y")) {
winScore = (bestOf / 2 + 1);
System.out.println("Okay, best " + (bestOf / 2 + 1) + " of " + bestOf + " it is!");
break;
} else {
System.out.println("That's not a valid response! Try again.");
response2 = userIn.nextLine();
}
}
Instead of using parseInt use the string, in other words the input take it as string (even if is a number) them use the function "isNumber" too check if the string the user put is a number if not, do a while
System.out.println("Best of:");
String line = userIn.nextLine();
String aux = line;
do{
if (line.length() > 0)
aux = line;
if(!isNumeric(aux)){
System.out.println("Please enter a number");
line = userIn.nextLine();
}
}while(!isNumeric(aux));
bestOf = Integer.parseInt(aux);
so
public static boolean isNumeric(String str) {
try {
double d = Double.parseDouble(str);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
You can extract your loop as a method and use it in second case as well.
private Integer readInt(Scanner scanner){
String line = scanner.nextLine();
while (true) {
if (line.length() > 0) {
try { //try catch to stop strings for a response
Integer result = Integer.parseInt(line);
return result;
} catch (NumberFormatException e) {
}
}
System.out.println("Please enter a number");
line = scanner.nextLine();
}
}
or even better:
private Integer readInt(Scanner scanner){
Integer result;
do{
try{
return scanner.nextInt();
} catch (InputMismatchException e){
scanner.nextLine();
System.out.println("Please enter a number");
}
} while (true);
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I am writing a program that asks the user to input his name, address and phone number. When the data is entered the program shall print the data and ask the user to verify the data by entering YES or NO. This process shall be repeated until the user is satisfied and answers YES to the question.
Now in my case I may have put a if-else statement inside the while loop in an inappropriate way. That's why it's not working as it is expected to be. How can I solve this?
Also I only have tried the promt asking to enter the users name. But if I want to add more prompt with different question in the similiar way then how could I do that?
Code:
package userinfo;
import java.util.Scanner;
public class UserInfo {
public static void main(String[] args) {
String name;
String yes = "YES";
String no = "NO";
Scanner userInput = new Scanner(System.in);
System.out.println("Enter your name:");
name = userInput.next();
System.out.println("Please varify your name by typing YES or NO");
while (true) {
String input = userInput.next();
if (input == yes) {
System.out.println("Your name is: " + name);
}
if (input == no) {
System.out.println("Enter your name again");
} else {
System.out.println("Invalid input! Enter value again:");
break;
}
}
}
}
You should use it like this:
if (input.equals(yes)) {
System.out.println("Your name is: " + name);
}
else if (input.equals(no)) {
System.out.println("Enter your name again");
}
Because the statement:
input==yes;
only checks if the references are equal or not
And to input more values from the user you can do it like this:
System.out.println("Enter your name:"); //This you already did
name = userInput.next
System.out.println("Enter your surname:");
String surname = userInput.next();
full code:(Asking for multiple prompts)
package userinfo;
import java.util.Scanner;
public class UserInfo {
public static void main(String[] args) {
String name;
int teleNum;
String inputTeleNum;
String yes = "YES";
String no = "NO";
Scanner userInput = new Scanner(System.in);
while (true) {
System.out.println("Enter your name:");
name = userInput.next();
System.out.println("Please varify your name by typing YES or NO");
String input = userInput.next();
if (input.equals(yes)) {
System.out.println("Your name is: " + name);
} else if (input.equals(no)) {
System.out.println("Enter your name again");
}
while (true) {
System.out.println("Enter your telephone number:");
teleNum = userInput.nextInt();
System.out.println("Please varify your telephone number by typing YES or NO");
inputTeleNum = userInput.next();
if (inputTeleNum.equals(yes)) {
System.out.println("Your telephone num is: " + teleNum);
} else if (inputTeleNum.equals(no)) {
System.out.println("Enter your tele number again: ");
}
}
}
}
}
The break statement should go inside
if(input.equals(yes))
Not in the else{}.
Since JDK 7 it's possible to use a String in a switch statement:
public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
String typeOfDay;
switch (dayOfWeekArg) {
case "Monday":
typeOfDay = "Start of work week";
break;
case "Tuesday":
case "Wednesday":
case "Thursday":
typeOfDay = "Midweek";
break;
case "Friday":
typeOfDay = "End of work week";
break;
case "Saturday":
case "Sunday":
typeOfDay = "Weekend";
break;
default:
throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
}
return typeOfDay;
}
Maybe this is applicable in your situation. You loose the options of #equalsIgnoreCase() though.
To compare String use the methods equals() or equalsIgnoreCase(). this will resolve your issue.
I've set up a "menu" that prints to console. Takes user input, calls according method, and then should return to the menu for further instruction. How should I structure my code so that it outputs the "menu" after it's done doing whatever it's doing?
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
EntryNode n = new EntryNode();
AddressList addressBook = new AddressList();
String menu = " ";
System.out.println("******************************************************************");
System.out.println("Welcome to the Jackie 2000 Address Book");
System.out.println("What do you want to do? ");
System.out.println("[p] View All Entries in Address Book [a] Add New Entry");
System.out.println("[d] Remove An Entry [s] Search for Entry");
System.out.println("[i] Import Address Book [x] Export Address Book");
System.out.println("[z] Exit");
System.out.println();
System.out.println("Please enter your choice: ");
menu = keyboard.next().toLowerCase();
if (menu.equals("p")) {
try {
addressBook.printList();
}
catch (Exception e){
}
}
else if (menu.equals("a")) {
System.out.println("Enter in the first name ");
String firstName = keyboard.next().toUpperCase();
System.out.println("Enter in the last name ");
String lastName = keyboard.next().toUpperCase();
System.out.println("Enter in the phone number");
String phoneNum = keyboard.next().toUpperCase();
System.out.println("Enter in the email");
String email = keyboard.next().toUpperCase();
addressBook.addEntry(firstName,lastName,phoneNum,email);
}
else if (menu.equals("d")) {
EntryNode temp = head;
for (int i = 0; i <addressBook.length(); i++) {
System.out.println(i + " Name: " + temp.getFirstName() + " " + temp.getLastName() + " "
+ temp.getPhoneNum() + " " + temp.getEmail());
temp = temp.getNext();
}
System.out.println(" ");
System.out.println("Please enter the index of the entry you wish to delete ");
int index = keyboard.nextInt();
addressBook.removeEntry(index);
}
else if (menu.equals("s")) {
System.out.println("Do you want to search by email or name? ");
String decision = keyboard.next();
if (decision.equals("email")) {
System.out.println("What email address are you looking for? ");
String email = keyboard.next();
addressBook.searchEmail(email);
}
else if (decision.equals("name")) {
System.out.println("What name are you looking for?");
String name = keyboard.next();
addressBook.searchEntry(name);
}
else System.out.println("Invalid entry. Type in 'email' or 'name'");
}
else if (menu.equals("i")) {
addressBook.importBook();
}
else if (menu.equals("x")) {
addressBook.exportBook();
}
else if (menu.equals("e")) {
System.exit(0);
}
else {
System.out.println("Invalid Entry");
}
}
}
You should definitely take a look at java's switch statement: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
You could have the entire switch-case statement inside a while loop with a boolean for when it should exit. For example:
while(!exit){
switch(input){
case "a": do something;break;
case "d":...
...
case "e": exit = true;
}
}
If you want the same menu to be displayed again after the user entered a choice and the program executed what he had to do, just put the whole process in a while or do...while loop and only exit it when the user choose the exit option.
Put a menu printlns into a separate static method. Call it after each addressBook method call, just before you close else if, except for an exit case.