gpt4 book ai didi

java - NumberformatException JFreeChart

转载 作者:行者123 更新时间:2023-12-01 10:54:19 25 4
gpt4 key购买 nike

输入文件(内容):

8dict, 3
9GAG, 2
RT, 7
The, 2
awkward, 2
co, 14
http, 11
https, 3
irrfan_k, 2
is, 2
my, 3
rainymornings, 3
t, 14
the, 2
this, 2
you, 3

我的代码是:

package pck;

import java.io.*;
import java.util.StringTokenizer;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;

public class PieChart_File
{
public static void main( String[ ] args )throws Exception
{
String mobilebrands[ ] = {
"8dict" ,
"9GAGs" ,
"RT" ,
"The" ,
"awkward",
"co",
"http",
"https",
"irrfan_k",
"is",
"my",
"rainymornings",
"t",
"the",
"this",
"you"
};

InputStream in = new FileInputStream( new File( "C:/temp/test.txt" ) );
BufferedReader reader = new BufferedReader(new InputStreamReader(in ) );
StringBuilder out = new StringBuilder();
String line;
DefaultPieDataset dataset = new DefaultPieDataset();

while (( line = reader.readLine() ) != null )
{
out.append( line );
}
StringTokenizer s = new StringTokenizer( out.toString(), "," );
int i=0;
while( s.hasMoreTokens( ) && ( mobilebrands [i] != null ) )
{

dataset.setValue(mobilebrands[i], Double.parseDouble( s.nextToken( ) ));
i++;
}
JFreeChart chart = ChartFactory.createPieChart(
"Repeated words", // chart title
dataset, // data
true, // include legend
true,
false);

int width = 560; /* Width of the image */
int height = 370; /* Height of the image */
File pieChart = new File( "pie_Chart.jpeg" );
ChartUtilities.saveChartAsJPEG( pieChart, chart, width, height);
}
}

当我尝试运行该文件时出现以下错误:

Exception in thread "main" java.lang.NumberFormatException: For input string: "8dict"
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at pck.PieChart_File.main(PieChart_File.java:48)

所有文件均已正确导入,仅出现此错误。输入文件路径也正确。请帮忙。

最佳答案

你试图将一个字符串解析为一个数值,但字符串当然无法解析,如果你解析它,“8dict”的值是多少?

您应该尝试仅解析每个字符串的第一个数值。

<小时/>

使用正则表达式的解决方案

替换

dataset.setValue(mobilebrands[i], Double.parseDouble( s.nextToken( ) ));

Pattern p = Pattern.compile("\\d*"); // Finds the digits in a given String
Matcher m = p.matcher(s.nextToken());
m.find();
dataset.setValue(mobilebrands[i], Double.parseDouble(m.group(0)));

关于java - NumberformatException JFreeChart,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33711867/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com