0

I cant get this to work for some reason. I have an app that reads transactions, when an empty line in entered it needs to print out some stuff.

    int transationCount = 0;
    while(sc.hasNext())
    {
        String trans = sc.next();


            String mode = trans.substring(0, 1);
            Double amount = Double.valueOf(trans.substring(1));

            if(mode.equals("C"))
            {
                c.charge(amount);
                ps.println(c.getBalance());
                transationCount = transationCount + 1;
            }
            else if(mode.equals("P"))
            {
                c.pay(amount);
                ps.println(c.getBalance());
                transationCount = transationCount + 1;
            }
    }
    ps.println(c.getBalance());
    ps.println(transationCount);

I tried

while(sc.hasNext() && !(sc.next().equals("")))

doesnt work. I also tried adding inside the while loop

else if (!(trans.equals("")) {break;}
Deniz Cetinalp
  • 901
  • 1
  • 18
  • 34

3 Answers3

2

By default, an empty line will be ignored by the scanner as it is not a valid token.

You could manually check if the line is empty:

public static void main(String[] args) throws Exception {
    Scanner sc = new Scanner(System.in);

    while(true) {
        String line = sc.nextLine();
        if (line.isEmpty()) {
            System.out.println("Empty line entered");
        } else {
            System.out.println("received line: " + line);
            String[] tokens = line.split("\\s+");
            System.out.println("tokens: " + Arrays.toString(tokens));
        }
    }
}
assylias
  • 321,522
  • 82
  • 660
  • 783
1

Your Scanner is using the default delimiter (a whitespace) to tokenize the input. This means that tokens are words, regardless of the lines they are in.

some

word

only returns two tokens, exactly as

some word

What you really need is to get lines separately, in order to tell which line is empty, and which line contain something. In order to do that, use new line as a separator:

Scanner.useDelimiter("\\n");

Or you might as well use BufferedReader, see BufferedReader.readLine()

Please note that two words on the same line will now be contained in the same trans string. You can use the String.split method to get each word separately.

djjeck
  • 1,781
  • 17
  • 25
0

So then how would I escape the while loop if an empty line is entered? Is there another way? – Infodayne

you can use label over/above your while loop, and break it when emptyLine is encountered

or alternatively you can use

Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
 while(! line.isEmpty()){

} 

line.isEmpty() returns true when line is empty,So condition to enter while loop will become false as now inside while loop we have(! (true)) which equals to (false) therefore while loop will not execute.

Tanmay jain
  • 814
  • 6
  • 11