Finding elements in array using for loop - java

import java.util.Arrays;
import java.util.Scanner;
public class Grocer2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String[] names = new String[5];
int count = 0;
while(true){
System.out.println("What is your name: ");
// Store scanner input in name
String name = scan.nextLine();
// Add name into array
names[count] = name;
count++;
if(count == 5){
break;
}
}
System.out.println(Arrays.toString(names));
while(true){
System.out.println("Who are you looking for ? ");
String contact = scan.nextLine();
for(int i = 0; i < names.length; i++){
if(names[i].equals(contact)){
System.out.println("They are in aisle " + i);
}else{
System.out.println("Not here");
}
}
break;
}
scan.close();
}
}
I am trying to add Scanner inputs into an array and I am trying to search for the element in an array using a for loop. The for loop looped through all the elements and print out "Not here" when names[i] is not equal to the Scanner input. How do I fix this issue ?

while(true){
System.out.println("Who are you looking for ? ");
String contact = scan.nextLine();
bool isFound = false;
for(int i = 0; i < names.length; i++){
if(names[i].equals(contact)){
System.out.println("They are in aisle " + i);
isFound = true;
break;
}
}
if(!isFound){
System.out.println("Not here");
}
break;
}

If you want it to print not here only when you have not found the element at all you should put it after the for loop. So you would loop through the whole array if you find the name say that you found it and then if you didn't u can print not here so something like that :
while(true){
System.out.println("Who are you looking for ? ");
String contact = scan.nextLine();
boolean isThere=false;
for(int i = 0; i < names.length; i++){
if(names[i].equals(contact)){
System.out.println("They are in aisle " + i);
isThere = true;
break;// break only if you want the first time the String appeared
}
}
if(!isThere){
System.out.println("Not here");
}
break;
}
Now that should work but here the while loop doesn't do anything. Consider removing it or doing something else with it since when you are doing the first loop you are breaking directly the first time so it's as if there were no loop at all.

You can create a boolean called contactFound and set it to true when a matching name has been found. You may also want to break out of the loop when this happens. Outside of the for loop, print "Not here" if contactFound is false, as shown below.
boolean contactFound = false;
for (int i = 0; i < names.length; i++) {
if (names[i].equals(contact)) {
System.out.println("They are in aisle " + i);
contactFound = true;
break; // If you want the loop to stop when a matching name has been found
}
}
if (!contactFound) System.out.println("Not here");

Your second while loop never loops. And you can use a do-while loop for the first loop. Here is a more compact version of the code:
Scanner scan = new Scanner(System.in);
String[] names = new String[5];
int count = 0;
do {
System.out.println("What is your name: ");
// Add name into array
names[count] = scan.nextLine();
count++;
} while (count != 5);
System.out.println(Arrays.toString(names));
System.out.println("Who are you looking for ? ");
String contact = scan.nextLine();
int aisle = -1;
for(int i = 0; i < names.length; i++){
if(names[i].equals(contact)){aisle = i; break;}
}
if (aisle != -1) System.out.println("They are in aisle " + aisle);
else System.out.println("Not here");
scan.close();
Edit: Doing this is a lot easier with an ArrayList instead of dynamic arrays. Here is a version that uses ArrayLists:
Scanner scan = new Scanner(System.in);
ArrayList<String> names = new ArrayList<>(5);
for (int i = 0; i<5; i++){
System.out.println("What is your name: ");
names.add(scan.nextLine());
}
System.out.println(names);
System.out.println("Who are you looking for ? ");
String contact = scan.nextLine();
if (names.contains(contact)) System.out.println("They are in aisle " + names.indexOf(contact));
else System.out.println("Not here");
scan.close();

import java.util.Arrays;
import java.util.Scanner;
public class Grocer2 {
public static void main(String[] args) {
int count = 0;
int size = 5;
//you should check here
boolean check = false;
Scanner scan = new Scanner(System.in);
String[] names = new String[size];
for (int i = 0; i<size; i++) {
System.out.println("What is your name: ");
// Store scanner input in name
String name = scan.nextLine();
// Add name into array
names[count] = name;
count++;
if (count == size) {
break;
}
}
System.out.println(Arrays.toString(names));
System.out.println("Who are you looking for ? ");
String contact = scan.nextLine();
for (int i = 0; i<names.length; i++) {
if (names[i].equals(contact)) {
System.out.println("They are in aisle " + i);
check = true;
break;
}
}
if (!check) {
System.out.println("Not here");
}
scan.close();
}
}

Related

My program is breaking out of the first for loop after one iteration

Here is my code. It asks user for terms and definitions, then quizzes the user. (It tells the user the term, and the user types in the answer.) The program uses arrays to store the terms and definitions. If the user doesn't get the definition correct, the program asks the user whether they want to study it again. If so, they will type in yes, and the program will store it on a separate array. After the program quizzes the users on all the terms and definitions, round 2 starts, where the program will quiz the user only on the starred definition. The problem is, the code is only running the for loop (that quizzes the user on round 1) once, and then skips onto round 2. Why is that so? I already tried looking at other people's questions and answers, but I can't seem to find the problem in my code.
import java.util.*;
public class Ptcreate {
public static void main(String[] args) {
String term;
String definition;
Scanner userInput = new Scanner(System.in);
System.out.println("How many terms would you like to study?");
int number_terms = userInput.nextInt();
String[] term_array = new String[number_terms];
String[] def_array = new String[number_terms];
String[] star_array = new String[number_terms];
String[] stardef_array = new String[number_terms];
System.out.println("Now, enter the " + number_terms + " terms now.");
for (int i = 0; i < number_terms; i++) {
term_array[i] = userInput.next();
}
System.out.println(
"Now, enter all the definitions, in the correct order such that it matches the order of the terms you entered.");
for (int i = 0; i < number_terms; i++) {
def_array[i] = userInput.next();
}
System.out.println("Ok. Now for the testing!");
for (int i = 0; i <= number_terms; i++) { // the for loop that isn't
// working.
System.out.println("What is definition " + (i + 1));
String answer = userInput.next();
if (answer.equals(def_array[i])) {
System.out.println("Correct");
star_array[i] = "null";
stardef_array[i] = "null";
} else if (!answer.equals(def_array[i])) {
do {
System.out.println("Incorrect.");
System.out.println("Would you like to study this term again? Type y or n.");
String bool = userInput.next();
if (bool.equals("y")) {
star_array[i] = term_array[i];
stardef_array[i] = def_array[i];
} else if (bool.equals("n")) {
star_array[i] = "null";
stardef_array[i] = "null";
}
System.out.println("What is the definition " + (i + 1));
answer = userInput.next();
} while (!answer.equals(def_array[i]));
if (answer.equals(def_array[i])) {
System.out.println(
"Correct"); /*
* when the user finally enters the
* right definition, the program skips
* to the code below
*/
}
}
System.out.println("Now, time for testing definitions you starred!");
for (int z = 0; z < number_terms; z++) {
if (star_array[z].equals("null")) {
break;
} else {
System.out.println("What is the definition of " + star_array[z] + " ?");
String star_answer = userInput.next();
if (star_answer.equals(stardef_array[z])) {
System.out.println("Correct.");
} else if (!star_answer.equals(stardef_array[z])) {
do {
System.out.println("Incorrect. Please try again.");
System.out.println("What is the definition of " + star_array[z] + " ?");
star_answer = userInput.next();
} while (!star_answer.equals(stardef_array[z]));
}
}
}
}
}
}
for (int i = 0; i <= number_terms; i++)
You have number_terms + 1 iterations. Replace with
for (int i = 0; i < number_terms; i++)
The bug is that the for-loop that you have tagged with the comment "the for loop that isn't working" is not looping through all the definitions. This for-loop after handling the first definition it moves on to handling round 2 instead of continuing the loop to the 2nd definition and so on. The fix requires that you place the closing bracket of this for-loop before the print statement "Now, time for testing definitions you starred!" as shown below. I have added the comment "end for-loop to ensure looping of all definitions" at the for-loop closing bracket that I have moved up in the code below. In addition this for loop's iteration condition should be 'i < number_terms' as the previous posters have indicated.
import java.util.*;
public class Ptcreate {
public static void main(String[] args) {
String term;
String definition;
Scanner userInput = new Scanner(System.in);
System.out.println("How many terms would you like to study?");
int number_terms = userInput.nextInt();
String[] term_array = new String[number_terms];
String[] def_array = new String[number_terms];
String[] star_array = new String[number_terms];
String[] stardef_array = new String[number_terms];
System.out.println("Now, enter the " + number_terms + " terms now.");
for (int i = 0; i < number_terms; i++) {
term_array[i] = userInput.next();
}
System.out.println(
"Now, enter all the definitions, in the correct order such " +
"that it matches the order of the terms you entered.");
for (int i = 0; i < number_terms; i++) {
def_array[i] = userInput.next();
}
System.out.println("Ok. Now for the testing!");
for (int i = 0; i < number_terms; i++) { // the for loop that isn't
// working.
System.out.println("What is definition " + (i + 1));
String answer = userInput.next();
if (answer.equals(def_array[i])) {
System.out.println("Correct");
star_array[i] = "null";
stardef_array[i] = "null";
} else if (!answer.equals(def_array[i])) {
do {
System.out.println("Incorrect.");
System.out.println("Would you like to study this term again? Type y or n.");
String bool = userInput.next();
if (bool.equals("y")) {
star_array[i] = term_array[i];
stardef_array[i] = def_array[i];
} else if (bool.equals("n")) {
star_array[i] = "null";
stardef_array[i] = "null";
}
System.out.println("What is the definition " + (i + 1));
answer = userInput.next();
} while (!answer.equals(def_array[i]));
if (answer.equals(def_array[i])) {
System.out.println(
"Correct"); /*
* when the user finally enters the
* right definition, the program skips
* to the code below
*/
}
}
} // end for-loop to ensure looping of all definitions
System.out.println("Now, time for testing definitions you starred!");
for (int z = 0; z < number_terms; z++) {
if (star_array[z].equals("null")) {
break;
} else {
System.out.println("What is the definition of " + star_array[z] + " ?");
String star_answer = userInput.next();
if (star_answer.equals(stardef_array[z])) {
System.out.println("Correct.");
} else if (!star_answer.equals(stardef_array[z])) {
do {
System.out.println("Incorrect. Please try again.");
System.out.println("What is the definition of " + star_array[z] + " ?");
star_answer = userInput.next();
} while (!star_answer.equals(stardef_array[z]));
}
}
}
}
}

How to scramble a word that is picked randomly from a text file

I am attempting to write a program that picks a random word from a text file, scrambles it, and allows the user to unscramble it by swapping 2 index locations at a time.
I have the program to the point where it grabs a random word from the text file and prints it out with the index numbers above it.
I am having trouble figuring out how to:
Get the word scrambled before it prints out on screen, and
How to get the user to be able to loop through swapping 2 indexes at a time until the word is unscrambled.
Is there a method I can write that will perform these actions?
Here is my code so far.
import java.io.*;
import java.util.*;
public class Midterm { // class header
public static void main(String[] args) { // Method header
int option = 0;
Scanner input = new Scanner(System.in);
int scrambled;
int counter = 0;
int index1;
int index2;
String[] words = readArray("words.txt");
/*
* Picks a random word from the array built from words.txt file. Prints
* index with word beneath it.
*/
int randWord = (int) (Math.random() * 11);
for (int j = 0; j < words[randWord].length(); j = j + 1) {
System.out.print(j);
}
System.out.print("\n");
char[] charArray = words[randWord].toCharArray();
for (char c : charArray) {
System.out.print(c);
}
/*
* Prompt the user for input to play game or quit.
*/
System.out.println("\n");
System.out.println("Enter 1 to swap a par of letters.");
System.out.println("Enter 2 to show the solution and quit.");
System.out.println("Enter 3 to quit.");
if (input.hasNextInt()) {
option = input.nextInt();
counter++;
}
else {
option = 3;
}
System.out.println("");
if (option == 1) {
System.out.println("Enter the two index locations to swap separated by a space. ");
index1 = 0;
index2 = 0;
if (input.hasNextInt()) {
index1 = input.nextInt();
}
else {
System.out.println("Please enter only numbers.");
}
if (input.hasNextInt()) {
index2 = input.nextInt();
}
else {
System.out.println("Please enter only numbers.");
}
}
}
// end main
public static String[] readArray(String file) {
// Step 1:
// Count how many lines are in the file
// Step 2:
// Create the array and copy the elements into it
// Step 1:
int ctr = 0;
try {
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine()) {
ctr = ctr + 1;
s1.nextLine();
}
String[] words = new String[ctr];
// Step 2:
Scanner s2 = new Scanner(new File(file));
for (int i = 0; i < ctr; i = i + 1) {
words[i] = s2.next();
}
return words;
} catch (FileNotFoundException e) {
}
return null;
}
}
I made some pretty major modifications to your code, including adding a scrambler method. The program is almost perfect, its just that your file "words.txt" can not hold words with repeat letters. For example, yellow, green, and purple won't unscramble correctly, but white, gray, blue, orange, or red will work fine. Other than that, the program works well. It chooses a random word, then when it is solved, chooses a different word, changing the last word to null, so it does not get picked again. Here's the program:
import java.io.*;
import java.util.*;
public class Experiments { // class header
private static String[] words = readArray("/Users/UserName/Desktop/words.txt"); //change to your location of the file
public static void main(String[] args) { // Method header
int option = 0;
Scanner input = new Scanner(System.in);
int counter = 0;
String scrambledWord;
int index1;
int index2;
Random rand = new Random();
int randWord = rand.nextInt(words.length);
for (int j = 0; j < words[randWord].length(); j += 1) {
System.out.print(j);
}
System.out.print("\n");
scrambledWord = scrambler(words[randWord]);
System.out.println(scrambledWord);
System.out.println("\n");
System.out.println("Enter 1 to swap a pair of letters.");
System.out.println("Enter 2 to show the solution and quit.");
System.out.println("Enter 3 to quit.");
option = input.nextInt();
if (option == 1) {
while (!scrambledWord.equals(words[randWord])) {
index1 = 0;
index2 = 0;
boolean validOption = false;
System.out.println("Enter the two index locations to swap separated by a space.");
while (!validOption) {
if (input.hasNextInt()) {
index1 = input.nextInt();
index2 = input.nextInt();
validOption = true;
}
else {
System.out.println("Please enter only numbers.");
validOption = false;
break;
}
}
String letter1 = scrambledWord.substring(index1, index1+1);
String letter2 = scrambledWord.substring(index2, index2+1);
System.out.println("replacing " + letter1 + " with " + letter2 + "...");
if (index1 < index2) {
scrambledWord = scrambledWord.replaceFirst(letter2, letter1);
scrambledWord = scrambledWord.replaceFirst(letter1, letter2);
} else {
scrambledWord = scrambledWord.replaceFirst(letter1, letter2);
scrambledWord = scrambledWord.replaceFirst(letter2, letter1);
}
System.out.println();
for (int j = 0; j < words[randWord].length(); j += 1) {
System.out.print(j);
}
System.out.println("\n"+scrambledWord);
System.out.println();
counter++;
if (scrambledWord.equals(words[randWord])){
System.out.println("You did it! The word was " + words[randWord]);
System.out.println("You got it with " + counter + " replacements!");
words[randWord] = null;
if (words.length == 0){
System.out.println("I'm all out of words. You win!");
System.exit(0);
} else {
main(args);
}
}
}
} else if (option == 2) {
System.out.println(words[randWord]);
System.exit(0);
} else {
System.exit(0);
}
input.close();
}
//scrambles the word given to it
private static String scrambler(String word) {
String scrambled = "";
Random rand = new Random();
int length;
int index;
String letter;
String firststring;
String secondstring;
while (word.length()>0) {
length = word.length();
index = rand.nextInt(length);
letter = word.substring(index, index+1);
firststring = word.substring(0, index);
secondstring = word.substring(index+1);
word = firststring + secondstring;
scrambled += letter;
}
return scrambled;
}
public static String[] readArray(String file) {
int ctr = 0;
try {
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine()) {
ctr = ctr + 1;
s1.nextLine();
}
String[] words = new String[ctr];
// Step 2:
Scanner s2 = new Scanner(new File(file));
for (int i = 0; i < ctr; i = i + 1) {
words[i] = s2.next();
}
return words;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
And here's the list of words in the file words.txt(I pretty much wrote down whatever popped into my head that did not have repeat letters):
orange
red
brown
black
white
blue
tiger
horse
bugs
stack
overflow
pathfinder
extra
zealous
wisdom
under
above
death
life
second
first
frost
forest
These are obviously not the only words that can go in, you can add as many as you want, as long as they do not have 2 occurrences of the same letter.
You are reading the file incorrectly. Do
public static String[] readArray(String file) {
int ctr = 0;
try {
Scanner s1 = new Scanner(new File(file));
while (s1.hasNext()) {
ctr = ctr + 1;
s1.next();
}
//..rest of code

For Loop Stalls on Second Time in Java

I am trying to make some code that should keep track of a win/loss ratio. I have a for loop that checks if a name is present in a separate variable, this works but when I try to do it again it stalls.
System.out.println("\nEnter Name 1");
scan.nextLine();
String name1 = scan.nextLine();
for (int i = 0; i < numPlayers; i++) {
if (name1.equals(players[i].name)) {
players[i].win++;
break;
}
}
System.out.println("\nEnter Name 2");
scan.nextLine();
String name2 = scan.nextLine();
for (int i = 0; i < numPlayers; i++) {
if (name2.equals(players[i].name)) {
players[i].loss++;
break;
}
}
After the code it should go back to a while loop, but it just stalls instead. If I comment out the name 2 part, the code works, but I need both parts.
Edit 1:
Heres the whole code
public class Counter {
#SuppressWarnings("resource")
public static void main(String[] args) {
int intTemp;
String stringTemp;
int keepGoing = 1;
int numPlayers = 0;
Player[] players = new Player[999];
Scanner scan = new Scanner(System.in);
System.out.println("Melee Score Tracker");
while (keepGoing == 1) {
System.out.println("\nPrint Scores\t1\nNew Match\t2\nNew Player\t3\nExit\t\t4");
intTemp = scan.nextInt();
// Print Scores
if (intTemp == 1) {
intTemp = 0;
System.out.print("\n");
for (int i = 0; i < numPlayers; i++) {
players[i].print();
}
}
// New Match
if (intTemp == 2) {
intTemp = 0;
System.out.println("\nEnter Name 1");
scan.nextLine();
String name1 = scan.nextLine();
for (int i = 0; i < numPlayers; i++) {
if (name1.equals(players[i].name)) {
players[i].win++;
break;
}
}
System.out.println("\nEnter Name 2");
scan.nextLine();
String name2 = scan.nextLine();
for (int i = 0; i < numPlayers; i++) {
if (name2.equals(players[i].name)) {
players[i].loss++;
break;
}
}
}
// New Player
if (intTemp == 3) {
intTemp = 0;
System.out.println("\nWhat's the player's name?");
scan.nextLine();
stringTemp = scan.nextLine();
players[numPlayers] = new Player();
players[numPlayers].name = stringTemp;
numPlayers++;
System.out.println(numPlayers);
}
// Exit
if (intTemp == 4) {
System.exit(0);
}
}
}
}
It stalls because of this;
scan.nextLine();
scan.nextLine();
String name2 = scan.nextLine();
It is waiting for input 3 times. You only want input once so replace it with;
String name2 = scan.nextLine();
In the future things like this can easily be debugged by checking if the code actually enters the for loop by printing out a little message in the loop.
String name2 = scan.nextLine();
for (int i = 0; i < numPlayers; i++) {
System.out.println("We have entered the loop.");
if (name2.equals(players[i].name)) {
players[i].loss++;
break;
}
}
If you see output in the console then you know the problem is not with the loop itself, but is before it.

Where do i write if item is not found, and display an appropriate message?

public static void modifyBall(String[] hookPotentialArray, String[] nameBallArray, int[] ballWeightArray, int count) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the name of the ball you would like to modify: ");
String name = keyboard.nextLine();
for (int i = 0; i < count; i++) {
if (name.compareToIgnoreCase(nameBallArray[i]) == 0) {
System.out.println("Please enter a new name for the ball: ");
String ballName = keyboard.nextLine();
System.out.println("Please enter a new weight for the ball: ");
int ballWeight = keyboard.nextInt();
System.out.println("Please enter a new hook potential for the ball: ");
String hookPotential = keyboard.next();
nameBallArray[i] = ballName;
ballWeightArray[i] = ballWeight;
hookPotentialArray[i] = hookPotential;
System.out.println("The ball list has been updated.");
System.out.println("");
}
}
You should refactor to separate the loop for finding/not finding the ball (or not), and do whatever you need to do with the ball (or error if not found) OUTSIDE the loop. This helps with readability because more of your lines are less indented, and it helps communicate your intent because most of your code in the loop is only going to be executed once anyway.
int ballIndex = -1;
for (int i = 0; i < count; i++) {
if (name.compareToIgnoreCase(nameBallArray[i]) == 0) {
ballIndex = nameBallArray[i];
break;
}
}
if (ballIndex >= 0) {
// found - do everything using ballIndex
} else {
// not found - display error
}
Set a flag variable to 0 before loop. Inside if set it 1. After the loop check if it is still zero. then print appropriate message that no item found.
Boolean flag = false; // before loop
flag = true; //inside if
// After loop
if(!flag)
System.out.println("Not Found");
Try this:
public static void modifyBall(String[] hookPotentialArray, String[] nameBallArray, int[] ballWeightArray, int count) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the name of the ball you would like to modify: ");
String name = keyboard.nextLine();
for (int i = 0; i < count; i++) {
if (name.compareToIgnoreCase(nameBallArray[i]) == 0) {
System.out.println("Please enter a new name for the ball: ");
String ballName = keyboard.nextLine();
System.out.println("Please enter a new weight for the ball: ");
int ballWeight = keyboard.nextInt();
System.out.println("Please enter a new hook potential for the ball: ");
String hookPotential = keyboard.next();
nameBallArray[i] = ballName;
ballWeightArray[i] = ballWeight;
hookPotentialArray[i] = hookPotential;
System.out.println("The ball list has been updated.");
System.out.println("");
return;
}
}
System.out.println("ball not found");
}
You could create a boolean and set it to true in your if statement that means it's been found. You could check the boolean after loop to see if it's true or false then display error message if true.
Example:
public static void modifyBall(String[] hookPotentialArray, String[] nameBallArray, int[] ballWeightArray, int count) {
boolean found = false; //boolean for if it's found or not
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the name of the ball you would like to modify: ");
String name = keyboard.nextLine();
for (int i = 0; i < count; i++) {
if (name.compareToIgnoreCase(nameBallArray[i]) == 0) {
found = true; //set boolean if found
System.out.println("Please enter a new name for the ball: ");
String ballName = keyboard.nextLine();
System.out.println("Please enter a new weight for the ball: ");
int ballWeight = keyboard.nextInt();
System.out.println("Please enter a new hook potential for the ball: ");
String hookPotential = keyboard.next();
nameBallArray[i] = ballName;
ballWeightArray[i] = ballWeight;
hookPotentialArray[i] = hookPotential;
System.out.println("The ball list has been updated.");
System.out.println("");
break; //break out of loop if item found
}
}
//check if boolean is false then print error message
if (!found)
{
System.out.println("There was a problem finding your item.");
}
I also added a break at end of if statement to break out of the loop if the item was found(no point in continuing on if the item was already found).

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