-3

We get the following error:

java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)

For this code:

Scanner readyBoi;
ArrayList<Item> shopStock = new ArrayList<Item>();

public Shop(String stock){
    this.readyBoi = new Scanner(stock);
    while(readyBoi.hasNextLine()){
        String temp = readyBoi.nextLine();
        Tycoon.out(temp);
        String tempArray[] = temp.split("\t", 5);
        Item i = new Item(
            Integer.parseInt(tempArray[0]),
            Integer.parseInt(tempArray[1]),
            Integer.parseInt(tempArray[2]),
            tempArray[3],
            tempArray[4]
        );
        this.shopStock.add(i);
    }
}

This is the referenced item declaration:

Item(int id, int price, int generation, String name, String desc)

The code compiles correctly, but produces a runtime error.

  • 4
    OK, but what is your question? One of the `Integer.parseInt` throws an exception because it gets something that is **not** a number –  Nov 12 '17 at 08:12
  • 1
    What is your input? – icarumbas Nov 12 '17 at 08:13
  • 3
    Compilers can't yet predict user's input. – Maroun Nov 12 '17 at 08:14
  • 1
    Your should include the complete error message and the complete stacktrace in all Java questions about runtime errors. – Stephen C Nov 12 '17 at 08:30
  • The 'error' you have quoted is the first line of the stack trace. The real error tells you exactly what is wrong, not that it's a mystery: you tried to parse something that wasn't an integer as an integer. – user207421 Nov 12 '17 at 08:37

2 Answers2

1

Problem is with your input. Here it is Stock String. Seems, you successfully split that String to tempArray[]. Your code expect first three elements of this array as integer values. But unfortunately not. So please check your Input Stock. May be id, price or generation cannot parse to Int.

Shineed Basheer
  • 578
  • 5
  • 16
0

I found this other stackoverflow answer helpful; How to check if a String is numeric in Java by @CraigTP.

But you can just catch the exception and deal with it as shown below:

Scanner readyBoi;
ArrayList<Item> shopStock = new ArrayList<Item>();

public Shop(String stock){
  this.readyBoi = new Scanner(stock);
  while(readyBoi.hasNextLine()){
    String temp = readyBoi.nextLine();
    Tycoon.out(temp);
    String tempArray[] = temp.split("\t", 5);
    try{
      Item i = new Item(
        Integer.parseInt(tempArray[0]),
        Integer.parseInt(tempArray[1]),
        Integer.parseInt(tempArray[2]),
        tempArray[3],
        tempArray[4]);
        this.shopStock.add(i);
    }catch(NumberFormatException nfe){
       System.out.println("One of the params is not an integer");
    }
  }
}
cdaiga
  • 4,861
  • 3
  • 22
  • 42