Reputation: 11
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;
}
}
}
}
Upvotes: 1
Views: 518
Reputation: 637
String type;
String word;
String words[] = new String[100];
int i = 0;
String k = "end";
System.out.println("Type a word: ");
word = sc.next();
words[i] = word;
while (word.compareToIgnoreCase(k) != 0) {
i = i + 1;
word = sc.next();
words[i] = word;
}
System.out.println("What type A,B,C:");
typ = sc.next();
if (typ.equals("B")) {
int lenght = words.length;
i = 0;
while (i < lenght-1) {
System.out.print(words[i]);
System.out.println();
i = i + 1;
}
}
}
}
Upvotes: 0
Reputation: 898
Your problem is that in the first loop where your adding things to the array you increment the counter after you do the assignment. This means that your index at the end represents the length + 1.
So you start at 1 (though Java arrays start at 0, so you never assign a value to the first entry in the array, not sure if thats intentional).
So when you add Cat the index becomes 2.
Further down you then add 1 to the length, with
lenght = i + 1;
The most simplest answer would be to remove this one line, though there is a lot of other re-factoring you could do to reduce the amount of code in this.
Upvotes: 0
Reputation: 121669
Arrays start at "0", not "1".
// Better
int i = 0
...
while (word.compareToIgnoreCase(k) != 0) {
words[i++] = word;
word = sc.next();
}
i = 0;
while (i < length) {
System.out.print(words[i++]);
System.out.println();
}
There are several things about your logic I don't understand, but I assume you probably want to add one "word" each time.
And I'm almost certain you probably want to start at index "0", and stop at "length-1". Because "array[length]" and all subsequent elements will default to "null".
Upvotes: 0
Reputation: 156534
You just need to add that last word to the array:
while (word.compareToIgnoreCase(k) != 0) {
words[i] = word;
i = i + 1;
word = sc.next();
}
words[i] = word; // Add the last item entered
By the way, I'd advise using a List<String>
instead of a String[]
, and calling words.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.
Upvotes: 2