+ 4

Can you help me with what's wrong with my code? I want to input a sentence and print each word in separate lines

import java.util.Scanner; public class string { public static void main(String[] args) { String s,w=" "; Scanner sc = new Scanner (System.in); s=sc.nextLine(); s=s+" "; int len=s.length(); for(int i=0;i<len;i++) { char c=s.charAt(i); if(c!=' ') { w=w+c; } else { System.out.println(w); } w=" "; } } }

8th Apr 2019, 9:46 AM
Drishya
Drishya - avatar
2 odpowiedzi
+ 6
https://code.sololearn.com/cCu3b35BKQx1/?ref=app Your code debugged ... Basically what you were doing was w=" " On every iteration of loop but we need it only when c==' ' so after printing w ,in the else block, do w=" " there..
8th Apr 2019, 10:13 AM
Saksham Jain
Saksham Jain - avatar
0
why you typed s=s+” “ ?
23rd Feb 2020, 2:18 PM
Arian
Arian - avatar