2
  try {
        Scanner s = new Scanner(new BufferedInputStream(System.in));
        while (s.hasNextLine()) {
            first = true;
                int val1 = add(alpha, s.nextLine().toLowerCase().split(""));
                int val2 = add(alpha, s.nextLine().toLowerCase().split(""));
                first = false;
                while (val1 > 9 || val2 > 9) {
                    val1 = add(alpha, Integer.toString(val1).split(""));
                    val2 = add(alpha, Integer.toString(val2).split(""));
                }
                if (val1 > val2) {
                    System.out.println(format.format((val2 / (double) val1) * 100) + " %");
                } else {
                    System.out.println(format.format((val1 / (double) val2) * 100) + " %");
                }
        }
    } catch (NoSuchElementException e) {
        System.exit(0);
    }
}

static int add(String[] alpha, String[] letter) {
    int val = 0;
    for (String string : letter) {
        if (Character.isLetter(string.charAt(0))) {
            val += Arrays.asList(alpha).indexOf(string) + 1;
        } else if (!first && Character.isDigit(string.charAt(0)))
            val += Integer.parseInt(string);
    }
    return val;
}

I have read almost all previous questions about Scanner hasNext() not working properly but I couldn't get a fix. Any solution to this problem. The input is a multiple line string and there's no sentinel to character.

Petrus Kambala
  • 82
  • 1
  • 12
  • 1
    Is that your answer? http://stackoverflow.com/a/5653349/1503780 – Barbe Rouge Oct 14 '15 at 09:38
  • Thanks. But, do you have any solution to this. The strange part is if I debug I notice that at the end of the input, the s.hasNext() causes the while loop to stop but then the program itself doesn't stop. I don't know how that is possible though. – Petrus Kambala Oct 14 '15 at 09:44
  • As described in the linked answer above, scanner will always say it has a next line when reading keyboard input, unless you signal the end of input by Ctrl+Z / Ctrl+D. So you can either do that, or test for some chosen keyword in your input and end the loop then. – Cinnam Oct 14 '15 at 10:04

0 Answers0