在java中使用scanner错误:变量age可能尚未初始化

时间:2015-03-07 10:33:09

标签: java core

import java.io.*;
import java.util.Scanner;

public class Age {

public static void main(String []args) {

System.out.println("Enter Your Age: ");

int age;
Scanner in = new Scanner(System.in);
in.nextInt();

if(age<18)
{
   System.out.println("You Can't Vote");
}
else
{
    System.out.println("You Can Vote Now");
}
} 
}

编译器在编译时给出错误plz解决任何问题。

错误:变量年龄可能尚未初始化

2 个答案:

答案 0 :(得分:2)

年龄变量未初始化,初始化方式为:

age = in.nextInt();

import java.io.*;
import java.util.Scanner;

public class Age {

public static void main(String []args) {
int age;

System.out.println("Enter Your Age: ");

Scanner in = new Scanner(System.in);
age = in.nextInt();

if(age<18)
{
   System.out.println("You Can't Vote");
}
else
{
    System.out.println("You Can Vote Now");
}
} 
}

答案 1 :(得分:1)

编译器抱怨你没有初始化年龄而你正在进一步使用它(如果条件比较)。所以而不是:

in.nextInt();

使用

age = in.nextInt();