+ 8

Java Help Needed

public class Program { public static void main(String[] args) { String str = "sololearn"; for(int k=0;k<str.length();k++) { if(k%2==0) System.out.print(str[k]); else System.out.print("+"); } } } why this program is not running?

10th Apr 2017, 12:46 PM
Ajay Agrawal
Ajay Agrawal - avatar
13 Respuestas
+ 12
@Ajay You can use str.charAt() and there are many more available:D
10th Apr 2017, 12:58 PM
Dev
Dev - avatar
+ 12
@Ajay Yes, it outputs places....I never knew you wanted characters:)
10th Apr 2017, 1:38 PM
Dev
Dev - avatar
+ 11
public class Program { public static void main(String[] args) { String str = "sololearn"; for(int k=0;k<str.length();k++) { if(k%2==0) System.out.print(String.valueOf(k)); else System.out.print("+"); } } } Hope this helps! 😊
10th Apr 2017, 12:53 PM
Dev
Dev - avatar
+ 9
@Dayve is their any alternative available for this problem? just for first print line.
10th Apr 2017, 12:55 PM
Ajay Agrawal
Ajay Agrawal - avatar
+ 9
@Dayve String.valueOf(k) is printing places of k, not characters.
10th Apr 2017, 1:13 PM
Ajay Agrawal
Ajay Agrawal - avatar
+ 9
@Dayve sorry, I forgot to tell that. 😁
10th Apr 2017, 1:45 PM
Ajay Agrawal
Ajay Agrawal - avatar
+ 8
Thanks guys, this looks something appropriate for me.☺
10th Apr 2017, 1:01 PM
Ajay Agrawal
Ajay Agrawal - avatar
+ 8
@Nivedita Vaidya if I declare String str="sololearn"; then why it's not working?
11th Apr 2017, 4:47 AM
Ajay Agrawal
Ajay Agrawal - avatar
+ 4
Replace str[k] with str.charAt(k)
10th Apr 2017, 12:55 PM
AtoMX
AtoMX - avatar
+ 4
This is another way to get your answer public class Program { public static void main(String[] args) { String str[] = {"s","o","l","o","l","e","a","r","n"}; for(int k=0;k<str.length;k++) { if(k%2==0) System.out.print(str[k]); else System.out.print("+"); } } }
11th Apr 2017, 4:44 AM
Nivedita Vaidya
Nivedita Vaidya - avatar
+ 4
str is a string variable and you are accessing it as an array as str[k] hence it is not working.
11th Apr 2017, 6:19 AM
Nivedita Vaidya
Nivedita Vaidya - avatar
0
I like you
11th Apr 2017, 5:32 AM
shohag
0
i like you
11th Apr 2017, 5:33 AM
shohag