我想在使用数组和循环输入名称时获得名字
示例:
Enter the name : 1. Alvin Indra 2. Sada Rika
输出:
1. Alvin 2. Sada
代码:
public static void main(String[] args) {
int n;
String teman[],namadepan[];
Scanner sc = new Scanner(System.in);
Scanner x = new Scanner(System.in);
System.out.print("Put how many friends : ");
n = sc.nextInt();
teman = new String[n];
namadepan = new String[n];
for(int i=0;i<n;i++){
System.out.print("Friend Of-"+(i+1)+" : ");
teman[i] = x.nextLine();
}
System.out.print("\n");
System.out.println("First Name : ");
for(int i=0;i<n;i++){
if(teman[i] == ' '){ // this is where I need help
System.out.println((i+1)+". "+teman[i].substring(0,i));
}
}
}
答案 0 :(得分:1)
你去吧
String name = "John Smith";
System.out.println(name.split(" ")[0]);
使用它将替换第二个for循环,你不需要循环遍历每个字母以寻找空格,你可以在字符串上使用split方法并指定将字符串拆分的字符然后调用第一个元素。
import java.util.Scanner;
public class testest {
public static void main(String[] args){
int n;
String teman[],namadepan[];
Scanner sc = new Scanner(System.in);
Scanner x = new Scanner(System.in);
System.out.print("Put how many friends : ");
n = sc.nextInt();
teman = new String[n];
namadepan = new String[n];
for(int i=0;i<n;i++){
System.out.print("Friend Of-"+(i+1)+" : ");
teman[i] = x.nextLine();
}
System.out.print("\n");
for(int i=0;i<n;i++){
System.out.println("First Name : ");
System.out.println(teman[i].split(" ")[0]);
System.out.print("\n");
}
}
}
答案 1 :(得分:1)