为什么我的 java 程序在输出中打印 "null" 作为字符串,当我通过方法将它作为输入时?

why is my java program printing "null" in output for a string when I took it as an input through a method?

package com.company;

import java.util.Scanner;

class fields{
    Scanner sc = new Scanner(System.in);
    String fn;
    String ln;
    String em;
    String phn;
    String country;
    String city;
    public fields() {
        System.out.println("\n                    ~~~ FORM ~~~\n");
        System.out.print("First Name: ");
        input(fn);
        System.out.print("Last Name: ");
        input(ln);
        System.out.print("Email: ");
        input(em);
        System.out.print("Phone number: ");
        input(phn);
        System.out.print("Country: ");
        input(country);
        System.out.print("City: ");

        input(city);
    }
    public void input(String x){
        x = sc.nextLine();
    }
    public void output(){
        System.out.println("The user's name is: " + fn + " " + ln + "\nEmail: " + em + "\nPhone Number: " + phn + ",\nand lives in: " + city + ", " + country);
    }
}

public class Form {
    public static void main(String[] args) {

        fields obj = new fields();
        System.out.println("\n                    ~~~ OUTPUT ~~~\n");
        obj.output();

    }
}

我是 java 的新手。我仍在学习它的概念。我认为这可能是变量初始化范围的问题。我期待着任何能解决我问题的人的指导。谢谢

空值来自 input 不初始化值的方法,其中一种正确的形式如下所示

public class Fields {
Scanner sc = new Scanner(System.in);
private String fn;
private String ln;
private String em;
private String phn;
private String country;
private String city;

public Fields() {
    System.out.println("\n                    ~~~ FORM ~~~\n");
    System.out.print("First Name: ");
    this.fn = sc.nextLine();
    System.out.print("Last Name: ");
    this.ln = sc.nextLine();
    System.out.print("Email: ");
    this.em = sc.nextLine();
    System.out.print("Phone number: ");
    this.phn = sc.nextLine();
    System.out.print("Country: ");
    this.country = sc.nextLine();
    System.out.print("City: ");
    this.city = sc.nextLine();
}

public void output() {
    System.out.println("The user's name is: " + fn + " " +
            ln + "\nEmail: " + em + "\nPhone Number: " + phn + ",\nand lives in: " + city + ", " + country);
}}

更多请尊重class命名的语言[约定][1]。

[1]: https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html#:~:text=Class%20names%20should%20be%20nouns,such%20as%20URL%20or%20HTML).

问题出在 input() 方法上。此方法接收一个字符串参数。但请记住,java 中的参数是按值传递的,特别是字符串是不可变对象,因此当您调用 input() 并将字符串变量作为参数传递时,会复制该变量。因此,您在 input() 方法内部修改的值是发送的参数的副本。这就是为什么永远不会初始化 fn、ln、em、phn、country、city 变量的原因。

另一种输入法实现如下:

public String input(){
    return sc.nextLine();
}

并调用它如下例:

:
System.out.print("Last Name: ");
ln = input();
:

这只是一个有趣的示例,用于理解如何在 java 中传递参数,因为似乎没有必要使用仅从标准输入执行读取的方法。

最后的评论:作为惯例,java 中的 Class 个名称以大写字母开头。