我有一个简单的小问题,我需要从scanner.scan读取变量“age”,用户输入一个数字。它一直告诉我初始化它,但为了做到这一点,我需要为变量提供一个整数,我不想这样做。我怎么能解决这个问题?
import java.util.*;
import java.io.*;
import java.util.Scanner;
public class Person
{
public static void main(String[]args)
{
int age;
Scanner scan = new Scanner(System.in);
System.out.println("Enter in your age.");
if (age < 18)
{
System.out.println("Youth is a beautiful thing.");
}
else
{
System.out.println("Age is just a state of mind.");
}
}
}
答案 0 :(得分:5)
您必须阅读age
。见下文。
import java.util.*;
import java.io.*;
import java.util.Scanner;
public class Person
{
public static void main(String[]args)
{
int age;
Scanner scan = new Scanner(System.in);
System.out.println("Enter in your age.");
age = scan.nextInt(); <---- **//This is what you are missing**
if (age < 18)
{
System.out.println("Youth is a beautiful thing.");
}
else
{
System.out.println("Age is just a state of mind.");
}
}
}
答案 1 :(得分:4)
(“输入你的年龄。”);
age = scan.nextInt();
答案 2 :(得分:3)
您没有在任何地方阅读age
。为此,请在初始化扫描后执行以下操作。
age = scan.nextInt();