Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!

How to loop again while there is no input?

New member
Joined
Feb 21, 2023
Messages
2
I was hoping you could help me with my java code.

Here is the code:

Code:
public static void main(String[] args)
{
     Scanner in = new Scanner(System.in);
    
 ArrayList<String> name = new ArrayList<String>();
 ArrayList<String> team = new ArrayList<String>();
 ArrayList<String> pos = new ArrayList<String>();
  
 for(int s=0; s<2; s++)
 { 
 System.out.println("Enter Player Name: ");
 name.add(in.nextLine());
 do {
 System.out.println("Please Enter a Name\n");
 System.out.println("Enter Player Name: ");
 name.add(in.nextLine()); 
 }
 while(name.contains(""));
    
 System.out.println("Enter Basketball Team: ");
 team.add(in.nextLine());

 System.out.println("Enter your Position: ");
 pos.add(in.nextLine());
 }   
    
 for(int i=0; i<name.size(); i++)
 {
 System.out.println(name.get(i)+"\t"+team.get(i)+"\t\t"+pos.get(i));
  }     
    }
   }
What I'm trying achieve is that, in each scanner you are required to input something. If it doesn't have any it will ask you to input something. It will not continue to the other scanner but instead it will loop again to that same scanner until you input something.
I tried in the scanner "name.add" do-while loop where if you don't have any input it will continuously ask you to input a name. the problem is that even if I input something it doesn't proceed to the other scanner anymore.
 
New member
Joined
Feb 21, 2023
Messages
2
The reason it keeps looping is because you have this condition: while(name.contains("")); this means that after you entered an empty line it will have this value "" in the array as it adds this value regardless if the value is valid or not. This means that you will keep looping in this do-while loop.
The easiest way I can think of to fix this is to have a separate boolean value to check if the input is different than empty space, and then only after it passes this validation you will add this to the name array.
 
Top