【发布时间】:2014-11-11 12:01:17
【问题描述】:
好的,所以我有一个全局数组作为“临时”类的一部分。我想从程序中的任何位置编辑该数组。那工作正常。但是,当我尝试使用这些值在我的“Cords”类中设置值时,我得到一个空异常错误。 我已经在我的代码中注释了它。知道为什么吗?
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
int n = 0;
for(int k = 0; k<4; k++){
Temp.tempValues[k] = 0;
}
boolean checkNums = false;
String coords = "";
while(n<1 || n>2000){
System.out.println("Enter number of lines");
n = inp.nextInt();
}
Cords[] lines = new Cords[n];
int proceed = 0;
inp.nextLine();
for(int i = 0; i<n; i++){
proceed = 0;
checkNums = false;
while((proceed != 3) || (checkNums == false)){
System.out.println("Enter line coordinates. "+(i+1));
coords = inp.nextLine();
proceed = checkSpaces(coords);
checkNums = rightNums(coords);
}
lines[i] = new Cords();
lines[i].setValues(Temp.tempValues[0], Temp.tempValues[1], Temp.tempValues[2], Temp.tempValues[3]);
}
}
public static int checkSpaces(String sent){
int spaces = 0;
for(int y = 0; y< sent.length(); y++){
if(sent.charAt(y)==' '){
spaces++;
}
}
return spaces;
}
public static boolean rightNums(String sent){
int z = 0;
int l = 0;
String num = "";
while(z<sent.length()){
while((z<sent.length())&&(sent.charAt(z) != ' ')){
num += sent.charAt(z);
z++;
}
if(Integer.parseInt(num) < 0 || Integer.parseInt(num) >=10000){
return false;
}else{
Temp.tempValues[l] = Integer.parseInt(num);
num = "";
z++;
l++;
}
}
return true;
}
public class Cords{
int x1 = 0;
int x2 = 0;
int y1 = 0;
int y2 = 0;
public void setValues(int xx1, int yy1, int xx2, int yy2){
x1 = xx1;
y1 = yy1;
x2 = xx2;
y2 = yy2;
}
}
public static class Temp{
static int[] tempValues = new int[4];
}
}
【问题讨论】:
-
一个不能有,单个文件中有两个公共类。
-
需要,因为我会在线发布代码,并且只能从一个文件中读取
-
尝试从该线类中删除“public”,然后尝试您的示例
标签: java arrays class global-variables