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!
Related
So, I want to receive input from the user, check if they used alphabetical values and then check if it is too long. If too long, I want to start again from the top (checking if alphabetical) by calling the method I am in. However, when I start over and I type, say "Danny", this will show:
Output: "Thank you, got Danny"
Output: (length of previous, too long input) + "is too many characters, try to keep it under 30."
So somehow, it keeps the original input (that was alphabetical, but above 30) saved and it doesn't alter it when it starts over. Anyone know what I should do instead?
public static String inputPattern() {
Scanner scanner = new Scanner(System.in);
String player;
int strLength;
System.out.println("Please enter your name:");
while (!scanner.hasNext("[A-Za-z]+")) { //Checks if alphabetical value
System.out.println("Please stick to the alphabet!");
scanner.next();
}
player = scanner.next();
player += scanner.nextLine();
System.out.println("Thank you! Got " + player);
strLength = player.length(); // Saves the length of user-inputted name
while (strLength > 30) { // Checks if not too long
System.out.println(strLength + " is too many characters, please try to keep it under 30");
inputPattern(); // Starts over again if too long
}
return player;
}
I have taken your method and modified it a bit.
It is non recursive solution.
Also in your code scanner resource was not closed at the end.
Iterative Solution
import java.util.Scanner;
public class SO66064473 {
public static void main(String[] args) {
inputPatternIterative();
}
public static String inputPatternIterative() {
Scanner scanner = new Scanner(System.in);
String player = "";
int strLength = Integer.MAX_VALUE;
while (strLength > 30) { // Checks if not too long
System.out.println("Please enter your name:");
while (!scanner.hasNext("[A-Za-z]+")) { //Checks if alphabetical value
System.out.println("Please stick to the alphabet!");
scanner.next();
}
player = scanner.next();
player += scanner.nextLine();
System.out.println("Thank you! Got " + player);
strLength = player.length(); // Saves the length of user-inputted name
if (strLength > 30)
System.out.println(strLength + " is too many characters, please try to keep it under 30");
}
scanner.close(); // Closing scanner resource after use.
return player;
}
}
Output :
Please enter your name:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Thank you! Got aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
70 is too many characters, please try to keep it under 30
Please enter your name:
aaaaaaaaaaaaaaaaaaaa12
Please stick to the alphabet!
coifvoifoivmrfvoirvoirovroijfoirjfoijroifjrwofjorwfouwrfoijwrofjworjfoiwrjf
Thank you! Got coifvoifoivmrfvoirvoirovroijfoirjfoijroifjrwofjorwfouwrfoijwrofjworjfoiwrjf
75 is too many characters, please try to keep it under 30
Please enter your name:
Danny
Thank you! Got Danny
EDIT : with the suggestion made by #Dev-vruper here is updated easy recursive code
Recursive Solution
import java.util.Scanner;
public class SO66064473 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
inputPatternRecursive(sc);
sc.close();
}
public static String inputPatternRecursive(Scanner sc) {
System.out.println("Please enter your name:");
String player = sc.nextLine();
if (!player.matches("[A-Za-z]+")) {
System.out.println("Please stick to the alphabet!");
inputPatternRecursive(sc);
} else {
System.out.println("Thank you! Got " + player);
if (player.length() > 30) {
System.out.println(player.length() + " is too many characters, please try to keep it under 30");
inputPatternRecursive(sc);
}
}
return player;
}
}
This should solve your problem in a pretty easy way:
public static String inputPattern(){
Scanner scanner = new Scanner(System.in);
String player = "";
int strLength;
boolean bShowedInstruction = true;
System.out.println("Please enter your name:");
while (true) {
if (!bShowedInstruction)
System.out.println("Please enter your name:");
bShowedInstruction = false;
player = scanner.next();
if (!player.matches("[A-Za-z]+")) {
System.out.println("Please stick to the alphabet!");
}
else if (player.length() > 30) {
System.out.println(player.length() + " is too many characters, please try to keep it under 30!");
}
else
break;
}
System.out.println("Thank you! Got " + player);
return player;
}
There's no need for a recursion. A simple while(true) loop does the trick.
It's a pretty clean solution keeping unnecessary scan-methods out of the game.
I am taking input for my application using scanner. My code is as follows:
Scanner sc = new Scanner(System.in);
System.out.println("Do you want to give user input :YES/NO")
if(sc.next().equals("YES")){
System.out.println("which input? student or teacher name")
if(sc.next().equals("student")){
system.out.println("do something");
}
if(sc.next().equals("teacher")){
system.out.println("do something");
}
}
}else
{
system.out.println("program will run itseld");
}
Code is working fine but it is asking input twice. Suppose if I enter student it will not proceed but when I enter student again second time my program starts working. I also saw some similar questions on stackoverflow and tried their solutions but I am not able to resolve this. Please help.
sc.next() grabs an input each time. Store this to a variable and just use the variable when comparing.
String input = sc.next();
if(input.equals("YES")) {
// logic here
}
try something like this
import java.io.*;
import java.util.*;
class SumsInLoopTester {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Do you want to give user input :YES/NO");
String input = sc.next();
if (input.equals("YES")) {
System.out.println("which input? student or teacher name");
String input2 = sc.next();
if (input2.equals("student")) {
System.out.println("do something");
} else if (input2.equals("teacher")) {
System.out.println("do something");
}
} else {
System.out.println("program will run itseld");
}
}
}
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);
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?
Can anyone help me understand why program requires me to input my selection twice before proceeding?
public static void main(String[] args) {
String quit = "quit";
String input = "input";
String print = "print";
#SuppressWarnings("resource")
Scanner scan = new Scanner(System.in);
System.out.println("please enter a command : \n 1) Quit \n 2) Input \n 3) Print \n");
String initialSelection = scan.next();
boolean stringInput = scan.hasNext();
boolean intInput = scan.hasNextInt();
boolean boolinput = scan.hasNextBoolean();
if(initialSelection.equalsIgnoreCase(quit)) {
System.out.println("The program has quit.");
System.exit(0);
}else if(initialSelection.equalsIgnoreCase(print)){
[constructor]
do {
System.out.println("\nplease enter a command : \n 1) Quit \n 2) Input \n 3) Print \n");
initialSelection = scan.nextLine();
if (initialSelection.equalsIgnoreCase(print)) {
new BonusArrayList();
} else if(initialSelection.equalsIgnoreCase(quit)) {
System.out.println("The program has quit.");
System.exit(0);
}
} while (initialSelection.equalsIgnoreCase(print));
}else if(initialSelection.equalsIgnoreCase(input)){
System.out.println("\n Please enter some kind of value (ex: 123, hello, True)");
}
}
I believe it is coming from the nested do-while statement, but I cannot seem to fix that issue. Any tips would be appreciated!
It is because you either need to have
String initialSelection = scan.next();
or
boolean stringInput = scan.hasNext();
boolean intInput = scan.hasNextInt();
boolean boolinput = scan.hasNextBoolean();
If you have both you need to enter twice