Reputation: 29
I'm trying to make a program that asks the user to type in 3 cities and the program is supposed to take the 3 cities , and put them in a String Array , the first city in [0],second in [1] and third in [2] , I got it to ask for them , collect the answers but it's only Printing out the first answer, not all 3. Any ideas how I can fix that?
My code looks like this atm
public static void main(String[] args) {
String ans;
String[] favoritStad = new String [3];
Scanner scanner1 = new Scanner (System.in);
System.out.println("skriv in 3 favoritstäder");
String Användarinlägg1 = scanner1.nextLine();
String Användarinlägg2 = scanner1.nextLine();
String Användarinlägg3 = scanner1.nextLine();
favoritStad[0] = Användarinlägg1;
favoritStad[1] = Användarinlägg1;
favoritStad[2] = Användarinlägg1;
System.out.print(Användarinlägg1);
}
Användarinlägg is userinputt , favorit stad is favcity the string "ans" was just an idea I tried to make to collect all 3 answers and print it out but never figured it out
Solved it ! Just needed to add
System.out.print(Användarinlägg2);
System.out.print(Användarinlägg3);
Upvotes: 1
Views: 1436
Reputation: 1
Also you need to print...
System.out.print(favoritStad);
instead of
System.out.print(Användarinlägg1);
Upvotes: 0
Reputation: 14199
Try this way
favoritStad[1] = Användarinlägg2;
favoritStad[2] = Användarinlägg3;
Now Print Array:
1st way :
for(int i=0; i<favoritStad.length; i++) {
System.out.println(favoritStad[i]);
}
2nd way:
for(String s :favoritStad) {
System.out.println(s);
}
Upvotes: 0
Reputation: 3235
You can use for
loop to print all the values of an array. You can use something like below:
for (int i=0; i<favoritStad.length();i++){ System.out.println(favoritStad[i]) }
Upvotes: 0
Reputation: 1431
As I suggested in my comment below your question - use a for
loop. Also always check twice if you are not using the same variable (for example Användarinlägg1
) over and over.
favoritStad[0] = Användarinlägg1;
favoritStad[1] = Användarinlägg2;
favoritStad[2] = Användarinlägg3;
for(int i=0; i<favoritStad.length; i++) {
System.out.println(favoritStad[i]);
}
Upvotes: 2
Reputation: 19284
In your code you've added the same element 3 times.
You need to use:
favoritStad[0] = Användarinlägg1;
favoritStad[1] = Användarinlägg2;
favoritStad[2] = Användarinlägg3;
And in order to print you can use for loop or just:
System.out.print(favoritStad[0]);
System.out.print(favoritStad[1]);
System.out.print(favoritStad[2]);
Upvotes: 0