Reputation: 171
I'm having a problem with this code:
package Jensen;
import java.util.Scanner;
public class JensenUppgift7 {
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
String[] ord = new String[10];
System.out.println("Hej och välkommen till mitt program. Det här programmet" +
" kommer fråga dig att mata in ord som du väljer och sedan skriva " +
"ut de i omvänd ordning.");
for(int x = 0; x < ord.length; x++)
{
System.out.println("Skriv ett ord. Avsluta programmet genom att skriva 'Sluta'");
String indata = scanner.next();
if(indata.compareTo("Sluta") == 0 || x == ord.length - 1)
{
for(int i = x; i >= 0; i--)
if(i == 0)
System.out.print(ord[i] + ".");
else
System.out.print(ord[i] + ", ");
break;
}
else
ord[x] = indata;
}
}
}
The program asks for ten strings or less and prints them out in reversed order. My problem is that the last input value that is going to be the first one printed out is equal to null when I iterate through the array. I'm not sure why. The rest of the inputs are printed out correctly.
Upvotes: 0
Views: 110
Reputation: 213391
You are not assigning the last value to the array at all. The below if
condition:
if(indata.compareTo("Sluta") == 0 || x == ord.length - 1)
becomes true
when the value of x
is ord.length - 1
, which is the last index, and it doesn't reach the else
block, where you are assigning the value to the array.
You don't need to have that 2nd condition in the if
block. The for
loop will take care of your indices. Just remove it.
Also you can use equals
method instead of compareTo
to check for equality. and since you are comparing the value from user input, I suggest you to do an ignore case comparison:
if(indata.equalsIgnoreCase("Sluta"))
Actually I don't understand the logic of this if
block, as you are starting to print the array based on this condition. But it's sure that, if you print the array there, it won't be fully filled. Since your messages are not in English, it hard to guess what are you trying to do. Is it some kind of exit condition? Generally you don't have an exit condition, when you are storing the user input in an array. You let the array indices decide when to stop.
I'll let you decide what you actually want, and after doing the required changes, you can run another for
loop after the given for
loop, to print the values in array in reverse.
Upvotes: 4
Reputation: 12174
The last element is left out from the input loop. Change the condition x == ord.length - 1
to x == ord.length
.
Upvotes: 1