This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
import java.util.Scanner;
public class Box
{
public static void main(String[] args)
{
String empty = "";
String yes = "yes";
String no = "no";
String response;
String name;
Scanner input = new Scanner(System.in);
System.out.print("Please enter your name >>");
name = input.nextLine();
if(name.equals(empty))
{
System.out.println("You did not enter a name, please try again >>");
name = input.nextLine();
}
System.out.println("Would you like the profanity filter turned on?");
response = input.nextLine();
response = response.toLowerCase();
if(response.equals(yes) || response.equals(no))
{
if(response.equals(yes))
System.out.print("Profanity filter will be turned on.");
else
System.out.print("Profanity filter will not be turned on.");
}
else
System.out.print("Invalid response, please try again.");
}
}
This displays "Please enter your name >>", but no matter what I enter there, even if it's empty, it always asks if you'd like the profanity filter turned on.
It just skips over the if that's supposed to loop forever until you actually enter a name, and I can't figure out why.
Also, I know I didn't ask this in the title, but I also can't figure out a way for the final statement to loop back to the "response = input.nextLine();" when someone doesn't enter either "yes" or "no".
If you want it to loop forever then you need to use while loop and not if, e.g.:
Scanner input = new Scanner(System.in);
System.out.print("Please enter your name >>");
String name = input.nextLine();
while(name.isEmpty()){
System.out.println("You did not enter a name, please try again >>");
name = input.nextLine();
}
This will keep asking the user to enter the name until he enters a non empty String.
Related
Question:
create a class named Account that contains the string fields name, email and
password.
Develop a program called LoginSim that simulates a login procedure.
The program reads a list of names, email addresses and passwords from a file pw.txt.
Store the information in an ArrayList of Account objects.
*Note: for Netbeans users the file must be placed in a test folder and accessed with new File("test/pw.txt");
Your program will prompt the user for their email address.
If the email is not in the system, prompt the user to try again. Give them an option to quit.
If the email is found in the system, prompt the user to enter their password.
After 3
unsuccessful tries, inform the user that they are locked out and end the program.
If the password matches, welcome the user by name and ask if they would like to change their
password.
If so, prompt for the new password and change it accordingly. If not, end the
program by confirming that they have signed out.
When the program ends, display the list of accounts.
Sample output:
Enter your email address (q to quit):
draco#hogwarts.com
Email not found, please try again (q to quit):
dmalfoy#hogwarts.com
Email not found, please try again (q to quit):
q
Goodbye!
pw.txt
Hagrid hagrid#hogwarts.com 111
Harry harry#hogwarts.com killvoldy777
Ron ron#hogwarts.com mypassword123
Hermione hermione#hogwarts.com 98fJG83h*4iwrej!
What should I do next, exception at line 16
import java.util.*;
import java.io.*;
public class LoginSim {
private static int index;
public static void main(String args[]) throws
FileNotFoundException, ArrayIndexOutOfBoundsException {
String em;
String pw;
Scanner f = new Scanner(new File("src/pw.txt"));
Scanner kb = new Scanner(System.in);
String[] email = new String[3];
String[] password = new String[3];
int i = 0;
while (f.hasNext()) {
email[i] = String.valueOf(f.hasNext());
password[i] = String.valueOf(f.hasNext());
i++;
}
System.out.println("Enter Email:");
em = kb.next();
System.out.println("Enter Password:");
pw = kb.next();
if (index != -1) {
System.out.println("Enter pw:");
pw = kb.next();
int tries = 0;
while (!pw.equals(tries < 2) &&
!pw.equals(password[index])) {
System.out.println("Incorrect Password, Try Again");
tries++;
pw = kb.next();
}
if (pw.equals(password[index])) {
System.out.println("Successful Login");
}else {
System.out.println("3 Strikes, Locked out");
}
System.out.println("Email not found");
}
}
}
Ok, you are getting java.lang.ArrayIndexOutOfBoundsException: 3 in this line email[i] = String.valueOf(f.hasNext()); because the size of your array is 3 (String[] email = new String[3];), but you are trying to add more then 3 entries to it, at least 4 based on your sample "pw.txt".
Also, you have the same issue with your password array.
I'm doing a small project and I have everything done, just one small error. the error shows "symbol not found" and shows the red squiggly line under my scan.
package pkgif.elsestatements.java;
import java.util.Scanner;
public class IfElseStatementsJava {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
String your_name;
System.out.print("What is your name?");
your_name = user_input.next();
System.out.println("Hi " + your_name);
String user_input2;
System.out.print(".");
user_input2 = user_input.next();
System.out.println("Do you like Gospel Music Paul?"); //Asks question
String input = scan.nextLine(); //Waits for input
if (input.equalsIgnoreCase("Yes")) { //If the input is Yes)
System.out.println("Here are some songs; Amazing Grace, I'll Fly Away, A Little Talk With Jesus ");
}
else { //If the input is anything else
System.out.println("Ok! Have a nice day!");
}
}
this line is the one giving me trouble ---- String input = scan.nextLine(); //Waits for input
I was feeling really great about finish this with no errors beforehand, then this. Any help is appreciated.
According to the code above. You've defined Scanner user_input = new Scanner(System.in); i.e. user_input as the oject ref.
So, changing String input = scan.nextLine(); to String input = user_input.nextLine(); should do.
My task is to create a program which asks the user to enter a year, a first name and a last name. It then takes the last 2 numbers of the year, the whole last name, and the first letter of the first name and formats them into an email like this: 16SmithJ#mymail.co.uk. It places this email in a text file, which doesn't need to be printed. At the end, it asks if the user wishes to repeat the process again to make a new email.
This is my program, and it isn't fully complete yet. I have it working, but when I go to implement the part which repeats it if wanted, the email is no longer made in the file:
public static void main(String[] args) throws IOException {
PrintWriter pw = new PrintWriter (new FileWriter("7D_mail.txt"));
boolean done = false;
while (done==false){
Scanner kb = new Scanner (System.in);
System.out.print ("Enter the year (e.g 2016) > ");
String year = kb.nextLine();
System.out.print ("Enter your first name > ");
String fname = kb.nextLine();
System.out.print ("Enter your last name > ");
String lname = kb.nextLine();
pw.write (year.substring(2)+lname+fname.charAt(0)+"#mymail.co.uk");
System.out.print ("*** Email created - another one? (Y/N)");
pw.close();
}
}
This program above works, but if I then add one line after the last one (String answer = kb.nextLine();), to make a new string for the answer, it no longer works.
public static void main(String[] args) throws IOException {
PrintWriter pw = new PrintWriter (new FileWriter("7D_mail.txt"));
boolean done = false;
while (done==false){
Scanner kb = new Scanner (System.in);
System.out.print ("Enter the year (e.g 2016) > ");
String year = kb.nextLine();
System.out.print ("Enter your first name > ");
String fname = kb.nextLine();
System.out.print ("Enter your last name > ");
String lname = kb.nextLine();
pw.write (year.substring(2)+lname+fname.charAt(0)+"#mymail.co.uk");
System.out.print ("*** Email created - another one? (Y/N)");
String answer = kb.nextLine();
pw.close();
}
}
Any idea why this doesn't work? Thanks
I don't think it stopped working. You are unconditionally setting "done" to true after you take the user's repsonse, so it exits. Wrap "done = true" in a condition that checks for the value of "answer" to be "Y".
This is because the value 'done' is set to true after the first iteration of the loop and the loop never gets a chance to run again.
Besides, you close the PrintWriter after one iteration as well.
What I would suggest is this change:
if(answer.equals("N")){
done = true;
pw.close();
}
Try using System.out.println (); after printing the question to avoid exceptions (you can read the api here https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()).
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I'm new to Java and i decided to experiment, however I'm having hard time trying to understand what is the problem. What my program is supposed to do is to receive login and login2, password and password2, and if they match then program says "You may enter", if not then program says "You may not enter", however, it says it even when login and login2, password and password2 are the same. Any ideas what to do?
public static void main(String args[]) {
Scanner input = new Scanner (System.in);
System.out.println("In order to register type your login");
String login = input.nextLine();
System.out.println("And password");
String password = input.nextLine();
System.out.println("Enter Login");
String login2 = input.nextLine();
System.out.println("Enter password");
String password2 = input.nextLine();
if (login == login2 && password == password2){
System.out.println("You may enter");
}
else{
System.out.println("You may not enter");
}
}
A String is an Object in java. You have to compare it with .equals() or .equalsIgnoreCase().
if (login.equals(login2) && password.equals(password2)){
I am not sure what is wrong and my Professor is stumped as well. The while loop condition only terminates if the condition is met right away. Once the loop is running, the met condition no longer stops it and it just keeps going. Its like the look isnt checking the condition anymore? Below is my code. Thank you for any help.
import java.io.*;
import java.util.*;
public class createPhoneList {
public static void main(String[] args) {
DataOutputStream ostream;//creates output stream
Scanner input = new Scanner(System.in);//creates scanner in object
final String DONE = "DONE";//will be used to end data entry loop
String firstName;
String lastName;
long phoneNumber;
try{
ostream = new DataOutputStream(new FileOutputStream("javaContactsUnit4Assignment.txt"));
System.out.print("Enter First Name or type 'DONE' to quit: ");
firstName = input.nextLine();
while(!firstName.equalsIgnoreCase(DONE)){
/*
* Error occuring at runtime where while loop terminates only if
* "done" is typed first, but once the loop is running "done" no longer
* stops it. Not sure what is wrong...
*/
input.nextLine();
System.out.print("Please enter Last Name: ");
lastName = input.nextLine();
System.out.print("Please enter the Phone Number(with NO DASHES, as they will cause a fatal error): ");
phoneNumber = input.nextLong();
ostream.writeUTF(firstName);
ostream.writeUTF(lastName);
ostream.writeLong(phoneNumber);
System.out.print("Enter First Name or type 'DONE' to quit: ");
firstName = input.nextLine();
}
}
catch(IOException e){
System.err.println("Error opening file.");
}
catch(InputMismatchException e){
System.err.println("Invalid data was entered. Please try again.");
}
catch(Exception e){
System.err.println("You encountered a fatal error. Please try again.");
}
}
}
You should add another input.nextLine(); after phoneNumber = input.nextLong();.
That's because input.nextLong() command reads only the long value (and skips the \n which is the enter key you press right after).
So when you continue reading with input.nextLine() you receive the \n and not "done", that's why your loop never terminates. So adding another input.nextLine() will "swallow" the \n and the next one will read the actual String.