I’m not quite sure, where the problem is.
Code is working properly but, after I type few words i.e:
Cat
Cats
End
It shows me:
Cat
Cats
null.
My guessing is on String k or with size of array.
So I think, I need to input somehow “end” work, am i right ?
public static void main(String[] args) {
Scanner sc = new Scanner(System. in );
String type;
String word;
String words[] = new String[100];
int i = 1;
String k = "end";
System.out.println("Type a word: ");
word = sc.next();
while (word.compareToIgnoreCase(k) != 0) {
words[i] = word;
i = i + 1;
word = sc.next();
}
System.out.println("What type A,B,C:");
typ = sc.next();
if (typ.equals("B")) {
int lenght = words.length;
lenght = i + 1;
i = 1;
while (i < lenght) {
System.out.print(words[i]);
System.out.println();
i = i + 1;
}
}
}
}
You just need to add that last word to the array:
By the way, I’d advise using a
List<String>instead of aString[], and callingwords.add(word). For one thing, this means you won’t have to keep track of your index (i). More importantly, the list can get as long as you like, and you will only use as much memory as you need.