I don't understand why can't initialize strings like this | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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); } } }

2nd Apr 2020, 2:38 PM
David Bukedi Diela
David Bukedi Diela - avatar
7 Answers
+ 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++)
2nd Apr 2020, 3:05 PM
A͢J
A͢J - avatar
+ 2
Thank you
2nd Apr 2020, 3:14 PM
David Bukedi Diela
David Bukedi Diela - avatar
+ 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
2nd Apr 2020, 2:44 PM
A͢J
A͢J - avatar
+ 1
Ho nonono don't pay attention to the function repeat, just the function main
2nd Apr 2020, 2:49 PM
David Bukedi Diela
David Bukedi Diela - avatar
+ 1
That's where i get the index out of bounds exception
2nd Apr 2020, 2:49 PM
David Bukedi Diela
David Bukedi Diela - avatar
+ 1
Actually , I'm trying to find a way to initialize an array of strings with a for loop
2nd Apr 2020, 2:50 PM
David Bukedi Diela
David Bukedi Diela - avatar
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.
2nd Apr 2020, 2:47 PM
Denise Roßberg
Denise Roßberg - avatar