我希望程序的输出为R. pandya,如果我进入rachit pandya,但它是说,输入的句子(rachit pandya)的长度是6但它应该是13工作我的程序可以任何人请告诉我错误 代码给出..
public class surName {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the Name-:");
String s = sc.next();
s = " " + s;
for (int i = 0; i < s.length() - 1; i++) {
if (Character.isWhitespace(s.charAt(i))) {
System.out.print(Character.toUpperCase(s.charAt(i + 1)) + ".");
}
}
int a = s.lastIndexOf(" ");
for (int i = a + 1; i < s.length(); i++) {
System.out.print(s.charAt(i));
}
}
}
答案 0 :(得分:1)
而不是
String s = sc.next()
使用
String s = sc.nextLine();//would read your last and first name i.e. whole line as one String
因为next方法只会读取“rachit”标记(默认分隔符空格之前的任何内容)而不是整行。
答案 1 :(得分:0)
这是另一种方式:
Scanner sc = new Scanner(System.in);
System.out.println("name?");
String name = sc.nextLine();
String output[] = name.split(" ");
System.out.println(output[0].charAt(0)+". " + output[1]);