Java Do and While validation - java

I created this simple program where there is a password, for some reason if I input password the program will carry on executing even though I used do and while.
import java.util.Scanner;
public class PassCheck {
double password;
int UserInp;
public void Validation() {
do{
System.out.println("Please enter the password");
Scanner in = new Scanner(System.in);
int password = in.nextInt();
} while (password == 1111);
System.out.println("Please select whether you would like to workout area or perimeter");
System.out.println("Enter 1 for area and Enter 2 for perimeter");
Scanner in = new Scanner(System.in);
int UserInp = in.nextInt();
switch (UserInp){
case 1:
CircleArea CircleAreaObject = new CircleArea();
CircleAreaObject.area();
case 2:
}
}
}

You have two password variables. The "while" condition is using the method variable. You have another variable declared in the scope inside the while condition-- that one is not the one that the "while" condition is using.
So one solution is to pull out your "int password" declaration into a line immediately before the do/while loop. Then assign it inside the do/while loop scope. And remove the PassCheck password declaration in the class.

Your int password that you actually assign is only valid inside the brackets of your do { ... } block. In the while, you are referencing the double password which is never 1111.
do{
System.out.println("Please enter the password");
Scanner in = new Scanner(System.in);
int password = in.nextInt(); // This "password"...
} while (password == 1111); // is NOT the same variable as this...
In the while(password = 1111) you are referencing the double password (as someone already mentioned, why is this double? ). You cannot reference the local int password here, since it's scope is limited to the insides of the brackets above.

What you have done is to create a new variable password of type int in the scope of your do block, java let you do this because the pacakage-private password field declared at the beginning of your class is of type double rather than int like its's local counterpart. You can correct this problem by making the following changes to your class. Your class also had a lot of style and naming issues which I've cleaned up.
import java.util.Scanner;
public class PassCheck {
int password;
int userInp;
public void validation() {
do {
System.out.println("Please enter the password");
Scanner in = new Scanner(System.in);
password = in.nextInt();
} while (password != 1111);
System.out.println("Please select whether you would like to workout area or perimeter");
System.out.println("Enter 1 for area and Enter 2 for perimeter");
Scanner in = new Scanner(System.in);
int userInp = in.nextInt();
switch (userInp){
case 1:
CircleArea circleAreaObject = new CircleArea();
circleAreaObject.area();
case 2:
}
}
}

Related

Java. Scanner Trying to to a loop until user quits

I've been trying to make a while loop where I enter in a movie number until the user types 'q' for quit, but every time I enter a valid number, I have to enter it twice before it prompts me with the "Enter movie number" message again. And the break function doesn't work when I wish to leave the loop. I simply wish to enter in the movie number once and break out when I want to.
public class Main {
public static void main(String[] args) {
while(true)
{
System.out.println("Enter in movie number: ");
Scanner input = new Scanner(System.in);
if(!input.hasNextInt())
{
System.out.println("invalid input");
continue;
}
if (Integer.parseInt(input.next()) < 0)
{
System.out.println("invalid no negative numbers");
continue;
}
if(Objects.equals(input.next(), "q"))
break;
}
}
I tried other variations of the while loop, but a similar thing has happened.
I assume your intention is to get one line of input, and if it is a number, process it somehow, and if not check if the user wants to quit.
You've got a couple problems with your program, firstly, you're creating a new Scanner within the while loop, which creates unnecessary overhead. Second, you're trying to get 2 lines of input within your loop, you wait for the user to input an integer, then you try to parse that integer with input.next(). Afterwards, you call input.next() again to check if the user wants to quit. By calling next() twice, you're requiring the user to input 2 lines, causing the issue you were describing.
You can fix this by calling next() once and storing its return value in a variable, then check if it equals q for quit, otherwise you can parse an integer value from it.
Here is working code that applies fixes to these issues:
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(true) {
System.out.println("Enter in a movie number:");
// Get user input
String input = scanner.next();
// If the input equals q, we break out of the loop
if(input.equalsIgnoreCase("q")) break;
int intInput;
try {
// Get integer input
intInput = Integer.parseInt(input);
} catch(NumberFormatException e) { // Input was not a number
System.out.println("Invalid, must input a number");
continue;
}
if(intInput < 0) {
System.out.println("Invalid, no negative numbers");
continue;
}
}
}
}
Also, a small note, instead of using Object.equals to check if two strings are equal you can just use the equals method inside of the String class like so: str1.equals(str2).

Can't input anything after the User obj3 = new User(); part

i cannot input anything after the User obj3 part. Can anyone help me on what's wrong with it? i didn't know what to do already.
public class test {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
Administrator obj = new Administrator();
System.out.print("Enter user ID: ");
String userID = input.nextLine();
System.out.print("Enter user password: ");
int userPassword= input.nextInt();
System.out.print("Enter user Phone Number: ");
long phoneNo = input.nextLong();
Administrator obj1 = new Administrator(userID, userPassword);
Administrator obj2 = new Administrator(userID, userPassword, phoneNo);
User obj3 = new User();
System.out.println("ID : ");
String ID = input.nextLine();
System.out.println("Password : ");
int pass = input.nextInt();
User obj4 = new User(ID,pass);
if (userID == ID && userPassword==pass){
System.out.print("Login succesfully!");
}
}
}
It looks like a problem with the way you used Scanner. I tried to run this myself (with User and Administrator commented out), and it skipped over the ID: and Password: inputs.
Scanner has a few catches to it. One of them is that nextLong() doesn't grab all the input from a line, only the first long it finds, separated by whitespace. Which means that the Scanner is still on the previous line when you call nextLine(). It just grabs the remainder of what is on the line when you fetched the phone number.
The easiest way to fix this would be to get rid of all of your nextInt() and nextLong(), and replace them with nextLine(). Once you have done that, use Integer.parseInt() to convert the Strings that are outputted from nextLine() into Integers, or use Long.parseLong() to convert to Longs.
Also, you are comparing String like this.
if (userID == ID && userPassword==pass)
It might be better for you if you did it like this instead.
if (userID.equals(ID) && userPassword==pass)
Remember, .equals() is how you compare Strings (or any type of Object).

How to loop my password acceptance program

I am fairly new to java(as in started 2 days ago) and i would like to know how i could loop this program. I tried to do the do while function but it keeps saying that my variables cannot be resolved as a variable.
This is the code:
class GS1 {
public static void main(String[]args){
do {
System.out.println("Enter your password");
Scanner F_pass = new Scanner(System.in);
String f_word= F_pass.next();
System.out.println("Verify Password");
Scanner Pass = new Scanner(System.in);
String word = Pass.next();
} while(f_word != word);
}
}
This seems like it would work. Typically you only need one instance of a Scanner object, and it will work throughout the entire class--depending on the scope that you use.
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
String origPass = "Original";
String verify = "Verify";
while(!origPass.equals(verify)){
System.out.println("Enter your password");
origPass = input.nextLine();
System.out.println("Verify your password");
verify = input.nextLine();
}
}
All I did was compare the values of the two string. If they are not the same, your program will repeat until the condition is satisfied. You can add a print statement to let the user know it was an incorrect password should they not have matching values. Hope this is what you were looking for.

Why won't my password do-while loop in Java won't Work? What did I do wrong?

I am having a problem with a do-while loop. It has two if statements inside of it. The program is supposed to take your username and password (which you enter) and then confirm them by having you type them in again. When you type them again, the have to be the same as the first time you typed them. The do-while loop is supposed to stop when boolean redo is set to false, (it gets set to false when you re-enter your username and password correctly) however the loop keeps going, even though it says that you got the username and password correct. (It says Welcome, (Username)) then the loop goes again and asks you to re-enter your username and password. How can I stop this loop after getting the correct password? Please help.
package Pack1;
import java.util.Scanner;
public class class1 {
public static void main(String[] args){
String Username; //Used to set the original username
String Password; //Used to set the original password
String Usernameuse; //Used as a test. This one has to be equal to the original username.
String Passworduse; //Used as a test. This one has to be equal to the original password.
boolean redo; //This is to determine whether the do-while loop will repeat.
Scanner in1 = new Scanner(System.in); //getting the original username
System.out.println("Enter your desired username");
Username = in1.nextLine();
Scanner in2 = new Scanner(System.in); //getting original password
System.out.println("Enter your desired password");
Password = in2.nextLine();
System.out.println("Identity Confirmation-- Enter your account information");
do{
Scanner in3 = new Scanner(System.in); //gets second username which has to be equal to original
System.out.println("Please Enter your Username");
Usernameuse = in3.nextLine();
Scanner in4 = new Scanner(System.in); //gets second password which has to be equal to the original
System.out.println("Please Enter your Password");
Passworduse = in4.nextLine();
if(Usernameuse.equals(Username) && Passworduse.equals(Password)){ //determines if both are true
System.out.println("Welcome, " + Username);
redo = false; //makes redo = false
}
if(!Usernameuse.equals(Username) || !Passworduse.equals(Password)){ //determines if either one is false
System.out.println("Either Username or Password are incorrect, please redo");
redo = true; //makes redo = true
}
} while(redo = true); //Is supposed to stop looping when you set redo to false, by entering correct username and password
System.out.println("You are now on your secret account!");
}
}
while(redo = true);
This is an assignment instead of a comparison. This will always be true.
while(redo == true);
is what you meant to type, but
while(redo);
is what you really want because it makes it impossible to commit the assignment-instead-of-comparison error.
When you compare a constant other than a boolean and a variable it's always best to put the constant first for the same reason.
if (1 == someInt)
instead of
if (someInt == 1)
If you accidentally use = instead of == the constant-first form won't compile.
while(redo = true)
Results in always true because it is equal to while(true).
= is assignment
== is comparison.

Both next() and nextLine() not helping to store name with spacing

I am currently using a Scanner to record the user input which is a String and print it out. If the user input is a single name such as Alan, it works fine. If I enter a name with spacing such as Alan Smith, it returns an error saying InputMisMatchException.
I read around similar cases here and they advised to use nextLine() instead of next(). It made sense but that doesn't work for me either. When I use a nextLine(), it immediately skips the step where I enter the name and goes back to the starting of the loop asking me to input choice again. Please advice how I can correct this. Thank you.
import java.io.IOException;
import java.util.Scanner;
public class ScannerTest {
static String name;
static Scanner in = new Scanner(System.in);
static int choice;
public static void main(String[] args) {
while(choice != 5){
System.out.print("\nEnter Choice :> ");
choice = in.nextInt();
if(choice == 1){
try{
printName();
}
catch(IOException e){
System.out.println("IO Exception");
}
}
}
}
private static void printName()throws IOException{
System.out.print("\nEnter name :> ");
name = in.next();
//name = in.nextLine();
if (name != null){
System.out.println(name);
}
}
}
Try this instead: add name = in.nextLine(); after choice = in.nextInt();.
Then try replacing name = in.next(); with name = in.nextLine();
Explanation: After the scanner calls nextInt() it gets the first value and leaves the rest of the string to the \n. We then consume the rest of the string with nextLine().
The second nextLine() is then used to get your string parameters.
The problem is easy: when you prompt the user to enter his/her choice, the choice will be an int followed by a new line (the user will press enter). When you use in.nextInt() to retrieve the choice, only the number will be consumed, the new line will still be in the buffer, and, so, when you call in.nextLine(), you will get whatever is between the number and the new line (usually nothing).
What you have to do, is call in.nextLine() just after reading the number to empty the buffer:
choice = in.nextInt();
if (in.hasNextLine())
in.nextLine();
before to call name = in.next(); do this in = new Scanner(System.in);
the object need rebuild itself because already has value.
good luck

Categories

Resources