简体   繁体   中英

printing names after the while loop

I'm practicing on my java and I'm having issues trying to figure out how to print the names entered from the user. I placed name in the print statement and it didn't work. I also tried concatenating it also no luck. If someone could show me in the right direction that would be great

import java.util.Scanner;
public class name{
    public static void main(String[] args){

    Scanner input = new Scanner(System.in);
    System.out.print("Enter a name or type END to exit");

    String name = "name";
    int i = 0;  

    while(i < 10){
    System.out.print("Type your name: ");
    i++;

    name = input.next(); 
    if(name.equals("end"))break;    
    }
      System.out.print(name);
  }
}

It seems that implementation will only print out the last name. A collection eg nameList can be used to add each name as they are being put in the list

import java.util.*;

class Scratch {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a name or type END to exit");

        String name;

        ArrayList<String> nameList = new ArrayList<>();

        int i = 0;
        while (i < 10) {
            System.out.print("Type your name: ");
            i++;

            name = input.next();
            nameList.add(name);
            if (name.equals("end")) break;
        }
        System.out.println(nameList);
    }

}

If you dont want 'end' to appear in the final output you can swap the break line and the .add line

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