-3

In the main() function of http://penguin.ewu.edu/cscd501/Wint-2011/BranchAndBound/Knap01BnB.txt

  inp = new Scanner ( new File(lineIn) );

  maxWeight = inp.nextInt();
  n = inp.nextInt();
  System.out.printf ("Reading data from file %s, with %d items\n",
                     lineIn, n);

  avail = new Item[n];
  pack  = new boolean[n];

  for ( k = 0; k < n; k++ )
  {  weight = inp.nextInt();
     profit = inp.nextInt();
     avail[k] = new Item(weight, profit);
  }

Using the above code, i tried running the Bandp.txt and it had no problem. I had a problem whie trying to run the txt file with decimal fraction values:

Exception in thread "main" java.util.InputMismatchException at
java.util.Scanner.throwFor(Unknown Source) at 
java.util.Scanner.next(Unknown Source) at 
java.util.Scanner.nextInt(Unknown Source) at 
java.util.Scanner.nextInt(Unknown Source) at 
Knap01BnB.main(Knap01BnB.java:199)

Which part of the codes do i need to change as such that decimal values can be shown and they would not show a input mismatch.

My txt file is as shown below : data.txt

100 20
12.64 8.43 4.21 8.45 17.56 8.31 13.85 12.39 19.32 14.29 4.03 17.14 8.24 1.24 0.79 5.59 6.6 12.18 12.24 1.67 6.45 19.43 9.88 8.75 18.37 15.64 8.24 5.55 3.6 6.4 6.69 18.44 3.07 0.71 11.28 10.25 14.26 12.14 0.71 2.37

And this are the values in BandP.txt :

15 7 5 25 11 45 3 12 2 7 2 6 7 10 5 4

Mat
  • 202,337
  • 40
  • 393
  • 406
  • This was the problem that i had encountered Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at Knap01BnB.main(Knap01BnB.java:199) – user1632981 Aug 29 '12 at 11:46

1 Answers1

3

The error message tells you what the problem is:

Exception in thread "main" java.util.InputMismatchException at
...
java.util.Scanner.nextInt(Unknown Source) 
at Knap01BnB.main(Knap01BnB.java:199)

Line 199 of your program calls Scanner.nextInt(). Scanner.nextInt() called a stack of other methods, and one of them threw an InputMismatchException.

The documentation for Scanner.nextInt() tells you under what circumstances it throws that exception: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html#nextInt()

So it has read something which it can't parse, because nextInt() is for reading integers, and you are giving it a number containing a decimal point.

You could change it to nextFloat(). This will have other effects. For a start, the variable you are assigning to will need to become a float. There will be a domino effect -- read the compiler errors and the stack traces, follow the line numbers, and fix them one by one.

I can't guarantee that your algorithm will even work with floating point numbers -- I guess you'll find out.

slim
  • 40,215
  • 13
  • 94
  • 127