Validation of an int value - java

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.

Related

Java 3.6 Checking inputs

Ask the user to "Input a number: " 4 times.
If the input is not a number, ask again.
Output "success." after they have entered 4 numbers.
Please answer this code for me using while, if, if else and do statements.
int counter; System.out.print("Input a number: ");
while(!(scan.hasNextInt()));{
for (int i = 0; i < 3; i++){
scan.next();
System.out.print("Input a number: ");
if (!(pass.equals(pass2))) {
counter++;
} else if (!(scan.hasNextInt())) {
}
}
if (counter >= 2) {
System.out.println("Input a number: ");
}
} else if (!(scan.hasNextInt())) { System.out.println("success."); }
This is very basic stuff but I am struggling.
int[] inputIntegers = new int[4]; // Array to save input
Scanner scan = new Scanner(System.in);
int counter = 0;
while(counter < 4) {
System.out.println("Input a number: ");
String input = scan.next();
if(input.matches("[-]?[0-9]*")){ // Checking, if input is an integer
inputIntegers[counter]=Integer.parseInt(input); // Persing string to integer
counter++;
} else {
System.out.println("Input is not an integer");
}
}
System.out.println("Success");
scan.close(); //Do not forget do close scanner

How would I use a while loop to get multiple inputs?

I'd like to make a program that asks the user to enter the number of customers for booking tickets, reads the entered number, performs the loop to ask the age of each customer, and decide the unit price for each customer.
my code so far only has the if else statements:
if (customerP <4){
System.out.println("The unit Price of customer 1 is: 0");
}else {
if(customerP <13) {
System.out.println("The unit price of customer 1 is: 5");
}else {
if(customerP <19) {
System.out.println("The unit price of customer 1 is: 8");
}else {
System.out.println("The unit price of customer 1 is: 10");
}
}
}
How do I add a while loop to ask the to ask the age for each customer?
Here you go:
Scanner scanner = new Scanner(System.in);
System.out.println("Enter No of Customers: ");
int noCustomers = scanner.nextInt();
if (noCustomers < 1) {
throw new IllegalArgumentException("No of Customers has to be 1 or greater");
}
int[] customerAges = new int[noCustomers];
for (int i = 0; i < noCustomers; i++) {
System.out.println("Enter age for customer: " + i);
customerAges[i] = scanner.nextInt();
}
System.out.println("Ages: " + Arrays.toString(customerAges));
Below provides code using while loop
Scanner sc = new Scanner(System.in);
int customerCount = sc.nextInt();
int[] ageOfCustomers = new int[customerCount];
int i=0;
while(customerCount-- > 0) {
ageOfCustomers[i++] = sc.nextInt();
}
System.out.println(Arrays.toString(ageOfCustomers));

how do i do input validation inside a try and catch block?

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

How to call a statement over and over again in Java

import java.util.*;
public class TestProject
{
public static void theMath()
{
double add = 1;
double subtract = 2;
double multiply = 3;
double divide = 4;
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
//Pick first number
System.out.println("Please enter a number: ");
int intOne = input.nextInt();
// Pick second number
System.out.println("Please enter another number: ");
int intTwo = input.nextInt();
//User chooses operator
System.out.println("Now please choose an operator (1 for add, 2 for subtract, 3 for mulitply, 4 for divide): ");
int userChoice = input.nextInt();
// Add
if (userChoice == add)
System.out.println("Your answer is: " + (intOne + intTwo));
// Subtract
else if (userChoice == subtract)
System.out.println("Your answer is: " + (intOne - intTwo));
// Multiply
else if (userChoice == multiply)
System.out.println("Your answer is: " + (intOne * intTwo));
// Divide
else if (userChoice == divide)
System.out.println("Your answer is: " + (intOne / intTwo));
// If wrong input
else
{
System.out.println("Nothing happens!");
System.out.println("Please make sure you entered a number and an operator.");
}
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
theMath();
System.out.println("Would you like to do another calculation?");
String redo = input.nextLine();
if(redo.equals("yes"))
theMath();
else if(redo.equals("no"))
System.out.println("Thanks for calculating with me! It certainly was fun!");
else
System.out.println("Please enter 'yes' or 'no' only.");
String yesNo = input.nextLine();
if(yesNo.equals("yes"))
theMath();
else
System.out.println("Thanks for calculating with me! It certainly was fun!");
}
}
I was wondering how I could recall the main method an infinite amount of times if I wanted to. What I was doing was just copying and pasting it over and over again but there has to be a better way. And also, I would like to know how to return a value has a decimal(so I could do 25/6 and get the correct answer).
Why not put only the statements that should be repeated inside a loop?
String redo;
do{
System.out.println("Would you like to do another calculation?");
redo = input.nextLine();
if(redo.equals("yes"))
theMath();
else if(redo.equals("no"))
System.out.println("Thanks for calculating with me! It certainly was fun!");
else
System.out.println("Please enter 'yes' or 'no' only.");
String yesNo = input.nextLine();
if(yesNo.equals("yes"))
theMath();
else
System.out.println("Thanks for calculating with me! It certainly was fun!");
}while(redo.equals("yes"))
As for the other part of your question. If you have two int values and want to get a decimal from a division, you can do it like this:
int x = 2;
int y = 3;
double result = (double)x/y;
System.out.println(result);
This is called casting.

Using Try/Catch in JAVA

I have the following piece of code where I'm trying to get the user to only enter integers; if a string is entered then it would display a system out error message "please only enter numbers" and then it would show the "Enter your ID#:" again. I tried using the try/catch method but was not using it correctly -- still a beginner. I know I can use the "NumberFormatException" but not sure where. Can anyone help? Thanks!
//Get Customer ID and Account Number
do
{ System.out.print("Enter your ID#: ");
custid = Integer.parseInt(input.readLine());
System.out.print("Enter your Account Number#: ");
custacctnum = Integer.parseInt(input.readLine());
//validate the choice
for(int i=0; i<people.length; i++)
{ if ((people[i].custid == custid) && (people[i].custacctnum == custacctnum))
{ match = true;
System.out.println("Welcome " +people[i].firstname+ " to JJ Dealership!");
for(int p=0; p<cluster.length; p++)
System.out.println(+(p+1)+ ": " +cluster[p].year+"," +cluster[p].make+ "," +cluster[p].model);
System.out.println(people[i].firstname+ ", what color car would you like?");
break;
}
}
if (!match)
{ System.out.println("Invalid ID");
} while (!(match));
Exceptions should be for exceptional circumstances. I suggest you use a Scanner and hasNextInt() to just continue when it isn't an int. That is make a Scanner like,
Scanner input = new Scanner(System.in);
and then something like this would work,
do {
System.out.print("Enter your ID#: ");
if (!input.hasNextInt()) {
System.out.printf("%s is not an int.%n", input.nextLine());
continue;
}
custid = input.nextInt();
System.out.print("Enter your Account Number#: ");
custacctnum = input.nextInt();
if (!input.hasNextInt()) {
System.out.printf("%s is not an int.%n", input.nextLine());
continue;
}
If you really want to use try-catch it should look something like,
do
{
try {
System.out.print("Enter your ID#: ");
custid = Integer.parseInt(input.readLine());
System.out.print("Enter your Account Number#: ");
custacctnum = Integer.parseInt(input.readLine());
//validate the choice
for(int i=0; i<people.length; i++)
{ if ((people[i].custid == custid) &&
(people[i].custacctnum == custacctnum))
{ match = true;
System.out.println("Welcome " +people[i].firstname
+ " to JJ Dealership!");
for(int p=0; p<cluster.length; p++)
System.out.println("" + (p+1) + ": " +cluster[p].year+","
+ cluster[p].make+ "," +cluster[p].model);
System.out.println(people[i].firstname
+ ", what color car would you like?");
break;
}
}
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
} while (!(match));
#Elliott Frisch, I "played" around with it before I saw your answer and figured out how to use the try/catch. It was fairly simple, but I will look at the other option that you posted. With the updated code below when the user enters a string, it will display the error message and then take them to the "Enter your ID#" line to try again.
Thank you all so much for the quick response.
do
{
try{
System.out.print("Enter your ID#: ");
custid = Integer.parseInt(input.readLine());
System.out.print("Enter your Account Number#: ");
custacctnum = Integer.parseInt(input.readLine());
//validate the choice
for(int i=0; i<people.length; i++)
{ if ((people[i].custid == custid) && (people[i].custacctnum == custacctnum))
{ match = true;
System.out.println("Welcome " +people[i].firstname+ " to JJ Dealership!");
for(int p=0; p<cluster.length; p++)
System.out.println(+(p+1)+ ": " +cluster[p].year+"," +cluster[p].make+ "," +cluster[p].model);
System.out.println(people[i].firstname+ ", what color car would you like?");
break;
}
}
if (!match)
{ System.out.println("Invalid ID");
}
} catch (NumberFormatException e)
{System.out.println ("Error! Please enter a number!");}
} while (!(match));

Categories