Categories

Java中变量的初始化

Java中定义的变量在初始化前必须初始化,在对对象数组初始化时尤其需要注意

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.util.Scanner;
 
class Student
{
	String name;
	int gpa;
}
 
public class Test
{
	public static void main(String[] args)
	{
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		Student[] s = new Student[n];
 
		for (int i = 0; i != n; ++i)
		{
			s[i] = new Student(); //在smallwood师兄的帮助下才改正了这个Bug,最开始我没有写这一行,运行时总是抛出异常。
			s[i].name = in.next();
			s[i].gpa = in.nextInt();
		}
	}
}

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

  

  

  

*