2

So I'm having a problem doing an assignment for my java class. The purpose is to create a program that uses a switch statement to convert letters from a string to their phonetics. i.e, A or a becomes Alpha.

The problem I'm having is the switch statement stops reading at the first whitespace in the string. How do i get it to continue reading the string without stopping at whitespaces (i.e " ")?

Basically user inputs a string "Hi Hi" the output should be "Hotel Indiana Hotel Indiana"

The problem I'm having is it only gives "Hotel Indiana" stopping at the first whitespace i think at least.

This is the code i have so far:(I cut out most of the letters/numbers to save space and kept what i thought was most important for answering the question.)

    import java.util.*;
    public class SwitchStatement {

/**
 * @param args
 */
public static void main(String[] args) {

    Scanner keyboard = new Scanner(System.in);
    System.out.println ("Enter a message: ");
    String message = keyboard.next(); 
    for(int i = 0 ; i < message.length(); i++) 
      switch(message.charAt(i)) { 
    case 'a':
    case 'A':  
        System.out.print("Alpha"); 
        break; 
    case 'b':
    case 'B':  
        System.out.print("Bravo"); 
        break;
    case ' ':  
                System.out.print(" "); 
                break;
    default:  
                System.out.print(message.charAt(i)); 
                break;
}

}
}

Thanks in advance for the help.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
user1761953
  • 47
  • 1
  • 6

2 Answers2

2

String message = keyboard.next(); reads one word at the time of call separated by space (" ").

Use String message = keyboard.nextLine(); to read the whole line including spaces within.

Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73
0

You should use nextLine. If you use next() deliminator comes in to picture which is space char. So eventually you end up reading only one token not full string.

String message = keyboard.nextLine();

e.g For below string

A a  B b
keyboard.next()---> will return you A if you again call then B and so on
keyboard.nextLine()-->will return you whole line ie. A a  B b which you want
Amit Deshpande
  • 19,001
  • 4
  • 46
  • 72