简体   繁体   中英

Using a while loop in an ArrayList

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?

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

if (x.equals("0")) { }
break;

Your if statement is broken

if (x.equals("0"));

This is basically saying if (x.equals("0")) do nothing...

This is one of the reasons why you should use parenthesis around your if statements

if (x.equals("0")) {
    break;
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM