Java 使用二维图形的饼图在使用数组时遇到问题
这是我的第二个文件Java 使用二维图形的饼图在使用数组时遇到问题,java,Java,这是我的第二个文件 import javax.swing.*; public class Main { public static void main(String[] args) throws FileNotFoundException { File file = new File(args[0]); Scanner input = new Scanner(file); int i = 0; String names[] = null; int sl
import javax.swing.*;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
File file = new File(args[0]);
Scanner input = new Scanner(file);
int i = 0;
String names[] = null;
int slices[] = {};
while (input.hasNext()) {
names[i] = input.next();
slices[i] = input.nextInt();
i++;
}
JFrame f = new JFrame("Pie chart");
f.setSize(600, 350);
f.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
f.add(new PieChart());
f.setVisible(true);
}
}
我当前的问题是它不接受输入;放入名称[]和切片[]的数组中。我怎样才能解决这个问题
while(input.hasNext()){
可能应该是while(input.hasNextLine()){
然后,您可能需要使用input.nextLine()
来获取实际文本,并使用第二个扫描仪来解析单独的行
我正在尝试将文本文件读入两个单独的数组。我希望一个数组保存名称,然后一个数组保存值。然后我希望能够从第二个文件访问数组中的值
您应该将数组传递给PieChart
类,可能是通过构造函数
在进行任何自定义绘制之前,还应该调用super.paintComponent
它给了我一个NullPointerException错误,它说它在第16行,即“names[i]=input.next();”
名称
从未初始化过(isnull
)
数组不是动态的,所以除非您事先知道有多少行,否则管理起来并不容易
在您的情况下,假设文件不变,您可以使用以下内容
String names[] = null;
int slices[] = {};
另一种选择是使用某种类型的列表
,或映射
,它们是动态的,因此您不需要事先知道可能需要多少元素
<>请参阅更多细节 ,如果您在开始添加项目的大小(如它将有20个索引)之前,您应该使用一个数组。在这里,您似乎直到运行时才知道。因此,数组将不是最佳的数据结构。
ArrayList name=new ArrayList();
而(…){
name.add(input.nextLine());
}
System.out.print(names.get(3))//打印第四个名称
您需要先将非空数组分配给name
,然后才能将值分配给它的元素;否则您将得到观察到的NullPointerException
但是,您不知道需要多少元素,因此应该使用可调整大小的数据结构,如ArrayList
如果将{}
赋值给名称
,就像对切片
赋值一样,您会得到一个ArrayIndexOutOfBoundsException
,因为它没有元素,但您正试图将一个值赋值给第0个。我当前的问题是它不接受输入。next()它在做什么?@AndyTurner它给了我一个NullPointerException错误,它说它在第16行,即“names[i]=input.next();”请不要使用原始类型。
swallow 10
magpie 5
fairywren 7
osprey 2
fantail 3
String names[] = null;
int slices[] = {};
String names[] = new String[5];
int slices[] = new int[5];
ArrayList<String> names = new ArrayList()<String>;
while(...){
names.add(input.nextLine());
}
System.out.print(names.get(3)) //prints the 4th name
String names[] = null;