静态方法访问实例变量可改成:import java.io.*;public class Try
{
static BufferedReader cin
= new BufferedReader(new InputStreamReader(System.in));
private int n;
static int getNo()throws IOException
{
System.out.print("Give New Student no : ");
return cin.read();
} public static void main(String[] agro)throws IOException
{
Try test= new Try();
test.n = test.getNo();
System.out.println(test.n);
}}还可改成:import java.io.*;public class Try
{
static BufferedReader cin
= new BufferedReader(new InputStreamReader(System.in));
private String n;
static String getNo()throws IOException
{
System.out.print("Give New Student no : ");
return cin.readLine();
} public static void main(String[] agro)throws IOException
{
Try test= new Try();
test.n = test.getNo();
System.out.println(test.n);
}}
{
static BufferedReader cin
= new BufferedReader(new InputStreamReader(System.in));
private int n;
static int getNo()throws IOException
{
System.out.print("Give New Student no : ");
return cin.read();
} public static void main(String[] agro)throws IOException
{
Try test= new Try();
test.n = test.getNo();
System.out.println(test.n);
}}还可改成:import java.io.*;public class Try
{
static BufferedReader cin
= new BufferedReader(new InputStreamReader(System.in));
private String n;
static String getNo()throws IOException
{
System.out.print("Give New Student no : ");
return cin.readLine();
} public static void main(String[] agro)throws IOException
{
Try test= new Try();
test.n = test.getNo();
System.out.println(test.n);
}}
but the second one this correct. why?
输入200输出50是因为你上面用的是read()没读完,下面的readline()读完了;
输入的是interger的话,读取进来后把string转换成interger就是了。
{
static BufferedReader cin
= new BufferedReader(new InputStreamReader(System.in));
private int n;
public int getNo()throws IOException
{
System.out.print("Give New Student no : ");
n=Integer.parseInt(cin.readLine());
return n;
} public static void main(String[] agro)
{
Test test= new Test();
System.out.println(test.n);
}}