Complete the code below. The prompts the user \"Enter string\". If the user type
ID: 3693146 • Letter: C
Question
Complete the code below. The prompts the user "Enter string". If the user types a 10 character string, then the program must put a hypen after the 3rd character. If the length of the string is not exactly 10 characters, the program must display a message saying; "invalid string" Sample outputs: Enter string: 1234567890 123-4567890 Enter string: 12345 Invalid string import.java.util.Scanner; public class StringFormatter { public static void main(String[]args) scanner kb = new Scanner(system.in); System.out.print("Enter string:"); String str = kb.next(); //COMPLETE CODE BELOW
Explanation / Answer
import java.util.Scanner;
/**
* @author
*
*/
public class StringFormatter {
/**
* @param args
*/
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("Enter string:");
String str = kb.next();
// COMPLETE CODE BELOW
// check weather it is having 10 chars or not
if (str.length() != 10) {
System.out.println("Invalid String");
} else {
// getting substring and insert - after 3rd char
str = str.substring(0, 3) + "-" + str.substring(3, 10);
System.out.println(str);
}
}
}
OUTPUT:
Enter string:1234567890
123-4567890
Enter string:12345
Invalid String