[英]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 的新手,我還在學習它的概念。 我認為這可能是變量初始化范圍的問題。 我期待着任何能解決我問題的人的指導。 謝謝
null 值來自不初始化值的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]。
問題出在 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 名稱以大寫字母開頭。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.