I have tried similar codes in this site but nothing works for me. So I want the program to keep asking the user to input an integer if its not integer. If the credit card is integer then go to expiration date and if it is valid then print invoice. I tried if and while loop, also try and catch but I guess my logic is broken. Any help will be appreciated.
Scanner s = new Scanner(System.in);
System.out.println("Type 'quit' to exit payment");
System.out.println("Enter name: ");
String name = s.next();
s.nextLine();
if (name.equals("quit"))
{
return;
}
System.out.println("Enter address: ");
String address = s.nextLine();
if (address.equals("quit"))
{
return;
}
System.out.println("Type '000' to exit payment");
System.out.println("Enter card number: ");
#override
int cardNo = s.nextInt();
if (cardNo == 000)
{
return;
}
System.out.println("Enter card expiration date: (DDMMYY)");
int expirationDate = s.nextInt();
if (expirationDate == 000)
{
return;
}
//if input is ok then printing invoice
}
Try the following, I'll also note a few things afterwards about quitting your application
Scanner s = new Scanner(System.in);
String name = "", address = "";
int cardNo = 0, expirationDate = 0;
while(name == "" || address == "" || cardNo == 0 || expirationDate == 0)
{
System.out.println("Type 'quit' to exit payment");
//Get Name
System.out.print("Enter name: ");
name = s.nextLine();
if (name.equals("quit")){return;}
//Get address
System.out.print("Enter address: ");
address = s.nextLine();
if (address.equals("quit")){return;}
System.out.println("Type '-1' to exit payment");
//Get card number continually until an integer is entered
do {
System.out.print("Enter card number: ");
try {
cardNo = Integer.parseInt(s.nextLine());
break;
} catch (Exception e) {
continue;
}
} while (true);
if (cardNo == -1) {return;}
//Get card expiration date continually until an integer is entered
do {
System.out.println("Enter card expiration date: (DDMMYY)");
try {
expirationDate = Integer.parseInt(s.nextLine());
break;
} catch (Exception e) {
continue;
}
} while (true);
if (expirationDate == -1){return;}
}
You might have noticed I changed what to enter when quitting at the card number and expiration date part of the program from 000 to -1. This is because 000 converted to an int will have the value of 0, so the user would never be able to exit your application.
Remember .nextLine() gets the next element each time you call the method . so it is better to assign it to the variable before processing .
From docs ,
Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line,
excluding any line separator at the end. The position is set to the
beginning of the next line.
Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the
line to skip if no line separators are present.
Related
I want to create a try-catch block inside a loop to give the user multiple opportunities to enter the info with the correct format. When I enter something with incorrect format, the program displays the sysout message "Please enter name and age with correct format." from the catch block.
The problem is when I enter the info with the correct formatting after this message, it keeps displaying the same message "Please enter name and age with correct format." even though it should exit and ask if I want to continue.
Here's what I have:
int inAge;
String inName;
while (true) {
try {
inAge = Integer.parseInt((input.substring((input.indexOf(',') + 1))));
inName = input.substring(0, input.indexOf(','));
list.add(new Plant(inName, inAge));
break;
} catch (Exception e) {
System.out.println("Please enter name and age with correct format.");
in.next();
}
}
System.out.println("Do you wish to continue? (Yes or No)");
endOrNo = in.nextLine();
if ("yes".equalsIgnoreCase(endOrNo))
go = true;
else
go = false;
possible that you call next() instead of nextLine(), that may read wrong input and keep taking you back to the exception block.
You need to update the value of input variable as so.
while (true) {
try {
input = in.nextLine(); // accept input
inAge = Integer.parseInt((input.substring((input.indexOf(',') + 1))));
inName = input.substring(0, input.indexOf(','));
list.add(new Plant(inName, inAge));
break;
} catch (Exception e) {
System.out.println("Please enter name and age with correct format.");
input = in.next();
}
}
System.out.println("Do you wish to continue? (Yes or No)");
endOrNo = in.nextLine();
if ("yes".equalsIgnoreCase(endOrNo))
go = true;
else
go = false;
I wrote a program that asks the person for strings of numbers between 1-6 and returns the number of rolls it took to get the string. I want to validate the input so that the person doesn't enter a number bigger than 6 or smaller than 1 and I can't seem to figure out how to do that.
int SIDES = 6;
String userString = "null";
String answer = "null";
int length = 0;
do {
do {
System.out.print("please enter a string of 6 numbers you want to be rolled");
userString = keyboard.next();
while (length != SIDES) {
System.out.println("please enter a valid string number");
userString = keyboard.next();
}
length = userString.length();
} while ( length != SIDES); // I want to add the validation to this line
dieRoll(userString);
while (length != SIDES) {
userString = keyboard.next();
try {
int userStringNumber = Integer.parseInt(userString);
if(userStringNumber<1||userStringNumber>6)
throw new IllegalArgumentException();
} catch (NumberFormatException e) {
System.out.println("Please provide a number");
}
catch (IllegalArgumentException ex){
System.out.println("Number should be between 1 and 6");
}
}
This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 6 years ago.
public static void main(String[] args) {
{
Scanner reader = new Scanner(System.in);
System.out.println("Enter your name: ");
String n = reader.nextLine();
System.out.println("You chose: " + n);
}
{
Scanner reader = new Scanner(System.in);
System.out.println("Enter your age: ");
int n = reader.nextInt();
System.out.println("You chose: " + n);
}
{
Scanner reader = new Scanner(System.in);
System.out.println("Enter your email: ");
String n = reader.nextLine();
System.out.println("You chose: " + n);
}
}
If a user places anything else under Enter your age other than a number, how do I make it say that the input is not correct and ask again?
You can get the line provided by the user, then parse it using Integer.parseInt(String) in a do/while loop as next:
Scanner reader = new Scanner(System.in);
Integer i = null;
// Loop as long as i is null
do {
System.out.println("Enter your age: ");
// Get the input from the user
String n = reader.nextLine();
try {
// Parse the input if it is successful, it will set a non null value to i
i = Integer.parseInt(n);
} catch (NumberFormatException e) {
// The input value was not an integer so i remains null
System.out.println("That's not a number!");
}
} while (i == null);
System.out.println("You chose: " + i);
A better approach that avoids catching an Exception based on https://stackoverflow.com/a/3059367/1997376.
Scanner reader = new Scanner(System.in);
System.out.println("Enter your age: ");
// Iterate as long as the provided token is not a number
while (!reader.hasNextInt()) {
System.out.println("That's not a number!");
reader.next();
System.out.println("Enter your age: ");
}
// Here we know that the token is a number so we can read it without
// taking the risk to get a InputMismatchException
int i = reader.nextInt();
System.out.println("You chose: " + i);
No need to declare a variable scanner so often, simply once
care with nextLine(); for strings; presents problems with blanks, advise a .next();
use do-while
do
{
//input
}
while(condition);//if it is true the condition returns to do otherwise leaves the cycle
use blocks try{ .. }catch(Exception){..}
to catch exceptions mismatch-input-type exception is when the input is not what I expected in the example enter a letter when a number expected
Scanner reader = new Scanner(System.in);
int n=0;
do
{
System.out.println("Enter your age: ");
try {
n = reader.nextInt();
}
catch (InputMismatchException e) {
System.out.print("ERROR NOT NUMBER");
}
}
while(n<0 && n>100);//in this case if the entered value is less than 0 or greater than 100 returns to do
System.out.println("You chose: " + n);
Is there a problem in my while or for loops by chance or am I missing something? First run through works fine but on the second I get this:
Enter course NAME: class name
Enter course HOURS: 4
Enter course GRADE: 4.0
You have entered class: jeff graves, class hours: 4 and, class grade 4.0
Do you want to continue:
y
Enter course NAME: Enter course HOURS:
It works just fine using (scanner).next(); but then I can only take one word from the user and it will throw an error from the nextInt when it rolls over.
public class GetGrades { //open class GetGrades
public static void main(String[] args) {
/**creating new instance of scanner named input to read user input*/
Scanner input = new Scanner(System.in); // create new instance of scanner object
boolean repeat = true; //boolean value for while loop holding array input
String s; // create string to store user input value for exiting loops
/** create 3 arrays to store course name, hours, and grades*/
String[] name = new String[20]; //type string array for class name
int[] hours = new int[20]; // type int array for class hours
float[] grade = new float[20]; //type float array for class grade
outerloop: // set break point for nested for loops exit on user input
while(repeat != false) {// while loop with boolean value to let user exit array input
for (int i=0; i<name.length; i++) { //for loop for name array
System.out.print("Enter course NAME: "); //prompt user for input
name[i] = input.nextLine(); //read next line value and store in array name
System.out.print("Enter course HOURS: "); //prompt user for input
hours[i] = input.nextInt(); //read the next int and store in array hours
System.out.print("Enter course GRADE: "); //prompt user for input
grade[i] = input.nextFloat(); //read the next float value and store in array grade
/**Print line to console summing um what the user has entered*/
System.out.println("You have entered class: " + name[i] + ", class hours: " + hours[i] +
" and, class grade " + grade[i]);
/**prompt user if wanted to enter more grades, break loop on n or N*/
System.out.println("Do you want to continue:");
s = input.next();
if ( s.equals("y") || s.equals("Y")) { //open if statement
repeat = true;
} else { //close if and open else
break outerloop;
} //close else statement
}//close for loop with i as count
}//close while
input.next() will read the next word. input.nextLine() will read up until the next time you press enter.
This means that when you write "y" and hit enter, you've input both a word "y", as well as the next enter, filling in both prompts at the same time and causing the next prompt to be written.
You can simply replace your next() with nextLine() when you ask to continue:
System.out.println("Do you want to continue:");
s = input.next();
becomes
System.out.println("Do you want to continue:");
s = input.nextLine();
thereby reading both the "y" and the enter. The next prompt is now free to accept new input.
When you input the grade, for example 12.3 and enter, "input.nextFloat();" will only take "12.3" but not "enter", so "enter" will be taken by the next scanner.
In my opinion,
first, change "s = input.next()" to "s = input.nextLine()", but it will take the "enter" of previous scanner "grade[i] = input.nextFloat();", so, second, put it into a while loop as a condition. like this
while((s = input.nextLine()).equals("")) {}
therefore, it won't stop til get the expect input.
try this..
System.out.print("Do you want to continue:");
while((s = input.nextLine()).equals("")) {}
if (s.equals("y") || s.equals("Y")) { // open if statement
repeat = true;
} else { // close if and open else
break outerloop;
} // close else statement
I am writing a bank account program for my Comp Sci class, and need to search a .txt file for a account number a user enters (which is an int) and then pull out the next row which is the balance. i.e. the user enters the account #12345679 and i need to pull out the balance of it. Below is an example of the txt file
12345678
133.87
12345679
500.00
12345670
123.00
So far I have and I know that i'm going to have to put how to get the balance in the if statment
while (accountTries < 3)
{
System.out.println("Please enter your 8 digit account number");
accountNumber = console.next();
accountLength = accountNumber.length();
while (in.hasNextInt())
{
line = in.hasNextInt();
if (accountLength == 8 && line == accountNumber )
{
accountTries = 3;
}
}
System.out.println("INVALID ACCOUNT NUMBER.");
accountTries++;
}
}//End of while loop
Not sure what you're trying to do... but this doesn't seem right:
line = in.hasNextInt();
Shouldn't you be getting the value here? You're just testing to see if there's anything there, like you did in the "while" condition.
outer: while (accountTries < 3)
{
System.out.println("Please enter your 8 digit account number");
accountNumber = console.next();
accountLength = accountNumber.length();
while (in.hasNextLine())
{
line = in.nextLine();
result = in.nextLine();
if (accountLength == 8 && line.equals(accountNumber))
{
accountTries = 3;
break outer;
}
}
System.out.println("INVALID ACCOUNT NUMBER.");
accountTries++;
}
}//End of while loop
I used a labeled break to get out of the outer while (you can do the same with if statements and a done flag but I'm to lazy to do that here)
You can simply read file to String and split it by line separator(\n or \n\r).
For example :
String fileContent = //read String from file;
String[] elements = fileContent .split("\n");
for(int i =0; i< elements.length; i++){
if(i%2 ==0){
//get account number
}else{
//get balance
}
}