0

So i'm working on a program that would read a line of ones or twos (dollar store stuff) and would return the number of one euro coins and two euro coins. If there is a 2 in the input line it takes one one euro coin from the register (to return to the customer). And if the cashier runs out of one euro coins it prints bankrupt. So here is my problem, when i input the following line in cmd 1 1 1 1 1 2 1 1 1 it should return this 7 1 each in its own line (didn't know how to do it here). but it returns both 0. P.S.: the "BANKROT"means bankrupcy.

Here is my code:

import java.util.Scanner;

public class Tester {

Scanner sc = new Scanner(System.in);


public void program() {
    blagajna();
}

public void blagajna() {
    sc.useDelimiter(System.getProperty("line.separator"));

    int evrskiKovanec = 0;
    int dvoevrskiKovanec = 0;
    while (sc.hasNextInt()) {
        int kovanec = sc.nextInt();
        if (kovanec == 1)
            evrskiKovanec++;
        else if (kovanec == 2) {
            dvoevrskiKovanec++;
            if(evrskiKovanec == 0) {
                System.out.println("BANKROT");
                break;

            }
            evrskiKovanec--;
        }
    }
    System.out.printf("%d%n%d%n", evrskiKovanec, dvoevrskiKovanec); 
}


public static void main(String[] args) {
    Tester obj =  new Tester();
    obj.program();
    }
}

After trying to fix a problem i had with the sc.hasNextInt() not stopping taking new integers i'm not even sure where the problem is. I tried using the println() to print out the values in each loop but it didn't show it, so is it possible that it somehow skips the whole while loop? Any help is appreciated. And i hope the way i make this program work with the static method calling a non-static method that is calling to other methods doesn't bother you too much.

Abra
  • 11,631
  • 5
  • 25
  • 33
simsam
  • 23
  • 5
  • you need to call `sc.nextLine()` after every call to `sc.nextInt()` because `sc.nextInt()` does not consume the trailing newline character from the console – sleepToken Feb 02 '20 at 17:11
  • so first call the nextInt and the nextLine? Why is that? Doesn't nextLine read the whole line? – simsam Feb 02 '20 at 17:14
  • a better example: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo – sleepToken Feb 02 '20 at 17:25
  • it does help me understand why the nextLine() is requiered but the loop itself is still skipped, or at least none of the values are actualy read – simsam Feb 02 '20 at 17:43
  • it appears the first value only is read, but the rest cause the problem – simsam Feb 02 '20 at 17:46

0 Answers0