How to use do-while loop to check user input again? - java

I want to add a loop to my program so that when a user enters an incorrect name it goes back to the start of the program and asks them to enter their name again. I think I need a do-while loop but I am not sure how to implement it with the if statements and boolean already included. I want the user to be only have three entries and if they get it wrong three times then the program closes.
import java.util.Scanner;
public class Username
{
public static void main(String[] args)
{
{
Scanner kb = new Scanner(System.in);
// array containing usernames
String[] name = {"barry", "matty", "olly", "joey"}; // elements in array
System.out.println("Enter your name");
String name1 = kb.nextLine();
boolean b = true;
for (int i = 0; i < name.length; i++)
{
if (name[i].equals(name1))
{
System.out.println("you are verified you may use the lift");
b = false;
break;// to stop loop checking names
}
}
if (b)
{
System.out.println("Invalid entry 2 attempts remaining, try again");
}
}

You can use a condition in the while loop. Something along the lines of:
boolean b = false;
while(!b){
System.out.println("Enter your name");
String name1 = kb.nextLine();
for (int i = 0; i < name.length; i++) {
if (name[i].equals(name1)) {
b = true;
System.out.println("you are verified you may use the lift");
}else{
System.out.println("Invalid entry 2 attempts remaining, try again");
}
}
}
The loop will quit if the name condition is fulfilled and will loop around if it is not.

You can do it like this:
int count = 0;
point:
do {
System.out.println("Enter your name");
String name1 = kb.nextLine();
boolean b = true;
for (int i = 0; i < name.length; i++) {
if (name[i].equals(name1)) {
System.out.println("you are verified you may use the lift");
b = false;
break point;// to stop loop checking names
}
}
if (b) {
count++;
System.out.println("Invalid entry 2 attempts remaining, try again");
}
while(!b || count <=3)

Use the following approach. Good thing is that it is a clean and robust solution.
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class AccessPoint
{
private Scanner scanner;
private List<String> usernames;
public AccessPoint()
{
scanner = new Scanner(System.in);
usernames = Arrays.asList("Barry", "Matty", "Olly", "Joey");
if (tryAccessForTimes(3))
{
allowAccess();
}
else
{
denyAccess();
}
scanner.close();
}
public static void main(String[] args)
{
new AccessPoint();
}
private boolean tryAccessForTimes(int times)
{
boolean accessAllowed = false;
for (int tryIndex = 1; tryIndex <= times && !accessAllowed; tryIndex++)
{
String userInput = getUserName();
for (String userName : usernames)
{
if (userName.equals(userInput))
{
accessAllowed = true;
break;
}
}
if (!accessAllowed)
{
printNumberOfTriesLeft(times, tryIndex);
}
}
return accessAllowed;
}
private void printNumberOfTriesLeft(int times, int tryIndex)
{
int triesLeft = times - tryIndex;
if (triesLeft != 0)
{
System.out.println("You have " + triesLeft
+ (triesLeft == 1 ? " try" : " tries") + " left.");
}
}
private String getUserName()
{
System.out.print("Enter Username: ");
return scanner.nextLine();
}
private void allowAccess()
{
System.out.println("Access Granted. Allowed to use lift.");
}
private void denyAccess()
{
System.out.println("Access Denied.");
}
}

package com.loknath.lab;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class User1 {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
// array containing usernames
String[] name = {"zerr", "barry", "matty", "olly", "joey" }; // elements
String []temp=name;
Arrays.sort(temp);
while (true) {
System.out.println("Enter your name");
String name1 = kb.nextLine();
if (Arrays.binarySearch(temp,name1)>=0) {
System.out.println("you are verified you may use the lift");
break;
} else {
System.out.println("Not a verified user try again!");
}
}
System.out.println("Done");
}
}
output
Enter your name
loknath
Not a verified user try again!
Enter your name
chiku
Not a verified user try again!
Enter your name
zerr
you are verified you may use the lift
Done

Related

While Loop Parsing Issue

I'm trying to give the user an infinite amount of inputs until they enter q. I'm using a while statement to run the program, but when the user tries to quit I get an error because the program would try and parse q as an integer. Any ideas on how I should change the structuring of this to prevent the error from occurring?
Scanner in = new Scanner(System.in);
System.out.println("What would you like your Fibonacci number to be?(enter q to quit)");
String value = in.next();
int trueValue;
while(!value.equalsIgnoreCase("q")) {
trueValue = Integer.parseInt(value);
Fibonacci userCase = new Fibonacci(trueValue);
System.out.println(userCase.calculateFibonacci(userCase.getCaseValue()));
System.out.println("Please enter another number.");
value = in.next();
trueValue = Integer.parseInt(value);
}
If it matters, here are the methods being called within the loop.
public int calculateFibonacci(int caseValue) {
if(caseValue == 0)
return 0;
else if(caseValue == 1)
return 1;
else
return calculateFibonacci(caseValue-1) + calculateFibonacci(caseValue-2);
}
public int getCaseValue()
{
return caseValue;
}
You can remove the last
trueValue = Integer.parseInt(value);
since you are already doing that at the start of the loop.
do{ getting the user value before checking } while(checking if it's ok);
/* https://stackoverflow.com/questions/40519580/trying-to-determine-if-a-string-is-an-integer */
private boolean isInteger(String str) {
if(str == null || str.trim().isEmpty()) {
return false;
}
for (int i = 0; i < str.length(); i++) {
if(!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
public static String check(Scanner in) {
String value;
do {
System.out.println("Please enter a number or q to quit.");
value = in.next();
} while(!value.equalsIgnoreCase("q") && !isInteger(value));
return value;
}
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
String value = check(in);
while(!value.equalsIgnoreCase("q")) {
Fibonacci userCase = new Fibonacci(Integer.parseInt(value));
System.out.println(userCase.calculateFibonacci(userCase.getCaseValue()));
value = check(in);
}
in.close();
}

Creating Login with Java, won't go to else statement?

I'm making a login program, but it is getting some errors. If I put in a name that is not in the list, I get an error. It doesn't seem to reach the else statement also, and I'm not sure why.
import java.lang.*;
import java.util.*;
import java.io.*;
import java.math.*;
public class HelloWorld {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String userName;
int n = 10;
int i = 0;
String[] array = new String[n];
array[0] = "John";
array[1] = "Johny";
array[2] = "ben";
System.out.println("Enter your user name(Note:**Case Sensative**)");
userName = input.nextLine();
while (i <= array.length) {
if (array[i].equals(userName)) {
System.out.println("Your UserName is valid");
break;
}
else if (!array[i].equals(userName)){
i++;
}
else {
System.out.println("Your UserName is not valid");
break;
}
}
}
}
First, I'd consider using a for-loop as it'll manage the i value for you, but also consider the logic you have
if element.equals(userName) {...}
else if !element.equals(userName) {...}
else {...}
How is it possible to ever get into the else block, either element will be or won't be equal to the userName, there is no other state. I'd consider having a flag which indicates if a user was found or not and checking that at the other end of the loop
As a general concept...
//...
userName = input.nextLine();
String validUser = null;
for (int index = 0; index < array.length; index++) {
if (array[i].equals(userName)) {
validUser = userName;
break;
}
}
if (validUser != null) {
System.out.println("UserName is valid");
} else {
System.out.println("Your UserName is not valid");
}
Because you probably don't care about the index so much, you can also do something like...
for (String element : array) {
if (array[i].equals(userName)) {
validUser = userName;
break;
}
}
which is shorthand version.
Have a look at The for statement for more details
First of all your if and else if are the only condition the java will run in your context and there are no other condition running afterwards. It is like you are doing TRUE and FALSE and expecting another condition. Make use of foreach in java much simpler way.
boolean found = false;
for(String name: array){
if (name.equals(userName)) {
found = true;
break;
}
}
if(!found){
System.out.println("Your UserName is not valid");
}else{
System.out.println("Your UserName is valid");
}
When you get mastered use the methods of Array , Collections and specially lambdas stream api for little bit lift up your java knowledge.
Your Statement will never go to the else part, because the the input(userName) will either EQUAL array[i], or not. Think about it...
if (array[i].equals(userName)) { //It will do this if userName is array[i]
System.out.println("Your UserName is valid");
break;
}
else if (!array[i].equals(userName)) { //It will do this if userName is NOT array[i]
i++;
}
else { //this is impossible, unreachable code
System.out.println("Your UserName is not valid");
break;
}
The reason your else is not reachable is because it is an impossible scenario. I edited your program, and it works now. Here's the whole thing:
import java.util.Scanner;
public class Experiments {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String userName;
boolean found = false;
String[] array = new String[3];
array[0] = "John";
array[1] = "Johny";
array[2] = "ben";
System.out.println("Enter your user name:");
userName = input.nextLine();
for(int i=0; i<array.length; i++) {
if (userName.equalsIgnoreCase(array[i])) {
System.out.println("Your UserName is valid");
found = true;
break;
}
if (!found && i == array.length-1) {
System.out.println("Your UserName is not valid");
}
}
input.close();
}
}
If the input (userName) is in the array at any spot, it will say "Your UserName is valid" If it isn't in the array, it will say "Your UserName is not valid".
Here is an example of a valid userName:
Enter your user name:
John
Your UserName is valid
And if the UserName is invalid:
Enter your user name:
Jimmy
Your UserName is not valid
Please comment if you have any questions about this, and I will explain.

Java - code keeps returning 'error: incompatible types: Object cannot be converted to int'

Inside my code, I am trying to compare the last element of an array list to a random number, but I keep getting the error "incompatible types: Object cannot be converted to int". I cannot seem to find a solution. The problem in question occurs at the boolean class 'checkLastGuess'.
import java.util.Scanner;
import java.util.Random;
import java.util.ArrayList;
public class GuessingGame
{
int numToGuess = new Random().nextInt(10);
ArrayList guesses = new ArrayList();
void getGuess()
{
Scanner keyboard = new Scanner(System.in);
boolean valid = false;
int userGuess = 0;
while (valid == false)
{
System.out.print("What is your guess: ");
String num = keyboard.next();
char new_num = num.charAt(0);
if (Character.isDigit(new_num))
{
userGuess = Integer.parseInt(num);
if (userGuess >= 0 && userGuess < 10)
{
guesses.add(userGuess);
valid = true;
}
else
{
System.out.println("Invalid guess, please enter a number between 0 and 9.");
}
}
else
{
System.out.println("Invalid guess, please enter digit.");
}
}
}
void printGuesses() {
int list_length = guesses.size();
System.out.print("Your guesses: ");
for (int counter = 0; counter < list_length; counter++)
{
System.out.print(guesses.get(counter) + " ");
}
System.out.println();
}
boolean checkLastGuess()
{
int numToTest = guesses.get(guesses.size()-1);
if (numToTest == numToGuess)
{
return true;
}
else
{
return false;
}
}
}
The code is then ran through the following test program
public class GuessingGameTest {
public static void main(String[] args) {
GuessingGame game = new GuessingGame();
System.out.println("Number to guess: " + game.numToGuess);
boolean guessedNumber = false;
while (!guessedNumber) {
game.getGuess();
guessedNumber = game.checkLastGuess();
}
}
}
You're not initializing the arraylist correctly. Change
ArrayList guesses = new ArrayList();
to
ArrayList<Integer> guesses = new ArrayList<Integer>();
Arraylists are generic (ArrayList<E>) in that they require an object to be specified in their construction so that you know what is in the arraylist.

Java SecretWord Code

I am making basic java program to hold a secret word (mouse) and allow a user to guess letters. The program will end either when the user guesses all the letters in the word, or when they guess 7 wrong letters. Whenever I type any letter into the program, it will run through it without giving the user an option to enter another letter. What should I add so that it will only run the program once per letter entered? Also if it wasnt quite obvious I am new to coding.
import java.util.Scanner;
public class GuessWord
{
String Secretword="mouse";
String letter;
int index;
private int number;
private int counter;
private String guesses;
Scanner scan = new Scanner(System.in);
public GuessWord()
{
String Secretword="";
String letter = "";
String guesses = "";
int number = 0;
int counter = 0;
int index = 0;
}
public String getLetter(){
System.out.println("Please enter a letter");
letter = scan.next();
return letter;
}
public void calc(){
guesses=letter;
while(number <= 7 && counter<5)
{
if(Secretword.indexOf(letter) != -1)
{
index = Secretword.indexOf(letter);
System.out.println("You entered a letter in the word");
counter++;
}
else
{
System.out.println("You entered an incorrect letter");
number++;
}
guesses=guesses+" " +letter;
System.out.println("The letters you have guessed are:" + guesses);
}
String str;
if(number == 7){
System.out.println("You lose");
}else
{
System.out.println("You win");
}
}
}//class
public class GuessWordR
{
public static void main(String[]args)
{
GuessWord g1 = new GuessWord();
g1.getLetter();
g1.calc();
}//class
}//main
You should use a while loop.
So while some condition is not met keep asking the user to enter a new key.
Perhaps add a new method to the GuessWord Class
public void startGuessing() {
while(hasGuesses /* some boolean flag */) {
getLetter()
getCalc()
}
}
And then call that method in your main method instead of getLetter() and getCalc().
You will need to add a boolean variable to your class to indicate when to exit this while loop and the logic to keep count of the number of failed guesses etc.
Use a boolean flag and run it in a loop. but for that you need to restructure your code as well. First fix the calc() method
public boolean calc() {
guesses = letter;
if (number <= 7 && counter < 5) {
if (Secretword.indexOf(letter) != -1) {
index = Secretword.indexOf(letter);
System.out.println("You entered a letter in the word");
counter++;
} else {
System.out.println("You entered an incorrect letter");
number++;
}
guesses = guesses + " " + letter;
System.out.println("The letters you have guessed are:" + guesses);
}
String str;
if (number == 7) {
System.out.println("You lose");
return true;
} else if (counter == 5) {
System.out.println("You win");
return true;
} else {
return false;
}
}
Your main method should be update like this
public static void main(String[] args) {
GuessWord g1 = new GuessWord();
boolean completed = false;
while (!completed) {
g1.letter = g1.getLetter();
completed = g1.calc();
}
}
you ask user for input unless condition get satisfied instead of asking and calculating once. And read char by char input instead of reading whole string.
something like:
public static void main(String[]args)
{
GuessWord g1 = new GuessWord();
while(number <= 7 && counter<5){
g1.getLetter();
g1.calc();
}
}//class

How to add for loops to if statements?

In my code below I am not sure what order to put it in to work properly.
I first want it to print out for the user to select an option which it does, then if they select 1 it asks them their name and verifies it with the loop etc.
When I enter a name it starts to just loop the question enter your name and I don't know how to fix it.
Do I need to add more statements to my program, if I do then can I still use if statements for the user to select an option?
import java.util.Scanner;
public class username {
public static void main(String[] args) {
{
int UseLift;
int AuditReport;
int ExitLift;
int a;
UseLift = 1;
AuditReport = 2;
ExitLift = 3;
}
System.out.println("choose an option");
System.out.println("Uselift(1)");
System.out.println("see audit report(2)");
System.out.println("Exit Lift(3)");
Scanner d = new Scanner(System.in);
int a = d.nextInt();
Scanner kb = new Scanner(System.in);
// array containing usernames
String[] name = {"barry", "matty", "olly", "joey"}; // elements in array
if (a == 1) {
System.out.println(" Enter your name ");
}
String name1 = kb.nextLine();
boolean b = true;
int j = 0;// counter will start at 0
outerloop:
while (j < 3) {
System.out.println("Enter your name");
}
for (int i = 0; i < name.length; i++) {
if (name[i].equals(name1)) {
System.out.println("you are verified you may use the lift, calling lift ");
}
break;// to stop loop checking names
}
System.out.println("Username Invalid");
j++;
if (a == 2) {
System.out.println("");
}
if (a == 3) {
System.out.println(" Please Exit Lift ");
}
}
}
here you go:
public static void main(String... args) {
String[] verifiedNames = { "barry", "matty", "olly", "joey" };
System.out.println("choose an option");
System.out.println("Uselift(1)");
System.out.println("see audit report(2)");
System.out.println("Exit Lift(3)");
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1:
scanner.nextLine(); // get '\n' symbol from previous input
int nameAttemptsLeft = 3;
while (nameAttemptsLeft-- > 0) {
System.out.println(" Enter your name ");
String name = scanner.nextLine();
if (Arrays.asList(verifiedNames).contains(name)) {
System.out.println("dear " + name + " you are verified " +
"you may use the lift, calling lift ");
break; // break out of loop
}
}
if (nameAttemptsLeft < 0) {
System.out.println("Username Invalid");
}
break;
case 2:
System.out.println("option 2");
break;
case 3:
System.out.println(" Please Exit Lift ");
break;
}
scanner.close();
}
Your while loop below:
while (j < 3) {
System.out.println("Enter your name");
}
will loop forever since j is not incrementing (j++). I believe you've mis-matched your curly braces at some point.

Categories