d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Question About Code Again
Add Reply New Topic New Poll
Member
Posts: 31,399
Joined: Mar 25 2009
Gold: 99.00
Nov 8 2018 07:04pm
Code
package com.company;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

int counter = 0;
int sum = 0;

while(true) {
int order = counter + 1;
System.out.println("Enter number #" + order + ":");

boolean isAnInt = scanner.hasNextInt();
if(isAnInt) {
int number = scanner.nextInt();
counter++;
sum += number;
if(counter == 10) {
break;
}
} else {
System.out.println("Invalid Number");
}

scanner.nextLine(); //Handle end of line (Enter Key)
}


System.out.println("Sum = " + sum);
scanner.close();

}
}




I don't understand when this part of the code is executed...?

Code
scanner.nextLine(); //Handle end of line (Enter Key)



if someone could explain it, i'd appreciate it. ty guys.
Retired Moderator
Posts: 26,153
Joined: Nov 6 2006
Gold: 77.33
Trader: Trusted
Nov 10 2018 08:33am
Maybe it helps to shorten the code excerpt a bit:

Code
while(true) {
boolean isAnInt = scanner.hasNextInt();

if(isAnInt) {
int number = scanner.nextInt();
doSomethingWith(number);
} else {
printWarning();
}

scanner.nextLine();
}

scanner.hasNextInt() returns true if the next token can be interpreted as an int (but does not advance past any input).

scanner.nextInt() reads just the number (that you now know exists), not the end of line or anything after the number.

scanner.nextLine() is outside of the if/else statement, gets executed once at the end of the while loop, and reads the remainder of the line.
Member
Posts: 36,244
Joined: Nov 29 2005
Gold: Locked
Trader: Scammer
Jan 8 2019 12:11am
scanner.nextLine() doesn't really do anything, is a void method. It just makes a new line at the command line. Nothing is printed there yet, cursor is at the beginning of the line, first-first.

You press 'enter' and the cursor goes to a new line.

This post was edited by the_rest on Jan 8 2019 12:15am
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll