英文:
Need the program to find space and extract variables to left and right of space and print them out. How do I do it?
问题
我正在编写一个程序,用户在同一行上输入他们的名字和姓氏,名字和姓氏之间有一个空格。然后程序将检测到这个空格,并将名字和姓氏提取到不同的变量中以便打印输出。
示例:假设用户在一行中输入了"simon hall",名字和姓氏之间有空格,我希望输出如下:
名字:Simon
姓氏:Hall
我的代码(目前几乎没用):(输入/输出如下)
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("在一行上输入名字和姓氏(包括空格):");
String fullName = scanner.next();
String result = fullName;
result = result.split(" ")[0];
System.out.println(result);
}
}
**输入:zayaan khan(一行上输入)
输出:
zayaan**(我想要打印:
名字:Zayaan
姓氏:Khan)
谢谢
英文:
I am writing a program where the user inputs their forename and surname with space inbetween all on one line. The program will then detect the space and extract the forename and surname into different variables to be printed out.
Example: Say a user entered "simon hall" on one line There is space inbetween and I want it outpuuted like this:
Forename: Simon
Surname: Hall
My code(pretty much useless right now): (Input/Output Below)
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input forename and surname on one line (space included)");
String fullName = scanner.next();
String result = fullName;
result = result.split(" ") [0];
System.out.println(result);
}
}
**Input: zayaan khan (on one line)
Output:
zayaan** (I want to print
Forename: Zayaan
Surname: Khan )
Thank you
答案1
得分: 2
获取逐行输入
String fullName = scanner.nextLine(); // 逐行输入获取器
根据空格拆分字符串并将其存储在字符串数组中,然后可以通过使用该数组的索引访问它
String result[] = fullName.split(" "); // 拆分字符串
System.out.println("名字:" + result[0] + " 姓氏:" + result[1]); // 打印结果
英文:
Get the Input as line by line
String fullName = scanner.nextLine(); // line by line input getter
Split the string based on space and store it in String Array and then you can access it by using indices of that array
String result[] = fullName.split(" "); // spliting the string
System.out.println("Forename: "+result[0]+" Surname: "+result[1]);// print it
答案2
得分: 1
使用正则表达式:
public class Main {
public static void main(String[] args) {
final Pattern pattern = Pattern.compile("(\\S+)\\s+(\\S+)");
final Scanner scanner = new Scanner(System.in);
final Matcher matcher = pattern.matcher(scanner.nextLine());
if (matcher.find())
System.out.println(String.format("名字: %s,姓氏: %s", matcher.group(1), matcher.group(2)));
}
}
英文:
Using regex:
public class Main {
public static void main(String[] args) {
final Pattern pattern = Pattern.compile("(\\S+)\\s+(\\S+)");
final Scanner scanner = new Scanner(System.in);
final Matcher matcher = pattern.matcher(scanner.nextLine());
if (matcher.find())
System.out.println(String.format("Forename: %s, Surname: %s", matcher.group(1), matcher.group(2)));
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论