Java 提示用户在一行中输入姓名并将其打印为“Last, First”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26808929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 03:19:33  来源:igfitidea点击:

Prompt user to enter name on one line and print it out as "Last, First"

javajava.util.scanneruser-input

提问by Sarah

No one in our entire lab was able to get this problem, so we have to do it for homework. We are to prompt the user to enter their first and last name on one line. The main method is supposed to handle all println statements and should print the name as Last, First.

我们整个实验室中没有人能够解决这个问题,所以我们必须做功课。我们将提示用户在一行中输入他们的名字和姓氏。main 方法应该处理所有 println 语句,并且应该将名称打印为 Last, First。

line 26 states "cannot find symbol."
line 36 states "not a statement. ';' expected.
line 39 states unreachable statement.

I have been playing with this code for an hour and have just about given up. Any help?

我一直在玩这个代码一个小时,几乎放弃了。有什么帮助吗?

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lab11;

import java.util.Scanner;

/**
 *
 * @author xxxxxx
 */
public class Lab11 {
    public static void main(String[] args) {
        System.out.println("Enter your name: ");
        Scanner user_input=new Scanner(System.in);

        changeNameFormat();
        System.out.println(lastName+", " + firstName);

        System.out.println("Enter a word. ");
        palindrome();
    }

    public static String changeNameFormat() {
        String firstName, lastName;
        firstName, lastName = user_input.nextLine;
        return lastName;
        return firstName;
    }

采纳答案by user1274820

Here is a list of steps you need to do:

以下是您需要执行的步骤列表:

Get the input [Will be Example: "John Smith"]

获取输入 [将是示例:“John Smith”]

Split it into two pieces [There are several ways to do this]

把它分成两部分[有几种方法可以做到这一点]

firstName = input.substring(0, input.indexOf(" "));
lastName = input.substring(input.indexOf(" ")+1, input.length());

substring()returns a portion of the string.

substring()返回字符串的一部分。

indexOf()finds a specific character in the string.

indexOf()在字符串中查找特定字符。

It takes a start value and an end value.

它需要一个起始值和一个结束值。

In this case, we start at the beginning, and end when we find a space.

在这种情况下,我们从头开始,当我们找到一个空格时结束。

To get the last name, we start where we find a space, and end at the end of the string.

要获取姓氏,我们从找到空格的地方开始,并在字符串的末尾结束。

You can also combine this with the .trim()method that removes whitespace from the beginning/end of strings.

您还可以将其与从字符串的开头/结尾删除空格的.trim()方法结合使用。

Finally, we return the concatenated value:

最后,我们返回连接后的值:

return lastName + ", " + firstName;

Complete code:

完整代码:

package lab11;
import java.util.Scanner;
public class Lab11 {
    public static Scanner user_input;
    public static void main(String[] args) {
        user_input = new Scanner(System.in);
        System.out.print("Enter your name: ");
        System.out.println(changeNameFormat(user_input.nextLine()));
    }
    public static String changeNameFormat(String input) { //Pass a name
        String firstName, lastName;
        firstName = input.substring(0, input.indexOf(" "));
        lastName = input.substring(input.indexOf(" ")+1, input.length());
        return lastName + ", " + firstName;
    }
}

Tested on: http://www.compileonline.com/compile_java_online.php

测试:http: //www.compileonline.com/compile_java_online.php

One final thing. It's a good convention to make your methods work as they are named.

最后一件事。使您的方法按命名方式工作是一个很好的约定。

Since yours is called "changeNameFormat()", we should probably pass it the name we want to change.

由于您的名称为“changeNameFormat()”,因此我们可能应该将要更改的名称传递给它。

Then in our main, we can get the input, or even pass it as a parameter.

然后在我们的 main 中,我们可以获取输入,甚至将其作为参数传递。

回答by chiastic-security

The "cannot find symbol" will be palindrome(), which is a method call but you haven't defined it anywhere (and it doesn't seem relevant to the problem). You'll also get this on the line

“找不到符号”将是palindrome(),这是一个方法调用,但您尚未在任何地方定义它(并且它似乎与问题无关)。你也会得到这个

System.out.println(lastName+", " + firstName);

because at that point you haven't declared lastNameor firstName.

因为那时你还没有声明lastNameor firstName

The "not a statement" is the line firstName, lastName = ..., which is not valid syntax in Java (though it is in some languages, where you can assign to two variables at once). You need to find a way to split the input up into two parts, and assign one part to firstNameand one part to lastName; but as it stands, this line isn't meaningful Java.

“not a statement”是 line firstName, lastName = ...,它在 Java 中不是有效的语法(尽管在某些语言中,您可以一次分配给两个变量)。您需要找到一种方法将输入分成两部分,并将一部分分配给 ,一部分分配firstNamelastName;但就目前而言,这一行对 Java 没有意义。

The "unreachable code" is the return firstName. The previous returnline ends execution of the method, so your code won't ever get to the return firstNamestatement. You're supposed to be printing things, not returning them.

“无法访问的代码”是return firstName. 上return一行结束了方法的执行,因此您的代码永远不会到达该return firstName语句。你应该打印东西,而不是退回它们。



In this case, all the errors reported are genuine. But in general, if you have lots of errors in the first part of your code, then the compiler won't reliably identify later errors, because it won't manage to parse the whole file. So sometimes, you'll find you fix a syntax error in the first few lines, and that seems to create a problem later on. It isn't really creating a new problem, it's just that the compiler wasn't previously able to find it.

在这种情况下,报告的所有错误都是真实的。但总的来说,如果您的代码的第一部分有很多错误,那么编译器将无法可靠地识别以后的错误,因为它无法解析整个文件。所以有时,你会发现你在前几行中修复了一个语法错误,这似乎会在以后产生问题。它并没有真正产生新问题,只是编译器以前无法找到它。

回答by Elliott Frisch

Java does not support that syntax. Instead, you will need to use something like String.split(String)and you might combine that with formatted output like

Java 不支持该语法。相反,您将需要使用类似的东西,String.split(String)并且可以将其与格式化的输出相结合,例如

Scanner input = new Scanner(System.in);
System.out.println("Enter your name: ");
if (input.hasNextLine()) {
    String line = input.nextLine();
    String[] names = line.split("\s+"); // <-- globs consecutive white-space
    if (names.length > 1) {
        String firstName = names[0];                // <-- indexes start at 0
        String lastName = names[names.length - 1];  // <-- so subtract 1!
        System.out.printf("%s, %s%n", lastName, firstName);
    } else {
        System.out.println("Unknown: " + line);
    }
}

回答by Muhammad

I have the following solution for your problem, the first name and last name must be separated using a space

对于您的问题,我有以下解决方案,名字和姓氏必须使用空格分隔

import java.util.Scanner;

public class LastFirst {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please Enter your name");
        String name = scanner.nextLine();
        name = name.substring(name.indexOf(" ")+1, name.length())+" "+name.substring(0, name.indexOf(" "));
        System.out.println(name);
    }
}