簡體   English   中英

掃描儀輸入字符串顯示為空Java

[英]Scanner input string appearing as null java

我的代碼在這里:

package test1;
import java.util.*;
public class Test1 {
public static String input;

public Test1(){
Scanner answer = new Scanner(System.in);
String test = answer.next();
}
public static void initializeConstructor(){
 Test1 input = new Test1();

}

   public static void begin () {
   System.out.println("type:");

  initializeConstructor();

   System.out.println(input);

}

public static void main(String[] args) {
    begin();
}

}

我真的是學習Java的新手,我的想法是可以調用構造函數來啟動掃描程序,它會吐回來我剛才輸入的內容。 我這樣做是為了讓我能更多地了解Java中的構造函數。 但是,當我運行以下程序時,它只會給我“ null”。 就像我說的那樣,我很新奇,所以這可能是一個愚蠢的問題,但是任何回應都將不勝感激。 先感謝您。

由於inputnull (從未分配),因此請更改

String test = answer.next();

input = answer.next();

這樣您的代碼就會起作用。 但是inputstatic (不應在真實代碼中輸入,如果在構造函數中進行設置,則不應input )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM