我正在制作一个应用程序,用各种颜色中最有价值的宝石组织魔兽世界宝石制作拍卖数据。为此,我尝试将json数据库解析为数组 - 我知道像我们这样的gson api这样做很简单但是因为这是一个入门级java类的项目我的教授我已经声明我应该使用我们在课堂上学到的东西来导入数据,据说我已经得到以下代码来解析json数据并将其打印在屏幕上(仍然在解析为数组){{3}并包含我到目前为止的代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class jcFormat {
public static void main(String[] args) {
try {
File f = new File("c:\\ProgramData\\jcUtil\\data.json");
Scanner sc = new Scanner(f);
List<Auction> ahdata = new ArrayList<Auction>();
sc.nextLine();//eats line
sc.nextLine();//eats line
sc.nextLine();//eats line
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] details = line.split(",");
//get item as string
String itemz = details[1];
itemz = itemz.substring(7, itemz.length());
//convert itemz string to item int
int item = Integer.parseInt(itemz);
//get buyout as string
String buyoutz = details[4];
buyoutz = buyoutz.substring(9, buyoutz.length());
//convert buyoutz string to buyout int
int buyout = Integer.parseInt(buyoutz);
//get quantity as string
String quantityz = details[5];
quantityz = quantityz.substring(11, quantityz.length());
//convert quantityz string to quantity int
int quantity = Integer.parseInt(quantityz);
Auction a = new Auction(item, buyout, quantity);
ahdata.add(a);
}
for (Auction a : ahdata) {
System.out.println(a.toString());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
class Auction {
private int item;
private int buyout;
private int quantity;
public Auction(int item, int buyout, int quantity) {
this.item = item;
this.buyout = buyout;
this.quantity = quantity;
}
/**
* @return the item
*/
public int getItem() {
return item;
}
/**
* @param item the item to set
*/
public void setItem(int item) {
this.item = item;
}
/**
* @param buyout the buyout to set
*/
public void setBuyout(int buyout) {
this.buyout = buyout;
}
/**
* @return the buyout
*/
public int getBuyout() {
return buyout;
}
/**
* @return the quantity
*/
public int getQuantity() {
return quantity;
}
/**
* @param quantity the quantity to set
*/
public void setQuantity(int quantity) {
this.quantity = quantity;
}
@Override
public String toString() {
return this.item + "\t" + this.buyout + "\t" + this.quantity;
}
}
我遇到的问题是这个错误:
线程中的异常&#34; main&#34; java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:-9 at java.lang.String.substring(String.java:1958) 在jcutil.jcFormat.main(jcFormat.java:40) Java结果:1
如果我在前10行data.json上测试我的代码,它运行得很好,所以我试图弄清哪些行引起了问题,并且作为java的新人我的调试技巧并不是很好,所以任何帮助搞清楚为什么我会收到这个错误将不胜感激。
答案 0 :(得分:0)
假设你正在使用eclipse在行上放置一个断点
buyoutz = buyoutz.substring(9, buyoutz.length());
并以调试模式运行应用程序,这将允许您查看问题所在。