Validating a string scanner - java

I am creating an "add customer" method and I want to validate the "add forename" scanner so that only a string can be entered and if the user enters an int etc it will throw up an error, below is the code I have got so far.
I have used "Harry" as an example, the concept seems to be working but obviously not every customer is going to be called Harry. Any help would be welcome!
boolean validInput12 = false;
String userOption13 = "";
do {
System.out.println("Enter Customer Forename");
if (sc2.hasNext()) {
userOption13 = sc2.next();
if (userOption13.matches("Harry")) {
validInput12 = true;
sc2.nextLine();
} else {
System.out.println("Input invalid: Please select a valid customer forename");
}
} else {
System.out.print("Input invalid: Please enter a valid name \n");
sc2.nextLine();
}
} while (!validInput12);

Related

Asking for a username from an array

I need to create a project where only if a specific username is inputted from the given names in the array, they are allowed to continue to the next menu options. How can I change my code to do this? It is just printing Hello John! Do I need a loop?
public class Project1 {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("please enter your username!");
String[] username = { "John","Lucy", "Amy", "Noah", "Sam"};
List<String> list = Arrays.asList(username);
if (list.contains("John")) {
System.out.println("Hello!" );
}
else if (list.contains("Lucy")) {
System.out.println("Hello!" );
}
else if (list.contains("Amy")) {
System.out.println("Hello!" );
}
else if (list.contains("Noah")) {
System.out.println("Hello" );
}
else if (list.contains("Sam")) {
System.out.println("Hello" );
}
else {
System.out.println("Please enter a valid username.");
}
}
returns:
Welcome, To start, please enter your username!
Hello John!
You effectivly need a loop to ask the user until the name is valid, a do/while loop is a good choice here
Scanner input = new Scanner(System.in);
List<String> allowedUsernames = Arrays.asList("John", "Lucy", "Amy", "Noah", "Sam");
System.out.println("Welcome, To start, please enter your username!");
String name = "";
do {
if (!name.equals("")) {
System.out.println("Please enter a valid username.");
}
name = input.nextLine();
} while (!allowedUsernames.contains(name));
System.out.println("Hello!");
Welcome, To start, please enter your username!
aa
Please enter a valid username.
uu
Please enter a valid username.
dd
Please enter a valid username.
John
Hello!

How to give each student a unique ID after being created by the user on JAVA program

I am working on a school project that basically allows the user to create, edit or view students. Once a student is created, they each get assigned a unique ID like 1, 2, 3, etc. All the functionally of creation, editing and displaying is working but I am stuck on have to give them a unique ID after created. Here is the code I have and in the // commented areas is what I attempted to do but I am not sure if its right. Any ideas will be very appreciated.
import java.util.Scanner;
import java.io.*;
public class MidTermProject {
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
System.out.println("Here is the sample of menu choices for Main Menu.");
System.out.println("\nWelcome to University Enrollment" + "\n1. Create Student" + "\n2. Edit Student" + "\n3. Display Student" + "\n0. --- Quit ---");
System.out.println("Please enter a valid choice(1-10, 0 to Quit) :");
int userInput = keyboard.nextInt();
if(userInput == 1) {
CreateStudent();
} else if(userInput == 2) {
EdithStudent();
} else if(userInput == 3) {
DisplayStudent();
} else if(userInput == 0) {
System.out.print("Done");
} else {
System.out.println("Invalid Option, Please try again.");
userInput = keyboard.nextInt();
if(userInput == 1) {
CreateStudent();
} else if(userInput == 2) {
EditStudent();
} else if(userInput == 3) {
DisplayStudent();
} else if(userInput == 0) {
System.out.print("Done");
}
}
}
public static void CreateStudent() throws IOException {
String FullName;
String address;
String city;
String state;
int StudentID;
Scanner keyboard = new Scanner(System.in);
FileOutputStream fstream =
new FileOutputStream("StudentInfo.dat");
DataOutputStream outputFile =
new DataOutputStream(fstream);
System.out.print("\nPlease enter your information bellow.\n" + "\nFull Name: ");
FullName = keyboard.nextLine();
outputFile.writeUTF(FullName);
System.out.print("Address: ");
address = keyboard.nextLine();
outputFile.writeUTF(address);
System.out.print("City: ");
city = keyboard.nextLine();
outputFile.writeUTF(city);
System.out.print("State: ");
state = keyboard.nextLine();
outputFile.writeUTF(state);
//allowed the user to select their own ID number
System.out.print("Please get a Student ID(1-10): ");
//Store the selected number on StudentID
StudentID = keyboard.nextInt();
//The for loop will increment index each time a user is created
for(int index = 0; index == StudentID; index++) {
//The if statement will compare index and StudentID, if equal will ask the user to enter a different number
if(index == StudentID) {
System.out.print("The selected ID has been selected already, Please select a different ID");
StudentID = keyboard.nextInt();
}
}
//write the number in the file
outputFile.writeInt(StudentID);
System.out.print("Successfully Created");
}
public static void EditStudent() throws IOException {
String editName;
String editaddress;
String editCity;
String editState;
Scanner keyboard = new Scanner(System.in);
RandomAccessFile file =
new RandomAccessFile("StudentInfo.dat", "rw");
file.seek(0);
System.out.print("\nPlease enter NEW information bellow.\n" + "\nFull Name: ");
editName = keyboard.nextLine();
file.writeUTF(editName);
System.out.print("Address: ");
editaddress = keyboard.nextLine();
file.writeUTF(editaddress);
System.out.print("City: ");
editCity = keyboard.nextLine();
file.writeUTF(editCity);
System.out.print("State: ");
editState = keyboard.nextLine();
file.writeUTF(editState);
file.close();
System.out.print("Successfully Edited");
}
public static void DisplayStudent() throws IOException {
FileInputStream fstream = new FileInputStream("StudentInfo.dat");
DataInputStream inputFile = new DataInputStream(fstream);
String student;
boolean endOfFile = false;
while(!endOfFile)
{
try
{
student = inputFile.readUTF();
System.out.print(student + " ");
}
catch (EOFException e)
{
endOfFile = true;
}
}
System.out.println("\nDone");
inputFile.close();
}
Firstly, following Java naming conventions makes your code more readable. So use lowercase first when naming a variable: studentId rather than StudentId. Initial-caps is for class names.
In your create student method, your for loop makes no sense.
for(int index = 0; index == StudentID; index++) {
//The if statement will compare index and StudentID, if equal will ask the user to enter a different number
if(index == StudentID) {
System.out.print("The selected ID has been selected already, Please select a different ID");
StudentID = keyboard.nextInt();
}
}
A for loop simply increments the index defined in the first clause, stepping the increment according to the third clause, until the second clause proves true.
So in your code, if the user enters 4, your loop counts 0, 1, 2, 3, 4 «bingo». Now that we reached the user’s specified number, we go on to ask them for another number. And we’re done. But that process is illogical.
That code fails to accomplish your goal of checking for existing students. You need to review all existing students one-by-one. Compare each existing student ID against the desired ID. Only after exhausting the list of all known students should we use the desired ID. If we find a match on an existing student, then we break out of the loop to ask the user for another choice of ID. And we need another outer loop to continue this “ask, search, ask again if needed” process until an unused desired ID is determined.
Big tip: If you write out your problem statement and solution attempt as plain prose, similar to what I just did in the paragraph above, your programming will go more smoothly. And your written prose will be fodder for writing helpful comments in your source code.

How can I get a multidimensional array to loop with string input?

Basically I'm making a program that reads from a multidimensional array to display it's corresponding information. What I want to do is make it so the while loop will continue to tell me I'm putting in the wrong class ID's until you put in a correct Class ID.
do
{
System.out.println("Please enter the name of your course to display it's information");
name = input.nextLine();
for(int x = 0; x <= classes.length; ++x)
{
if(name.equals(classes[x][0]))
{
i = true;
System.out.println("Course info: " + classes [x][0]);
System.out.println(classes[x][1]);
System.out.println(classes[x][2]);
x = classes.length;
}
else{
System.out.println("Wrong course id");
i = false;
input.next();
}
}
}
while (!(i));
System.out.println("This is the end of the program!");
System.exit(0);
First of all, try to keep good naming conventions. i is bad name for a flag variable. Name it boolean found or something. It will not only help other people read and understand your code, but it will help you in order find the logic you have to use as well.
Now, since you have input.next(); in else part, i guess you want to ask again for user input, until a something is found. So, a name = input.nextLine(); is required again in order to take new input. But in your case the else part can be removed completely and let the do-while do the work.
An example:
public class Classes {
private static final String[][] CLASSES = { { "Maths", "info" }, { "History", "info" }, { "Biology", "info" } };
public static void main(String[] args) {
boolean found = false;
String name;
Scanner input = new Scanner(System.in);
do {
System.out.println("Please enter the name of your course to display it's information");
name = input.nextLine();
for (int i = 0; i < CLASSES.length; i++) {
if (name.equals(CLASSES[i][0])) {
found = true;
System.out.println("Course info: " + CLASSES[i][0]);
System.out.println(CLASSES[i][1]);
// System.out.println(CLASSES[i][2]); //My CLASSES array, does not have 3 columns
break;// exit for loop
}
}
if (!found)
System.out.println("Wrong course id");
} while (!found);
input.close();
System.out.println("This is the end of the program!");
}
}

Java code not running as planned

This isn't the entire code, just the problem area. (Full code below)
if (passLength > 4) {
System.out.println("Signup alost complete.");
Random rand = new Random();
int randm = rand.nextInt(100000) + 1;
System.out.println(
"To confirm you are not a robot, please enter this code: "
+ randm);
String code = userInput.next();
if (code.equals(randm)) {
System.out.println("Thank you, " + userName);
System.out.println(
"You may now login. Begin by entering your username");
if (userInput.equals(userName)) {
System.out.println("Now please enter you password");
}
// Where the rest of the program will go
}
else {
System.out.println("The code entered is incorrect.");
}
}
else {
System.out.println("Invalid Password");
}
I am making a program where the user makes an account, then later signs in. The part I am having trouble with is a verification to ensure the user is human (they obviously are, but still). After creating their username and password, I generate and print a random int, and they have to type it back.
My problem is that the program always skips to the else statement, and prints "The code entered is incorrect." Even when I enter it perfectly.
Can anyone tell me what I'm doing wrong?
Below is the entire code, just in case.
public static void main(String[] args) {
System.out.println("Hi! To begin please choose your username.");
System.out.println("To do this, please enter your username below. ");
System.out.println("This name must be at least three characters.");
Scanner userInput = new Scanner(System.in);
String userName = userInput.next();
int nameLength = userName.length();
if (nameLength > 2) {
System.out.println("Now please enter your password.");
System.out
.println("This password must be at lease five characters");
String passWord = userInput.next();
int passLength = passWord.length();
if (passLength > 4) {
System.out.println("Signup alost complete.");
Random rand = new Random();
int randm = rand.nextInt(100000) + 1;
System.out.println(
"To confirm you are not a robot, please enter this code: "
+ randm);
String code = userInput.next();
if (code.equals(randm)) {
System.out.println("Thank you, " + userName);
System.out.println(
"You may now login. Begin by entering your username");
if (userInput.equals(userName)) {
System.out.println("Now please enter you password");
}
// Where the rest of the program will go
}
else {
System.out.println("The code entered is incorrect.");
}
}
else {
System.out.println("Invalid Password");
}
}
else {
System.out.println("Invalid Username");
}
}
You are comparing a String with an integer, which can't be the same obviously.
int randm = rand.nextInt(100000) + 1;
...
String code = userInput.next();
if (code.equals(randm))
To solve the problem you could convert the integer to a String and compare the strings (or the other way).
String randm = String.valueOfrand.nextInt(100000) + 1;
...
String code = userInput.next();
if (code.equals(randm)) // Comparing string now
Edit : As #Pshemo pointed out, int code = userInput.nextInt(); will do the work given that you compare the integers with ==.
It's because randm is int and code is String. So the code if (code.equals(randm)) always results to false.
You cannot compare a string and an integer.
Trying taking the input as an integer instead of a String.
String code = userInput.next();
Instead use:
int code= userInput.nextInt();
if(code==randm)
Or you could convert the integer to a String as well

Code doesn't continue after the do-while loop?

I have began to learn Java in my AS level computing class, and have really taken to the first DIY task we have been set.
I have used a do-while statement to see if the input username from the user is in the array "names"- if it's not, it requests to re-enter the username, until a correct one is inserted. I have also set up a boolean, so when a correct username is entered, it cancels the do-while loop and continues with code - but it doesn't.
String[] names = {"mckeownl", "heardj", "williamsc"};
String[] attendance = {"yes", "no", "yes"};
int[] grade = {96, 66, 73};
boolean loggedin = false;
Scanner user_input = new Scanner(System.in);
String login;
login = user_input.next();
do { // beginning of while - login
System.out.println("Insert student's surname followed by the first letter");
System.out.print("of their first name (e.g John Smith = smithj): ");
if (Arrays.asList(names).contains(login)) {
System.out.println("Student selected: "+login+".");
loggedin = true;
}
else {
System.out.println("Incorrect student name! Please try again.");
loggedin = false;
}
} while ( ! loggedin);
if (login.equals(names[0])) {
System.out.println("Attend today: "+attendance[0]);
System.out.println("Grade: ");
}
else {
System.out.println("poo");
}
}
}
The output for a correct name is ;
"Insert student's surname followed by the first letter
of their first name (e.g John Smith = smithj): mckeownl
Student selected: mckeownl."
Why isn't the final if statement output?
You should be asking for the login inside the loop.
You shouldn't set the loggedin variable to false if it fails. Just give text that it failed, then it'll return to the top and ask for login again.
You can have multiple lines in a method call. So you could have:
System.out.println("Insert student's surname followed by the first letter " +
"of their first name (e.g John Smith = smithj): ");
Instead of:
System.out.println("Insert student's surname followed by the first letter");
System.out.print("of their first name (e.g John Smith = smithj): ");
put login = user_input.next(); inside the loop.. In order for the user to loggedin again..
do { // beginning of while - login
System.out.println("Insert student's surname followed by the first letter");
System.out.print("of their first name (e.g John Smith = smithj): ")
login = user_input.next(); // <--- you should ask for login here
...
updated:
//for the final if statement
if (loggedin) { //just use this boolean variable since you used it as an indicator if it is valid name or not
System.out.println("Attend today: "+attendance[0]);
System.out.println("Grade: ");
}
else {
System.out.println("poo");
}
actually, you don't need to put condition after the loop since you already filter it inside the loop so if the name is not valid it will not exit the loop until the user enter a valid name.. you can just do it like this after the loop
do{
..
}while(..)
System.out.println("Attend today: "+attendance[0]);
System.out.println("Grade: ");
I started from scratch, and have created this, which uses the same principles, but has solved my answer.
There are three users, each with their own login, password creation and password entry (if you have a better way to do this, please say).
package codeyom9a;
import java.util.Scanner;
public class Codeyom9a {
public static void main(String[] args) {
String[] names = {"Luke", "Jack", "Brad" };
String[] surnames = {"Mckeown", "Heard", "Reed" };
Scanner user_input = new Scanner(System.in);
boolean firstloggedin;
boolean passloggedin;
String firstlogin;
do { //login first name
firstloggedin = false;
System.out.print("Enter your first name: ");
firstlogin = user_input.next();
if (firstlogin.equals(names[0]) || firstlogin.equals(names[1]) || firstlogin.equals(names[2])) {
firstloggedin = true;
}
else {
System.out.println("Please try again.");
}
} while (! firstloggedin);
boolean secondloggedin;
String secondlogin;
do { //login surname
secondloggedin = false;
System.out.print("Enter your surname: ");
secondlogin = user_input.next();
if (secondlogin.equals(surnames[0]) & firstlogin.equals(names[0])|| secondlogin.equals(surnames[1]) & firstlogin.equals(names[1]) || secondlogin.equals(surnames[2]) & firstlogin.equals(names[2])) {
secondloggedin = true;
}
else {
System.out.println("Please try again.");
}
} while (! secondloggedin);
if (secondlogin.equals(surnames[0]) & firstlogin.equals(names[0])) { //pass login user 1
String password1; //pass create user 1
System.out.print("Create a password (no spaces): ");
password1 = user_input.next();
boolean passloggedin1 = false;
do{
String passwordenter1; //pass enter user 1
System.out.print("Enter your password now: ");
passwordenter1 = user_input.next();
if (passwordenter1.equals(password1)) {
passloggedin1 = true;
System.out.println("Correct! You have now logged in.");
}
else {
System.out.println("Incorrect password!");
}
} while (! passloggedin1);
} //end user 1
if (secondlogin.equals(surnames[1]) & firstlogin.equals(names[1])) { //pass login user 2
String password2; //pass create user 2
System.out.print("Create a password (no spaces): ");
password2 = user_input.next();
boolean passloggedin2 = false;
do{
String passwordenter2; //pass enter user 2
System.out.print("Enter your password now: ");
passwordenter2 = user_input.next();
if (passwordenter2.equals(password2)) {
passloggedin2 = true;
System.out.println("Correct! You have now logged in.");
}
else {
System.out.println("Incorrect password!");
}
} while (! passloggedin2);
} //end user 2
if (secondlogin.equals(surnames[2]) & firstlogin.equals(names[2])) { //pass login user 3
String password3; //pass create user 3
System.out.print("Create a password (no spaces): ");
password3 = user_input.next();
boolean passloggedin3 = false;
do{
String passwordenter3; //pass enter user 3
System.out.print("Enter your password now: ");
passwordenter3 = user_input.next();
if (passwordenter3.equals(password3)) {
passloggedin3 = true;
System.out.println("Correct! You have now logged in.");
}
else {
System.out.println("Incorrect password!");
}
} while (! passloggedin3);
} //end user 3
}
}
If you type in "Luke", "Jack", or "Brad", it then requests for the surname (which is in the same index in the 'surnames' array). If both correct, it request for a password to be created, and then asks for the user to input that created password.
Regarding my first code, I don't know why this works and the other doesn't, any ideas why?

Categories