Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a while loop in an ArrayList

Tags:

java

I'm new to programming and to this website, so here goes. I wanted to write a program that would allow as many input strings as possible to be added to an ArrayList. So I used a while loop in the following code. What I intended was for the loop to break if the input was 0.

import java.util.*;

public class AddToList2
{
static Scanner q = new Scanner(System.in);

public static void main(String[] args)
{
    ArrayList<String> inputlist = new ArrayList<String>();
    while (true)
    {
        System.out.print("Enter something here: ");
        String x = q.nextLine();
        inputlist.add(x);
        if (x.equals("0"));
            break;
    }
}

The program was compiled without error, but sadly, when I ran the program many times, the loop broke no matter what the input was. Any way to solve this?

Well, that was careless of me! Anyway, I had created that program in order to find out what was wrong with this:

ArrayList<String> endangeredlist = new ArrayList<String>();
    ArrayList<Integer> popn = new ArrayList<Integer>();
    while (true)
    {
        System.out.print("Name an animal: ");
        String animal = q.nextLine();
        endangeredlist.add(animal);
        if (animal.equals("EXTERMINATE"))
            break;          
        q.next();
        System.out.print("How many are left in the wild? ");
        int numberleft = q.nextInt();
        popn.add(new Integer(numberleft));
    }

(This is part of a much larger program.) My intention was for the loop to break when the animal name input was EXTERMINATE. Sadly the program throws a NoSuchElement exception if the input first time round was EXTERMINATE, and if I had inputted something else first the loop would start, but then inputting EXTERMINATE second time round does not break the loop. Why is that?

like image 771
user1762169 Avatar asked Apr 17 '26 23:04

user1762169


2 Answers

You have an extraneous semicolon after your if, which effectively makes it

if (x.equals("0")) { }
break;
like image 123
Jon Newmuis Avatar answered Apr 20 '26 14:04

Jon Newmuis


You have a semi-colon at the end of your condition.

This turns the break into a statement of its own, without the condition.

like image 36
alex Avatar answered Apr 20 '26 13:04

alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!