public static void main(String args[])throws IOException{
validNumbers = new int[200];
Scanner sc1 = new Scanner(new File("validNumbers.txt"));
int i = 0;
while(sc1.hasNextInt()) {
validNumbers[i++] = sc1.nextInt();
}
// Creating loop for what the user enters
boolean newValidator = true;
Scanner scanner = new Scanner(System.in);
while(newValidator) {
System.out.print("Enter the account number: ");
String num = scanner.nextLine();
// If found, the calculations will get displayed
if(validator(num)) {
System.out.print("The calculated value to this account is: " + calculator(num));
newValidator = false;
System.out.println("\n" + "Would you like to enter another account number? (y/n)");
String ans = "";
ans = scanner.nextLine();
// Needed the false, if not the code would keep asking to "Enter account number: "
if (ans.equals("y")) {
System.out.print("Enter the account number: ");
String num2 = scanner.nextLine();
System.out.print("The calculated value to this account is: " + calculator(num2));
} else if(ans.equals("n")) {
newValidator = false;
System.out.println("** Program Exit **");
}
}
// Wanted to add a loop for the user to decide if they want to continue iff wrong account is inputed
else {
System.out.println("Not valid account number" + "\n\n" + "Would you like to try again? (y/n)");
String ans = "";
ans = scanner.nextLine();
if(ans.equals("y")) {
newValidator = true;
}
// How the program terminates if the user does not wish to continue
else if(ans.equals("n")) {
newValidator = false;
System.out.println("Not valid input, the program is now terminated!");
}
}
}
}
}
(Using Java) The code is doing the following:
1.) When the user enters a correct number it sees the number(in the file) and adds the digits
2.) When it is not in the file, it knows the number is not there and tells the user to try again and if the user doesn't want to, it ends the program.
***** (Using Java) What the code is not doing:
1.) After they entered the right code, the program is to ask the user if they want to enter another account(with the adding of an account if so). Then this is where I have the problem, the loop is ending after this second go and I need it to keep asking if they want to enter another account number unit the user wants to exit.*****
There's no need to have a nested question asking for another account number, the while loop itself will ask the user again when it repeats.
Simply ask the user if they want to enter another and then exit the loop if the don't. The while loop drops out when "newValidator" is set to false:
boolean newValidator = true;
while(newValidator) {
System.out.print("Enter the account number: ");
String num = scanner.nextLine();
if(validator(num)) {
System.out.println("The calculated value to this account is: " + calculator(num));
}
else {
System.out.println("Not valid account number!");
}
System.out.println("\n\nWould you like to enter another account number? (y/n)");
String ans = scanner.nextLine();
if (ans.equals("n") || ans.equals("N")) {
newValidator = false;
}
}
System.out.println("** Program Exit **");
Related
I am new to JAVA and have been using IDE, to cut it short whenever I try to check if bag contains a string thats the same as the given input JAVA counts it as FALSE, even if the if statements such as "is input equal to 1" and "is 1 inside the bag" pass as true. here is an excerpt from my code, I would appreciate any help and advice.
//user input
System.out.println("Please enter a string (to exit, enter 'exit'): ");
a=sc.next();
if (a.equals("1")) {System.out.println("adpkgnosıfbgojadnofabsndofgna");}
if (ValidAnswers1.contains("1")) {System.out.println("adpkgnosıfbgojadnofabsndofgna");}
//error detection. after I learn bag it will become if bag contains string s.
if (ValidAnswers1.contains(a)) {correct_input=1;} else {correct_input=0;}
while (correct_input==0)
{
System.out.println("you entered:"+ a+".");
System.out.println("Please enter a valid string (to exit, enter 'exit')");
a = sc.next();
if (ValidAnswers1.contains(a)) {correct_input=1;} else {correct_input=0;}
}
the console prints out both the keymashes and then diverts into the while loop. I have checked to make sure the while loop is correct by testing with fixed variables, but when scanner is used it seems to have an error.
I didn't understand, what you really want, i did the test and a yet is working fine. take a look at the class, maybe is some error in the variables or something
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String a;
String ValidAnswers1 = "1";
int correct_input = 0;
//user input
System.out.println("Please enter a string (to exit, enter 'exit'): ");
a = sc.next();
if (a.equals("1")) {
System.out.println("adpkgnosıfbgojadnofabsndofgna");
}
if (ValidAnswers1.contains("1")) {
System.out.println("adpkgnosıfbgojadnofabsndofgna");
}
//error detection. after I learn bag it will become if bag contains string s.
if (ValidAnswers1.contains(a)) {
correct_input=1;
} else {
correct_input=0;
}
while (correct_input==0) {
System.out.println("you entered:"+ a+".");
System.out.println("Please enter a valid string (to exit, enter 'exit')");
a = sc.next();
if (ValidAnswers1.contains(a)) {
correct_input=1;
} else {
correct_input=0;
}
}
}
Here is the output:
Please enter a string (to exit, enter 'exit'):
a
adpkgnos?fbgojadnofabsndofgna
you entered:a.
Please enter a valid string (to exit, enter 'exit')
1
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
//Create a new Object Scan in the memmory
Scanner scan = new Scanner(System.in);
String input;
String[] validAnswers = new String[]{"1","2","3","exit"};
boolean isCorrect = false;
//The method equalsIgnoreCase means that the text can be in uppercase too;
/*The number between the tags "[]" means the number in the array since arrays
starts with number "0" */
do{
System.out.println("Please enter a string (to exit, enter 'exit'): ");
input = scan.next();
if(input.equalsIgnoreCase(validAnswers[0])){
isCorrect = true;
System.out.println("Number 1");
}else if(input.equalsIgnoreCase(validAnswers[1])){
isCorrect = true;
System.out.println("Number 2");
}else if(input.equalsIgnoreCase(validAnswers[2])){
isCorrect = true;
System.out.println("Number 3");
}else if(input.equalsIgnoreCase(validAnswers[3])){
isCorrect = true;
System.out.println("EXIT!");
//You could use the method System.exit(0) to finish the program;
//If you put "1" in the exit value means that the prgram finished with some error;
//System.exit(0);
}else{
//If the Answers is different from all of the others;
System.out.println("you entered: " + input +".");
System.out.println("Please enter a valid string (to exit, enter 'exit')");
}
}while(isCorrect != true);
//I used the method do{}while because it's the only method that will exacute at least once;
}
boolean loop = false;
double numberOfStudents;
System.out.print("Enter a number: ");
if ((scnr.nextLine().trim().isEmpty()) ) {
loop = true;
}
while (loop) {
System.out.println("Enter a number");
if (scnr.hasNextDouble() ){
System.out.println("Loop has stopped");
numberOfStudents = scnr.nextDouble();
loop = false;
}
}
System.out.println("You're outside the loop!");
I'm trying to get the program to say "Enter a number" until the user has entered an actual number (no white spaces or letters or signs). When the user has entered a number, it sets numberOfStudents equal to that number and breaks out of the loop.
But if you hit enter twice, it doesn't iterate. It only displays "Enter a number" once.
What is wrong with the loop logic? Why isn't it looping until valid input is taken?
For the actual answer to your question of "Why doesn't 'Enter a number' display more than once?" see Tom's comment (update: Tom's answer).
I've rewritten your loop in a way which preserves your code, but also makes it a little easier to handle format exceptions (though at the risk of silently swallowing an exception -- should be acceptable for this use case).
Can be up to you to use this design, here is an SO post on why empty catch blocks can be a bad practice.
public static void main(String args[])
{
boolean loop = true;
double numberOfStudents;
Scanner scnr = new Scanner(System.in);
while(loop){
System.out.print("Enter a number: ");
String input = scnr.nextLine();
try{
numberOfStudents = Double.parseDouble(input);
loop = false;
}catch(NumberFormatException e){
}
}
System.out.println("You're outside the loop!");
}
Output:
Enter a number:
Enter a number:
Enter a number:
Enter a number: 50
You're outside the loop!
First of all: Since you're reading from System.in a call to the input stream will block until the user entered a valid token.
So let's check first scan using your scnr variable:
scnr.nextLine()
nextLine() reads everything til the next line delimiter. So if you just press return, then it will successfully read it and will perform the next stuff.
The next call is:
scnr.hasNextDouble()
This call expects a "real" token and ignores white spaces, except as a delimiter between tokens. So if you just press return again it doesn't actually read that input. So it still waits for more (for the first token). That is why it stucks in your loop and you won't get another "Enter a number" output.
You can fix that by either enter a real token, like a number, or by changing the loop like trobbins said.
I hope you now understand your program flow a bit more :).
While trobbins code basically solves your problem, it's bad practice to use exceptions for flow control.
I used a small regexp to check if the value is a number. But this example is not complete, it will still crash it the user enters for example two decimal points. So you would need to create a proper number check or just use integers where the check is much easier.
Someone in the comments pointed out that people may want to enter scientific notation like 5e10, so this would also be another case to check for. If this is just some code you need as a proof of concept or something quick and dirty, you can go with the exception handling method but in production code you should avoid using exceptions this way.
double numberOfStudents;
Scanner scnr = new Scanner(System.in);
while(true) {
System.out.print("Enter a number: ");
String input = scnr.nextLine().trim();
if(input.matches("^[0-9\\.]{1,}$")) {
System.out.println("Loop has stopped");
numberOfStudents = Double.parseDouble(input);
break;
}
}
System.out.println("You're outside the loop!");
The following code should help you:
double numberOfStudents = 0;
Scanner scnr = new Scanner(System.in);
boolean readValue = false; //Check if the valid input is received
boolean shouldAskForNumber = true; //Need to ask for number again? Case for Enter
do {
if (shouldAskForNumber) {
System.out.print("Enter a number:");
shouldAskForNumber = false;
}
if (scnr.hasNextDouble()) {
numberOfStudents = scnr.nextDouble();
readValue = true;
} else {
String token = scnr.next();
if (!"".equals(token.trim())) { //Check for Enter or space
shouldAskForNumber = true;
}
}
} while (!readValue);
System.out.printf("Value read is %.0f\n", numberOfStudents);
System.out.println("You're outside the loop!");
Update
Understood the following statement in question different way:
But if you hit enter twice, it doesn't loop back. It only displays
"Enter a number" once.
The code is set to print "Enter a number" only once if the user hits RETURN/ENTER or enters space character. You may remove the special check and use the code if needed.
import java.util.Scanner;
public class Testing {
public static boolean checkInt(String s)
{
try
{
Integer.parseInt(s);
return true;
} catch (NumberFormatException ex)
{
return false;
}
}
public static void main(String[] args) {
boolean loop = false;
double numberOfStudents;
Scanner scnr = new Scanner(System.in);
String input = "";
while (!(checkInt(input))) {
System.out.println("Enter a number");
input = scnr.nextLine();
}
numberOfStudents = Integer.parseInt(input);
System.out.println("Number of students: " + numberOfStudents );
}
}
//this code is working fine, if you want you check it out.
//In your code your taking another input if the first is an int/double; if the first input is not a number then you have mentioned to take input again..
Use a debugger to see what the code is actually doing. Here's a guide on debugging in Eclipse. After you have finished debugging your code, you will probably know what the problem is.
Below code will help you
boolean loop = true;
double numberOfStudents;
Scanner scnr = new Scanner(System.in);
System.out.print("Enter a number: ");
String input = scnr.nextLine();
while(!scnr.hasNextDouble()){
System.out.print("Enter a number: ");
try{
numberOfStudents = Double.parseDouble(input);
break;
}catch(NumberFormatException e){
}
input = scnr.nextLine();
}
System.out.println("You're outside the loop!");
The following code is working,
boolean loop = true;
double numberOfStudents;
Scanner scnr=new Scanner(System.in);
while(loop) {
System.out.println("Enter a number");
if ((scnr.nextLine().trim().isEmpty()) ) {
loop = true;
}
if (scnr.hasNextDouble() ){
System.out.println("Loop has stopped");
numberOfStudents = scnr.nextDouble();
loop = false;
}
}
System.out.println("You're outside the loop!");
The output is,
run:
Enter a number
hj
po
Enter a number
lhf
Enter a number
o
Enter a number
p
Enter a number
a
Enter a number
34
Loop has stopped
You're outside the loop!
You have to scan the next line if you want to get more values form the scanner again. The code should be like:
while (loop) {
System.out.println("Enter a number");
if(!(scnr.nextLine().trim().isEmpty())){
if (scnr.hasNextDouble() ){
System.out.println("Loop has stopped");
numberOfStudents = scnr.nextDouble();
loop = false;
}
}
}
I am trying to create a simple Java program where the user should input his age. If the user entered for example a letter instead of a number, he will get a message.
What I would like to do is that in addition to the message the user should be asked for another input and that input will be checked again to see if it is a number.
Can anyone know how can I achieve that?
System.out.println("2 - Set The Age");
Scanner b = new Scanner(System.in);
if (b.hasNextDouble()) {
double lage = b.nextDouble();
setAge(lage);
addEmployeeMenu();
} else {
System.out.println("You should type only numbers!");
}
You can use a while loop like this
Scanner b = new Scanner(System.in);
double lage;
while (true) {
System.out.println("2 - Set The Age");
if(b.hasNextDouble()){
lage = b.nextDouble();
break;
}else b.nextLine();
}
The point is, get your number and check it inside a while loop, repeat as long as the input is not correct
You can also use NumberFormatException:
while (true) {
System.out.println("Set the age: ");
String input = sc.next();
try {
int x = Integer.parseInt(input);
System.out.println("Your input '" + x + "' is a integer");
break;
} catch (NumberFormatException nFE) {
System.out.println("Not an Integer");
}
}
Write a program called PasswordChecker that does the following:
1. prompts the user to enter a password
2. prompts the user to renter the password
3. checks to ensure that the two password entries are identical
4. (for the first three attempts) Repeats steps 1 through 3 until the password is correctly entered twice.
5. After the 3rd attempt, if the user doesn’t enter the password correctly, the program needs to display an informative message indicating user account is suspended.
My code:
import java.util.Scanner;
public class passwordChecker{
public static void main(String [] args){
String pw1;
String pw2;
int count=0;
Scanner keyboard = new Scanner(System.in);
do{
System.out.println("Enter the password:");
pw1 = keyboard.nextLine();
System.out.println("Renter the password:");
pw2 = keyboard.nextLine();
count++;
if(pw1.equals(pw2))
System.out.println("Correct");
else if(count>=3)
System.out.println("Account is suspended");
while(pw1==pw2||count>3);
}
}
You seem to be missing a closing brace (you open the do but don't close before while). Your first condition should be count < 3 and I think you want to loop while the two String(s) are not equal. Something like,
do {
System.out.println("Enter the password:");
pw1 = keyboard.nextLine();
System.out.println("Renter the password:");
pw2 = keyboard.nextLine();
count++;
if (pw1.equals(pw2)) {
System.out.println("Correct");
} else if (count >= 3) {
System.out.println("Account is suspended");
}
} while (count < 3 && !pw1.equals(pw2));
Edit
The reason you don't use == (or !=) for Object types is that it tests reference equality only. You want to test for value equality (these String(s) came from different lines, so they won't compare equal by reference).
Do it simply
public class PasswordChecker {
public static void main(String[] args) {
String pw1;
String pw2;
int count = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the password:");
pw1 = keyboard.nextLine();
while(true){
System.out.println("Renter the password:");
pw2 = keyboard.nextLine();
if (pw1.equals(pw2)) {
System.out.println("Correct");
break;
} else if(count == 3){
System.out.println("Account is suspended");
break;
}
count++;
}
}
}
First time posting, and people here seem helpful.
I'm currently coding my 2nd assignment of a simple bank atm/account. My login code for the users pin is not doing the following.
1. Returning back to the start of the loop when the pin is not found in the array
2. making the program stop if the pin is incorrect
Here is the snippet of the login script, only. The problem lies in the while (menuChoice==1){} loop.
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
boolean userLogin = false; //Flag for user login authorization
boolean progOn=true; //confirmation that program is still be running
int num = 0, i = 0;
int Bal[] = {500, 250, 400, 700};
String Names[] = {"Niall", "Sean", "John", "Connor"};
String pin[] = {"1234", "2345", "3456", "4567"};
String menu2 = "\n1. Deposit \n2. Withdrawal \n3. Balance \n4: Change pin \n5: Exit";
String pinChoice = "", pinChange="";
int sub = 0; //To keep the subscript
String startMenu = ""; //The entered choice for the Start menu as a string
int menuChoice = 0; //The entered choice for the menu as an int
//--------------------
//login script
//--------------------
while (progOn == true) {
System.out.println("------------------------");
System.out.println("Welcome! Please select an option...\n");
System.out.println(">1. Login");
System.out.println(">2. Quit");
System.out.println("------------------------");
startMenu = in.next();
while (!startMenu.matches("[1-2]")) { //If the user enters a non digit, give message and return
System.out.println("\nError. Please enter a valid Menu option.\n");
System.out.println(">1. Login");
System.out.println(">2. Quit");
System.out.print("Please select an option\n"); //Ask the user to choose again
startMenu = in.next();
}//end while loop
menuChoice = Integer.parseInt(startMenu); //Parse the string to an int
while (menuChoice == 1) { //While loop to carry out the users choice
System.out.println("------------------------");
System.out.println("Please enter your pin number: ");
System.out.println("------------------------");
pinChoice = in.next();
while (!pinChoice.matches("\\d{4}")) { // 4 numbers only message to the user, if number is shorter or longer than 4
System.out.println("------------------------");
System.out.println("Error, must be a 4 number pin only! Please retry:");
System.out.println("------------------------");
pinChoice = in.next();
}
for (i = 0; i < Names.length; i++) {
//Check if PIN exists
if (pinChoice.matches(pin[i])) {
userLogin = true; //If the PIN exists (true) the user is brought to the main menu
System.out.println("------------------------");
System.out.println("Please select a option from the menu...");
sub = i; //sub is the array number stored of that account
}//end if PIN matches
}
if (userLogin == false) { //If the PIN doesn't exist
System.out.print("\nPin does not exist\n\n"); //Tell the user and bring them back to the main menu
}//end if no user found
break;
}// end loop menuChoic == 1
while (menuChoice == 2) { //user chooses to Leave the program
System.out.print("\nThank you, goodbye\n");
System.exit(0); //Exits the program
break;
}//end menuChoice==2
//--------------------
//end login script
//--------------------
}
}
I know the rest of the program works perfectly. I just can't get this one small part.
Bare in mind this is my first year in Comp. Sci. and my lecturer hasn't shown us any object orientating, thus he's not letting us any of it only the basics.
Thanks for looking! :)
In loops, you should use local variable. You have got a global variable
int i;
Try to change i to int ii in your loop
for (int ii = 0; ii < Names.length; ii++) {
//Check if PIN exists
if (pinChoice.matches(pin[ii])) {
userLogin = true; //If the PIN exists (true) the user is brought to the main menu
System.out.println("------------------------");
System.out.println("Please select a option from the menu...");
sub = ii; //sub is the array number stored of that account
}//end if PIN matches
}
After a good 2 hours I've figured it out and added an extra step to the login process.
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
boolean userLogin = false; //Flag for user login authorization
boolean progOn=true; //confirmation that program is still be running
int num=0;
int Bal[] = {500,250,400,700};
String Names[]={"Niall", "Chris", "John", "Connor"};
String pin[]= {"1111","2222","3333","4444"};
String menu2= "\n1. Deposit \n2. Withdrawal \n3. Balance \n4: Change pin \n5: Exit";
String pinChoice = "", pinChange="", strNameChoice="", startMenu="";
int sub=0, sub2=0; //To keep a subscript
int menuChoice=0 ; //The entered choice for the menu and name as an int
int nameChoice=0;
//--------------------
//login script
//--------------------
while(progOn==true){
System.out.println("------------------------");
System.out.println("Welcome! Please select an option...\n>1. Login\n>2. Quit");
System.out.println("------------------------");
startMenu=in.next();
while(!startMenu.matches("[1-2]")){ //If the user enters a non digit, give message and return
System.out.println("\nError. Please enter a valid Menu option.\n>1. Login\n>2. Quit\nPlease select an option\n"); //Ask the user to choose again
startMenu=in.next();
}//end while loop
menuChoice=Integer.parseInt(startMenu); //Parse the string to an int
while(userLogin==false){ // loop to verify that the login is correct, and a rest point.
while(menuChoice==1){ //While loop to carry out the users choice
System.out.println("------------------------");//User name selection
System.out.println("Please select the number of your user name. \n1> " +Names[0]+"\n2> " +Names[1]+"\n3> " +Names[2]+"\n4> " +Names[3]);
System.out.println("------------------------");
strNameChoice=in.next();
while(!strNameChoice.matches("[1-4]")){ // 4 numbers only message to the user, if number is shorter or longer than 4
System.out.println("------------------------");
System.out.println("Error, must be a one of the 4 numbers only! Please retry:");
System.out.println("------------------------");
strNameChoice=in.next();
}
nameChoice=Integer.parseInt(strNameChoice);
sub2=nameChoice-1;
System.out.println("------------------------"); //PIN ENTRY
System.out.print("Please enter your Pin\n");
pinChoice = in.next();
while(!pinChoice.matches("\\d+")){
System.out.print("\nError, digits only\n");
System.out.print("\nEnter your PIN\n>");
pinChoice = in.next();
}//end while PIN is non digits
for(int i=0;i<Names[sub2].length();i++){ //Check if PIN exists inside the loop
if(pinChoice.matches(pin[sub2])){
userLogin = true; //If the PIN exists (true) the user is brought to the main menu
sub = sub2-1; //sub is the array number stored of that account
}//end if PIN matches
}
if(userLogin == false){ //If the PIN doesn't exist
System.out.print("\n------------------------");
System.out.print("\nPin entered is incorrect \nPlease try again \n");
}//end if no user found
break;//Tell the user and bring them back to the main menu
}// end loop menuChoice==1
while(menuChoice==2){ //user chooses to Leave the program
System.out.print("\nThank you, goodbye\n");
System.exit(0); //Exits the program
break;
}//end menuChoice==2
}
//--------------------
//end login script
//--------------------
My simple mistake was that I had not put in my loop to flag whether the login was true or not, making the break;, for the incorrect pin, useless.
while(userLogin==false){ // loop to verify that the login is correct, and a rest point.
while(menuChoice==1){
Your while loop condition is while (menuChoice ==1), but within the loop the value of menuChoice never changes. Therefore, the loop can never be escaped. What you will need to do is change the value of menuChoice or add the break; line in the section where the PIN does not exist so that when that logic is reached, you can exit the loop.
I think the cleanest solution would be to move your break; to within the if condition userLogin == false
Good luck!
Replace
if (pinChoice.matches(pin[i]))
with
if (pinChoice.equals(pin[i]))
To check the pinChoice is equal to arrayElement use equals method.
Also the iteration of the for below loop :
for (i = 0; i < Names.length; i++)
must iterate to the size of pin array instead Names length