1
public class Valtiotesti 
{
    public static void main(String[] args) 
    {
        Scanner lukija = new Scanner(System.in);
        String nimi, pääkaupunki;
        int asukasluku;

        ArrayList<Valtio> valtiot = new ArrayList<Valtio>();     

        do{
            System.out.println("Anna valtion nimi: ");
            nimi = lukija.nextLine();

            if(nimi.length()>0){
                System.out.println("Anna ko. valtion pääkaupunki: ");
                pääkaupunki = lukija.nextLine();
                System.out.println("Anna ko. valtion asukasluku: ");
                asukasluku = lukija.nextInt();
                Valtio valtio = new Valtio(nimi, pääkaupunki, asukasluku);
                valtiot.add(valtio);
            }
        }
        while(nimi.length()>0);
    }
}

I have this problem with my code: I want to read countries into ArrayList containing country's name (nimi), capital (pääkaupunki), and population (asukasluku), until the user enters empty string as name of the country (just presses enter).

However when the code enters next round, netbeans just prints out the question: "Anna valtion nimi: " (give country's name), and finishes the program (BUILD SUCCESSFUL), WITHOUT giving the chance to enter new Country...

1 Answer 1

4

You must add a nextLine after your nextInt to consume the rest of the line that contained that int :

    if(nimi.length()>0){
        System.out.println("Anna ko. valtion pääkaupunki: ");
        pääkaupunki = lukija.nextLine();
        System.out.println("Anna ko. valtion asukasluku: ");
        asukasluku = lukija.nextInt();
        Valtio valtio = new Valtio(nimi, pääkaupunki, asukasluku);
        valtiot.add(valtio);
        lukija.nextLine();
    }
Sign up to request clarification or add additional context in comments.

1 Comment

@dovy lukija.nextInt() reads part of a line (the newline is not read). Therefore, in the next iteration of the loop, nimi = lukija.nextLine(); gets that new line instead of getting the next line, so nimi.length is 0 (the new line characters are truncated) and the loop is exited.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.