System.out.println() is being skipped - java

My prompt "Please Enter your ID" just after the second for loop is not appearing, it goes straight to "Please enter your password." It also skips alot of code from the Login Prompt to the Password prompt. If you have any ideas as to why it behaves like this please share it with me thanks.
public void main(String[] args){
Accounts Accounts = new Accounts();
Scanner kb = new Scanner(System.in);
System.out.print("Please create a login ID and hit \"ENTER\": ");
Login = kb.nextLine();
for(;;){
if(!Accounts.isTaken(Login)){
System.out.print("Please create a password and hit \"ENTER\": ");
PW = kb.nextLine();
if(Accounts.validPW(PW)){
Accounts.createAccount(Login, PW);
break;
}
}
}
System.out.print("Do you wish to Log in ? (Y/N): ");
String response = kb.nextLine();
if((response=="y")||(response=="Y")){
for(;;){
//Not Being Shown
System.out.println("Please enter your ID: "); // ?????? Where are you?????
Login = kb.nextLine();
Accounts.login(Login);
//Goes straight here
System.out.print("Please enter your Password: ");
if ((Accounts.isValid(Login))&&(Accounts.checkAuth(kb.nextLine()))){
break;
}
else{
System.out.println("Invalid Login-Password!");
}
}
}
System.out.println("Please enter your Password: ");
System.out.println("LOGIN AUTHORIZED: "+Accounts.checkAuth(kb.nextLine()));
}

Instead of
(response=="y")||(response=="Y")
use
(response.equals("y"))||(response.equals("Y"))

you are using == operator to check string equality. use equals() method.
== operator:
For primitive variables checks if two primitives have same value.
For objects: checks if two reference variables point(refer) to the same object.
equals() method
Checks if two objects are meaningfully equal.
if((response=="y")||(response=="Y")){
should be
if((response.equals("y"))||(response.equals("Y"))){
or even better
if((response.equalsIgnoreCase("y"))){

Since java is reference-based, response has a differend id than "y". You should use
response.equals("y")

Related

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 let the user input back to the former question

I write a code to let the user input cruise id first and then enter the ship name.
At first, I want to detect whether the user input integer type, if not, the user has to re-enter the first question again.
But in my code, it will directly print the second question instead of go back to the first question and ask again. Same, for the second question, I also want it return back and ask user to input again if the input is wrong
Please help me for that. Thanks!!
try{
System.out.println("Input Cruise ID:");
sc1 = sc.nextInt();
}catch(Exception e){
System.out.println("Please Enter integer:");
sc.nextLine();
}
System.out.println("Input ship name :");
try{
sc2 = sc.next();
}catch(Exception e){
if( sc2 != "Sydney1" || sc2 !="Melmone1"){
System.out.println("Oops!! We don't have this ship!! Please enter the ship name : Sydney1 or Melbone1");
}
}
I write a code to let the user input cruise id first and then enter the ship name. At first, I want to detect whether the user input integer type, if not, the user has to re-enter the first question again.
What you need is an input validation. try-catch block itself will not create an endless loop to reprompt the user should the input is not an integer. What you need is a while loop.
You can use a do-while loop as follows so that it runs first before performing a check:
String input = ""; //just for receiving inputs
do{
System.out.println("Input Cruise ID:");
input = sc.nextInt();
}while(!input.matches("[0-9]+")); //repeat if input does not contain only numbers
int cruiseID = Integer.parseInt(input); //actual curiseID in integer
To perform validation for your second input (i.e, your shipName, you need another while loop which encloses your prompt for input).
try-catch block are mainly used to handle exceptional cases. Try not to misuse it as a control statement for your implementations.
You can add more checks inside the while loop itself. For example, checking if the number is a negative number or zero etc. For example
while (true) {
try {
System.out.println("Input Cruise ID:");
cruiseId = sc.nextInt();
if(cruiseId <=0){
System.out.println("Please Enter integer:");
sc.nextLine();
}
break; // break when no exception happens till here.
} catch (Exception e) {
System.out.println("Please Enter integer:");
sc.nextLine();
}
}

How to prevent Java scanner from inputing spaces

I'm trying to prevent the user from inputting spaces or no values.
but nothing works. Even with no entered values program goes further without printing my error. What am I doing wrong?
my code example
Scanner nameScan = new Scanner(System.in);
System.out.print("Input your name: ");
String newcomer = nameScan.nextLine();
player.setName(newcomer);
String userName = player.getName();
userName = userName.trim();
if (userName.length()==0) {
System.out.println(" ");
System.out.println("You have to set up a player name first... ");
System.out.println(" ");
}
else {...
As #11thdimension said, you have to validate the input.
You can do something like:
if (newcomer.isEmpty()) {
System.out.println("Please write something");
}
Or you can do a while loop and keep asking for a correct input.
Your code
if(username.length() == 0)
will not check whether the username contains space because space is counted towards the length of the String.
To check for empty String input(which may contain space(s)), you can do:
if("".equals(username.replaceAll("\\s+",""))) //or
if("".equals(username.trim()) //or
if(username.isEmpty())
Further more, you would want to use a do-while loop for validation instead of using an if-statement.

Java Do and While validation

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:
}
}
}

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.

Categories

Resources