2011-11-30 41 views
2

我正在編寫一個非常簡單的類的程序。所有它需要我打印成績表,並能夠輸入3條信息(這裏用字符串studentName, idNumberassignmentTitle表示)。成績表必須存儲在一個字符串中。好吧,這對我來說看起來好像它應該工作,但無論出於什麼原因,輸出studentName, idNumberassignmentTitle應該出現在空值輸出。非常簡單的問題,我敢肯定,有什麼想法?這是我的代碼。String返回空值的Java問題,儘管使用Scanner類輸入數據

import java.util.Scanner; 

class GradingForm 
{ 
static String studentName; 
static String idNumber; 
static String assignmentTitle; 
    static String gradeSheet = "********************************* \n\n" + 
           assignmentTitle + "\n\n" + 
           studentName + " " + idNumber + "\n\n" + 
           "Grade Summary:\n\n" + 
           "Program Correctness:  Quality of Style:\n" + 
           "Late Deduction:    Overall Score:\n" + 
           "Comments:"; 
public static void gradeFormValues() 
{ 
    Scanner inData; 
    inData = new Scanner(System.in); 
    System.out.println("Enter student's name: "); 
    studentName = inData.nextLine(); 
    System.out.println("Enter student ID number: "); 
    idNumber = inData.nextLine(); 
    System.out.println("Enter Assignment title: "); 
    assignmentTitle = inData.nextLine(); 
} 
public static void printGradeSheet() 
{ 
    System.out.println(gradeSheet); 
} 

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

回答

4

你的問題是,你將值分配給他們之前使用這些變量:

static String gradeSheet = "********************************* \n\n" + 
           assignmentTitle + "\n\n" + 
           studentName + " " + idNumber + "\n\n" + 
           "Grade Summary:\n\n" + 
           "Program Correctness:  Quality of Style:\n" + 
           "Late Deduction:    Overall Score:\n" + 
           "Comments:"; 

你需要建立之後,纔給它們賦值例如字符串:

public static void printGradeSheet() 
{ 
    gradeSheet = "********************************* \n\n" + 
     assignmentTitle + "\n\n" + 
     studentName + " " + idNumber + "\n\n" + 
     "Grade Summary:\n\n" + 
     "Program Correctness:  Quality of Style:\n" + 
     "Late Deduction:    Overall Score:\n" + 
     "Comments:"; 
    System.out.println(gradeSheet); 
} 
+0

謝謝....計算它會很簡單 – Marq

1

你的問題是你的類是如何實例化的。這是發生了什麼:

studentName is set to null 

idNumber is set to null 

assignmentTitle is set to null 

gradeSheet is set using the current values of studentName etc (null). 

後您閱讀您的數據和設置的變量,但是這並不能改變gradeSheet已經設置的值。

0

你是問題是你初始化變量的順序。

當初始化gradeSheet(與static String gradeSheet =...線),assignmentTitlestudentNameidNumbernull

在完成接受來自用戶的輸入之後,您應該改爲初始化gradeSheet