Please check the else condition's sc.nextLine(), here I am giving 10 numbers and then getting their sum. If provides any invalid data(which is not int), it will go to else condition. consider input as - 1 2 3 d Then it shows the invalid data line twice. if I put sc.nextLine() outside from the else, it works fine. I want to know the logic behind two times printing.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int count = 0;
int sum = 0;
Scanner sc = new Scanner(System.in);
while (true) {
System.out.print("Enter number " + (count + 1) + " - ");
boolean isInt = sc.hasNextInt();
if (isInt) {
int num = sc.nextInt();
sum += num;
count++;
if (count == 10) {
break;
}
} else {
System.out.print("Invalid number, put int");
sc.nextLine();
}
// sc.nextLine();
}
System.out.println(sum);
sc.close();
}
}