+ 1
I don't understand why can't initialize strings like this
import java.util.ArrayList; import java.util.Scanner; public class Main { public static void reapeat(int n,String...b) { //String b; } public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("enter the number of baloon"); Scanner sc=new Scanner(System.in); int n= sc.nextInt(); ArrayList<String>colors=new ArrayList<String>(); // ArrayList<String>colors2=new ArrayList<String>(); System.out.println("enter the name of "+n+" color(s)"); String []s; s=new String[n]; for(int i=0;i<=n;i++) { colors.add(sc.nextLine()); s[i]=colors.get(i); } } }
7 Respostas
+ 5
David Bukedi Problem is your for loop. You are doing like this:-
for(int i=0;i<=n;i++)
Here suppose you are taking n = 5 but according to your loop it will go i = 0 to i = 5 which will give IndexOutofBound exception Because you have String Array with size 5 only. But you are accessing 6th value from the array.
s[o]
s[1]
s[2]
s[3]
s[4]
s[5] // Wrong, give IndexOutofBound exception
You need to change your loop by this:-
for(int i=0;i<n;i++)
+ 2
Thank you
+ 1
It's a problem with Sololearn input. We cannot take input inside loop. We have to take multiple input with new line.
https://code.sololearn.com/WhiNb9BkJUVC/?ref=app
+ 1
Ho nonono don't pay attention to the function repeat, just the function main
+ 1
That's where i get the index out of bounds exception
+ 1
Actually , I'm trying to find a way to initialize an array of strings with a for loop
0
declaration:
String b;
initialization:
String b = "";
But I would not use b as variable name because you used already b as parameter (String...b).
Maybe it helps to explain what you are want to do.