2016-09-16 62 views
1

初学者编码器在这里。我试图区分何时用户输入一个值并且没有输入值。区分“空白输入”和零值作为实际输入

当用户没有输入指定值时,整数变量= 0。

但是,如果用户输入0作为他们的变量,我需要它是不同的。

if(exam1Input == 0){ 
    exam1Per = 0;} 
if(exam2Input == 0){ 
    exam2Per = 0;} 
if(finalExamInput == 0){ 
    finalExamPer = 0;} 
if(labsInput == 0){ 
    labsPer = 0;} 
if(projectsInput == 0){ 
    projectsPer = 0;} 
if(quizzesInput == 0){ 
    quizzesPer = 0;} 
if(attendanceInput == 0){ 
    attendancePer = 0;} 

我这样做是多分支if语句的百分比等级权重值变相零如果输入的是零(即没有输入的话)。

但是,我遇到了一个问题,当用户输入“0”作为他们的实际等级。我不能让百分比权重为0,我仍然需要它是一定的等级百分比。

例如如果他们的测试平均值为0,我仍然需要根据等级0计算他们的百分比。

那么,我怎么能更具体并能够区分缺少的输入和实际输入?

我希望零作为实际成绩而不是丢失的输入。

+0

你用什么代码检索'int'? – 4castle

+1

为什么不使用-1作为默认值? – Shadov

+0

太糟糕了!你提出的代码非常糟糕!它的圈复杂性令人难以置信,没有理由!请改变你的代码的逻辑。 – acornagl

回答

1

一个简单的解决方案是使用一个不同的默认值,该默认值将是来自用户的无效输入。例如:

static final int NO_INPUT = -1; 

int exam1Input = NO_INPUT; 

/**Prompt the user for input somewhere around here*/ 

if(exam1Input == 0) ... 

现在,如果用户明确地将其设置为0,则exam1Input将仅为0,否则为-1。

1

或者,使用OptionalInt而不是int。这种情况是他们的目的。

OptionalInt input = OptionalInt.empty(); 
// input = Optional.of(someValue); if set 
If (input.isPresent()) { 
    int i = input.getAsInt(); 
    // use the value 
}