-1

I am writing a program to get a user to enter a list of 10 names or to enter "ZZZ" when finished less than 10. I need the program to count the names, but not the "ZZZ". It is counting the "ZZZ". How can I fix this?

for (int n = 0; n <= 10; n++) {
    System.out.println("Enter name");
    names[n]= input.nextLine();           
    /*Count names, but don't count ZZZ*/
    count++;//???How do I do this???
}
azurefrog
  • 10,785
  • 7
  • 42
  • 56
Lisa
  • 19
  • 4
  • possible duplicate of https://stackoverflow.com/q/7370174/1707353 – Jeff Holt Aug 02 '19 at 21:07
  • You probably want to actually first put `input.nextLine()` into its own string variable, and then _check_ what its value is before you decide to add it to `names`, either adding the value, or breaking out of your for loop. – Mike 'Pomax' Kamermans Aug 02 '19 at 21:09
  • Insert this just above `count++;`: `if(names[n].equals("ZZZ")) { names[n] = ""; break; }` – RaminS Aug 02 '19 at 21:12
  • A better solution, though, is to not use a fixed array. Instead, use an `ArrayList names` that you can append strings to, do `String name = input.nextLine()`, check what that `name` is, and if it equals `ZZZ`, break. If it's not, `names.add(name)` and keep going. – Mike 'Pomax' Kamermans Aug 02 '19 at 21:15

2 Answers2

0
for (int n = 0; n <= 10; n++) {
    System.out.println("Enter name");
    String name = input.nextLine();           
    /*Count names, but don't count ZZZ*/
    if(name.equals("ZZZ")) {
        break;
    }
    names[n] = name;
    count++;
}
0

This presumes you have a array or list to hold the names.

List<String> names = new ArrayList<>();
int count = 0;
for (int n = 1; n <= 10; n++) {
    System.out.println("Enter name");
    String name = input.nextLine();
     if (name.equals("ZZZ")) {
          break;
     }
     count = n;    
    names.add(name);
}

System.out.println(names);
WJS
  • 36,363
  • 4
  • 24
  • 39
  • Clearly she has an array called `names` to hold the names as presented in the question. – RaminS Aug 02 '19 at 21:13
  • 2
    @Mike'Pomax'Kamermans https://stackoverflow.com/questions/4166966/what-is-the-point-of-the-diamond-operator-in-java-7 – RaminS Aug 02 '19 at 21:14
  • 1
    @Mike'Pomax'Kamermans Nope. It is best to use the interface when assigning an implementation. And the type qualifier is not required on the right hand side. – WJS Aug 02 '19 at 21:17
  • It is an array. – Lisa Aug 02 '19 at 21:53