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

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

Related

How can I grab an integer of any length from a string input

So I've been trying to write a program where it will be able to get any integer from a string input despite it's length. I've only been able to get it if the length of the integer is 1. Here is my code so far with methods from another class I wrote.
Scanner input = new Scanner(System.in);
Object user1 = new Object();
String user1Input = null;
System.out.println("Please enter coins");
user1Input = input.nextLine();
while(!(user1Input.contains("end"))){
if(user1Input.contains("Quarters")){
user1.depositQuarters(Character.getNumericValue(user1Input.charAt(0)));
}
}
So this code I have so far, say I enter "2 Quarters" it will return me the balance of $0.50 But if I enter "20 Quarters" it will return me $0.50 as well. I have tried another way of having declaring another variable
System.out.println("Please enter coins");
int coins = input.nextInt();
String user1Input = input.nextLine();
And then the same while loop with if-statements follows this and returns an error.
Any help would be appreciated. Thanks
If you want to stay with your first approach you can change user1Input to replace the " Quarters" portion. Something like this:
user1.depositQuarters(Integer.parseInt(user1Input.replace(" Quarters", "")));
Hope this helps.
Please try this (I have tested the code); if it works, please then replace the second "System.out.println" to "user1.depositQuarters":
Scanner input = new Scanner(System.in);
Object user1 = new Object();
String user1Input = null;
System.out.println("Please enter coins");
user1Input = input.nextLine();
while(!(user1Input.contains("end"))){
if(user1Input.contains("Quarters")){
System.out.println(Integer.parseInt(user1Input.split(" ")[0]));
break;
}
}
Thanks!
A Scanner might do all the work for you:
int ncoins = input.nextInt();
int coinName = input.nextLine().trim();
will, with an input of "40 Quarters" give you 40 in ncoins and "Quarters" in coinName.
This will work even with spaces preceding the number or following the name.

How to use the Scanner class properly?

I'm doing an assignment for class. For some reason the program completely skips the part where the variable name is supposed to be typed in by the user. I can't think of any reason why it's behaving this way, since the rest of my code that is after the cardType part (which asks for things such as String and int types work fine and in order.
System.out.println("Enter the card information for wallet #" +
(n+1) + ":\n---\n");
System.out.println("Enter your name:");
String name = scan.nextLine();
name = capitalOf(name);
System.out.println("Enter card type");
String cardType = scan.nextLine();
cardType = capitalOf(cardType);
You probably need to consume the end of the last line you read prior to trying to get the user name :
scan.nextLine(); // add this
System.out.println("Enter the card information for wallet #" +
(n+1) + ":\n---\n");
System.out.println("Enter your name:");
String name = scan.nextLine();
name = capitalOf(name);
System.out.println("Enter card type");
String cardType = scan.nextLine();
cardType = capitalOf(cardType);
It is behaving this way because I am quite sure you used the same scanner object to scan for integers/double values before you used it to scan for name.
Having said that does not mean you have to create multiple scanner objects. (You should never do that).
One simple way to over come this problem is by scanning for strings even if you are expecting integers/doubles and cast it back.
Scanner scn = new Scanner(System.in);
int numbers = scn.nextInt(); //If you do this, and it skips the next input
scn.nextLine(); //do this to prevent skipping
//I prefer this way
int numbers = Integer.toString(scn.nextLine());
String str = scn.nextLine(); //No more problems

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

System.out.println() is being skipped

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

Categories

Resources