+ 2

Why this code doesn’t works in sololearn editor🌚?

import java.util.*; public class Program { static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { int x = getIntInput(); System.out.println(x); } public static int getIntInput(){ int choose = 0; while (choose == 0){ try{ choose = scanner.nextInt(); if(choose == 0){ throw new InputMismatchException(); } scanner.nextLine(); } catch(InputMismatchException e){ scanner.nextLine(); System.out.print("\nERROR: INVALID INPUT.\nPlease try again: "); } } return choose; } }

4th Feb 2021, 2:30 PM
Muhammad Abdullah
Muhammad Abdullah - avatar
6 RĂ©ponses
+ 6
Muhammad Abdullah NoSuchElement error will come because Sololearn editor takes input only one time. Sololearn editor is not like Command Line Argument where you can take input at run time. using while loop you are taking input multiple times but SoloLearn editor accept only one time so after giving valid error it will give NoSuchElement exception. You can simply handle exception like this try { int n = sc.nextInt(); System.out.println("Hello " + n); } catch (Exception e) { System.out.println("Enter only numeric value => " + e); }
5th Feb 2021, 1:26 AM
AÍąJ
AÍąJ - avatar
+ 4
it works, as soon as you enter at least a line starting with an integer followed by a new line... even if last line is empty. without this last new line, you'll get an error from scanner.nextLine wich could not find anything ^^
4th Feb 2021, 2:39 PM
visph
visph - avatar
+ 3
Muhammad Abdullah What is the use of scanner.nextLine() here. It seems useless.
4th Feb 2021, 3:07 PM
AÍąJ
AÍąJ - avatar
+ 2
I am trying to get only integer input from user. While a user inputting something out of integer, it will throw an exception and it also will catch it. The programme says that. But in the sololearn editor, when I run this, it takes an integer and can't handle the expression. Output say NoSuchElementFount! There’s a case: 'scanner.nextLine()' after if block, is doing something weird I didn’t wanting my programme. So I remove this line. But still the problem appears! If I input an integer, it output the integer nicely. But when I input anything else Integer, I directly output the corresponding Exception on the Sololearn terminal. Sololearn terminal didn’t run over the while loop for getting valid integer input! ?? :''(
5th Feb 2021, 1:03 AM
Muhammad Abdullah
Muhammad Abdullah - avatar
+ 2
Because Sololearn editor doesn't accept input during run time.... It only accept input at the start....change the code according to that and it will work fine
5th Feb 2021, 11:28 AM
Utkarsh
Utkarsh - avatar
0
This program is working fine. Can you please give your excpected output?
4th Feb 2021, 2:39 PM
Atul [Inactive]