Lemons12345
Lemons12345

Reputation: 25

Loop termination confusion

So I have this code to enter a series of integers to a sequence but I would like to know how can I terminate the while loop just by entering no values and pressing enter. I know that I can put a condition like terminate the loop if the x integer value is 0.

public static void main(String[] args) {
SimpleReader in = new SimpleReader1L();
    SimpleWriter out = new SimpleWriter1L();
    Sequence<Integer> s = new Sequence1L<>();
    Sequence<Integer> temp = s.newInstance();
    System.out.println("Enter ");
    int x = in.nextInteger();
    int i = 0;
    while (in.nextLine()) {
        s.add(i, x);
        x = in.nextInteger();
        i++;
    }
    System.out.println(s);
}

Upvotes: 1

Views: 57

Answers (5)

makingthematrix
makingthematrix

Reputation: 395

You can also hack it a bit, since the = operation returns the same value it sets:

  SimpleReader in = new SimpleReader1L();
  Sequence<Integer> s = new Sequence1L<>();
  System.out.println("Enter ");
  int i = 0;
  String line = "";
  while (!(line = ir.readLine()).trim().isEmpty()) {
    x = Integer.parseInt(line);
    s.add(i, x);
    i++;
  }
  System.out.println(s);

Upvotes: 0

user4318530
user4318530

Reputation:

Press enter with no values.,

while (in.nextLine().length() > 0) {
    s.add(i, x);
    x = in.nextInteger();
    i++;
}

loop terminates.

Upvotes: 0

akostadinov
akostadinov

Reputation: 18614

You need to change the way you're reading input if you want to achieve what you described - enter nothing.

First having a while (in.nextLine()) eats an extra line from your input. So half of your input lines are just lost.

I'd suggest reading the line like String line = in.nextLine(). Then something like:

if (line.equals("")) break;
int x = Integer.parseInt(line);

Sorry, not doing java lately to give you the whole loop. But I think you should get the idea.

Upvotes: 1

SMA
SMA

Reputation: 37033

Use a do while loop as below:

do {
    input = int.nextInteger();
    s.add(i, x);
    i++;
} while (input != 0);

or using while loop in your case

while (in.nextLine()) {//assuming it checks if user has input
    s.add(i, x);
    x = in.nextInteger();//assuming this api gives integer value back if user indeed entered one
    if (x == 0) 
        break;
    i++;
}

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234715

break can be used to exit a loop. So you could put this:

if (x == 0) break; just before the statement i++;

Upvotes: 0

Related Questions