user8203210
user8203210

Reputation:

for loop is executing only once

I am trying to obtain the following output but I am getting only first character i.e. 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]);        
        }
    }

Upvotes: 1

Views: 76

Answers (4)

karim mohamed
karim mohamed

Reputation: 3

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));
 } 
}
}

Upvotes: 0

Mohit Singh
Mohit Singh

Reputation: 31

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.

Upvotes: 3

Pranay Pujari
Pranay Pujari

Reputation: 35

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 :)

Upvotes: 0

Ankur Dubey
Ankur Dubey

Reputation: 29

why don't you just try

st.length();

it also returns the length of the string.

Upvotes: 0

Related Questions