I'm adjusting a class in my Java code to account for another int, here is the new one:
class Card {
private String name;
private int price;
private int profit;
public Card(String name, int price, int profit) {
this.name = name;
this.price = price;
this.profit = profit;
}
public String getName() {
return name;
}
public int getPrice() {
return price;
}
public int getProfit() {
return profit;
}
}
initislly public Card only read String name and int price, and had profit = price to just more simpler cases, how do I adjust this snippet of the code for all to go well? I've been stuck here for quite some time:
private static List<Problem> readProblems(String priceFilePath) throws IOException {
List<Problem> problems = new ArrayList<>();
Scanner scanner = new Scanner(new File(priceFilePath));
while (scanner.hasNextLine()) {
int numCards = scanner.nextInt();
int maxMoney = scanner.nextInt();
scanner.nextLine();
List<Card> cards = new ArrayList<>();
for (int i = 0; i < numCards; i++) {
String[] cardInfo = scanner.nextLine().split(" ");
String cardName = cardInfo[0];
int cardPrice = Integer.parseInt(cardInfo[1]);
cards.add(new Card(cardName, cardPrice));
}
problems.add(new Problem(cards, maxMoney));
}
scanner.close();
return problems;
}
I tried this new snippet:
private static List<Problem> readProblems(String priceFilePath) throws IOException {
List<Problem> problems = new ArrayList<>();
Scanner scanner = new Scanner(new File(priceFilePath));
while (scanner.hasNextLine()) {
int numCards = scanner.nextInt();
int maxMoney = scanner.nextInt();
scanner.nextLine(); // Move to the next line
List<Card> cards = new ArrayList<>();
for (int i = 0; i < numCards; i++) {
String[] cardInfo = scanner.nextLine().split(" ");
String cardName = cardInfo[0];
int cardPrice = Integer.parseInt(cardInfo[1]);
int cardProfit = Integer.parseInt(cardInfo[2]); // Add profit from input
cards.add(new Card(cardName, cardPrice, cardProfit));
}
problems.add(new Problem(cards, maxMoney));
}
scanner.close();
return problems;
}
then i got this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at Algo.readProblems(Algo.java:53)
at Algo.main(Algo.java:15)
tried debugging more by adding some error handling and a print statement to get the stack trace in case of an exception. Idea being it will help identify where the issue might be occurring, but to no avail
would appreciate any help on this