简体   繁体   中英

for loop is executing only once

I am trying to obtain the following output but I am getting only first character ie loop is executing only once while the code is correct. How to resolve this issue?

input : chirag hello bye
output : chb

Code:

public class PrintFirstLetter {

    public static void main(String[] args) {

        System.out.println("input");
        Scanner sc = new Scanner(System.in);    
        String st=sc.next();

        char[] ch = st.toCharArray();

        for (int i = 0; i < ch.length; i++) {       
            if((i==0&&ch[i] !=' ')||(ch[i] !=' '&&ch[i-1]==' '))
                System.out.print(ch[i]);        
        }
    }

You have input taken as String st=sc.next() which takes in the string till a space is encountered. Hence, only the first word gets stored in the String st. Try changing the line to String st=sc.nextLine() which will work.

why don't you just try

st.length();

it also returns the length of the string.

The problem is not in the for loop. the problem is in input method that is

next()

method takes only single word as input. for multiword input you need to use

nextLine()

method. You can confirm it by printing the String st. Hope it helps :)

as stated above you should use nextLine(); instead of next(); you can also use trim() to remove spaces. a simple implementation :

import java.util.Arrays;
import java.util.Scanner;
public class PrintFirstLetter {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("input :");
String input = sc .nextLine();
String[] words = input.split(" ");
for (String s: words)
{
    s=s.trim();
    System.out.println("output : " + s.charAt(0));
 } 
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM