对于我的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;
}
答案 0 :(得分:6)
为什么我收到错误“变量天数可能尚未初始化”
由于:
final int days;
应该是:
int days = 0;
为什么?
month
switch
的所有可能值
String month
,遮蔽参数int month
Scanner
未使用此外,如果您不打破案例块,则会执行下一个案例块,这意味着您可以执行以下操作:
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);
}
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)
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;
作为参数提供给函数。
您无法在所有控制路径上初始化month
:days
中的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
的重新声明,您就是黄金。