变量可能尚未初始化

时间:2016-02-18 15:23:52

标签: java variables initialization

对于我的Comp Sci课程,我必须创建一个程序来查找给定月份(1-12)的天数,你知道为什么我收到错误“变量天数可能没有被初始化“当试图从交换机返回int”days“时?这是代码:

public static int getNumberofDays(int month,int year)
   {
      // Imports the required Scanner
      Scanner kbd = new Scanner(System.in);

      final String month;
      final int days;
      switch (month) {
         case 1:  days = 31;
            break;
         case 2:  if ((year % 4 == 0) && year % 100 != 0)
                  {
                     days = 29;
                  }
                  else if ((year % 4 == 0) && (year % 100 == 0) && (year % 400 == 0))
                  {
                     days = 29;
                  }
                  else
                  {
                     days = 28;
                  }
            break;
         case 3:  days = 31;
            break;
         case 4:  days = 30;
            break;
         case 5:  days = 30;
            break;
         case 6:  days = 31;
            break;
         case 7:  days = 31;
            break;
         case 8:  days = 31;
            break;
         case 9:  days = 30;
            break;
         case 10: days = 31;
            break;
         case 11: days = 30;
            break;
         case 12: days = 31;
            break;
         default: month = "invalid";
            break;
      }
      return days;
   }

4 个答案:

答案 0 :(得分:6)

  

为什么我收到错误“变量天数可能尚未初始化”

由于:

final int days;

应该是:

int days = 0;

为什么?

  • 方法中的变量应该初始化
  • 无法修改最终变量。

其他错误:

  • 您未涵盖month
  • switch的所有可能值
  • 您定义String month,遮蔽参数int month
  • Scanner未使用
  • 更多...... XD

我的解决方案

此外,如果您不打破案例块,则会执行下一个案例块,这意味着您可以执行以下操作:

public static int getNumberofDays(int month,int year) {
    switch (month) {
       case 1:  
       case 3:  
       case 6:  
       case 7:  
       case 8:
       case 10: 
       case 12: 
             days = 31;
          break;
       case 4:
       case 5:
       case 9:
       case 11: 
             days = 30;
          break;
       case 2:  
          if ((year % 4 == 0) && year % 100 != 0)
          {
             days = 29;
          }
          else if ((year % 4 == 0) && (year % 100 == 0) && (year % 400 == 0))
          {
             days = 29;
          }
          else
          {
             days = 28;
          }
          break;
       default: days = -1;
          break;
    }
    return days;
}

我的解决方案:Calendar!:

public static int getNumberofDays(int month,int year)
{
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.MONTH, month);
    cal.set(Calendar.YEAR, year);
    return cal.getActualMaximum(Calendar.DAY_OF_MONTH); 
}

Neil解决方案:Java-8

public static int getNumberofDays(int month,int year)
{
    YearMonth yearMonthObject = YearMonth.of(year, month); 
    return yearMonthObject.lengthOfMonth();
}

答案 1 :(得分:1)

并非所有可能的代码路径都会为days变量赋值。确切地说,默认块没有。

default: month = "invalid";
           break;

如果您将其更改为

default: month = "invalid";
         days=0
           break;

警告消失。

我的其他问题是:

  • 为什么要定义一个字符串月份,从而影响参数月份?
  • 什么是扫描仪?
  • 为什么在默认区块中为月份分配无效,您永远不会将其返回。

答案 2 :(得分:0)

  1. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.IO; using System.Data.SqlClient; using System.Data.OleDb; public partial class CSV : System.Web.UI.Page { SqlConnection conn = new SqlConnection("Data Source=INHRPSM1D7C;Initial Catalog=HRSS;Integrated Security=True"); DataSet ds; DataTable Dt; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindGrid(); } } private void ImporttoDatatable() { try { if (FlUploadcsv.HasFile) { string FileName = FlUploadcsv.FileName; string path = string.Concat(Server.MapPath("~/Document/" + FlUploadcsv.FileName)); FlUploadcsv.PostedFile.SaveAs(path); OleDbConnection OleDbcon = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;"); OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", OleDbcon); OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(cmd); ds = new DataSet(); objAdapter1.Fill(ds); Dt = ds.Tables[0]; } } catch (Exception ex) { } } private void CheckData() { try { for (int i = 0; i < Dt.Rows.Count; i++) { if (Dt.Rows[i][0].ToString() == "") { int RowNo = i + 2; ScriptManager.RegisterStartupScript(Page, Page.GetType(), "InvalidArgs", "alert('Please enter Employee ID in row " + RowNo + "');", true); return; } } for (int i = 0; i < Dt.Rows.Count; i++) { if (Dt.Rows[i][1].ToString() == "") { int RowNo = i + 2; ScriptManager.RegisterStartupScript(Page, Page.GetType(), "InvalidArgs", "alert('Please enter Name in row " + RowNo + "');", true); return; } } for (int i = 0; i < Dt.Rows.Count; i++) { if (Dt.Rows[i][2].ToString() == "") { int RowNo = i + 2; ScriptManager.RegisterStartupScript(Page, Page.GetType(), "InvalidArgs", "alert('Please enter Designation in row " + RowNo + "');", true); return; } } for (int i = 0; i < Dt.Rows.Count; i++) { string date = DateTime.Parse(Dt.Rows[i][3].ToString()).ToString("dd/MM/yyyy"); if (!ValidateDate(date)) { int RowNo = i + 2; ScriptManager.RegisterStartupScript(Page, Page.GetType(), "InvalidArgs", "alert('Wrong Date format in row " + RowNo + "');", true); return; } } for (int i = 0; i < Dt.Rows.Count; i++) { if (Dt.Rows[i][4].ToString() == "") { int RowNo = i + 2; ScriptManager.RegisterStartupScript(Page, Page.GetType(), "InvalidArgs", "alert('Please Enter City in Row " + RowNo + "');", true); return; } } } catch (Exception ex) { } } private bool ValidateDate(string date) { try { string[] dateParts = date.Split('/'); DateTime testDate = new DateTime(Convert.ToInt32(dateParts[2]), Convert.ToInt32(dateParts[1]), Convert.ToInt32(dateParts[0])); return true; } catch { return false; } } private void InsertData() { for (int i = 0; i < Dt.Rows.Count; i++) { DataRow row = Dt.Rows[i]; int columnCount = Dt.Columns.Count; string[] columns = new string[columnCount]; for (int j = 0; j < columnCount; j++) { columns[j] = row[j].ToString(); } conn.Open(); string sql = "INSERT INTO EmpImport(EmployeeID,Name,Designation,DateOfBirth,City)"; sql += "VALUES('" + columns[0] + "','" + columns[1] + "','" + columns[2] + "',Convert(varchar(10),'" + columns[3] + "',103),'" + columns[4] + "')"; SqlCommand cmd = new SqlCommand(sql, conn); cmd.ExecuteNonQuery(); conn.Close(); } } protected void btnIpload_Click(object sender, EventArgs e) { ImporttoDatatable(); CheckData(); InsertData(); BindGrid(); } private void BindGrid() { DataSet ds = new DataSet(); conn.Open(); string cmdstr = "Select * from EmpImport"; SqlDataAdapter adp = new SqlDataAdapter(cmdstr, conn); adp.Fill(ds); gvEmployee.DataSource = ds; gvEmployee.DataBind(); ds.Dispose(); conn.Close(); } } 无效,因为final String month;作为参数提供给函数。

  2. 您无法在所有控制路径上初始化monthdays中的default阻止无法执行此操作。这是Java的一个很好的功能,因为它可以帮助您实现程序稳定性。没有比编译器告诉你该怎么做更好的了。 不要通过撰写switch强制解决问题;而是在final int days = 0;块中为其分配值。

答案 3 :(得分:-2)

days = 0;添加到您的默认案例中:

default: 
    month = "invalid";
    days = 0;
        break;

在尝试返回之前,必须在代码路径中的某处给days一个值。您还应将final int days;替换为int days;。 此外,您不能拥有final String month因为month作为参数传递给函数。只需删除month的重新声明,您就是黄金。