I just wrote down a program for a Java Programming question. As mentioned in the problem statement: The purpose of the question is to find out what digits do a particular 5-digit number comprise of and have them printed e.g. if the Number is 4567 then the output of the program should be 4 3 5 6 7
I implemented the solution in two methods one of them is named SimpleWay & the other is named HardWay().
Now when I run the program, after one method e.g. SimpleWay() has been called when the call is made for the HardWay() method I am getting the following error: java.util.NoSuchElementException: No line found
The code is given below:
package com.guru.chapter02;
import java.util.Scanner;
/**
Question: Write a program that inputs a five-digit integer,separates the integer
into its digits and prints them separated by three spaces each.
[Hint: Use the integer division and modulus operators.] For example, if
the user types in 42339, the program should print:
4 2 3 3 9
**/
public class C02Exercise27{
public static void main(String[] args) throws InterruptedException{
displayTheDigitsOfNumber_HardWay();
Thread.sleep(1000);
displayTheDigitsOfNumber_SimpleWay();
}
private static void p(String str){
System.out.print(str);
}
private static void displayTheDigitsOfNumber_SimpleWay(){
Scanner iScn = new Scanner(System.in);
p("Enter a five-digit number: ");
String str = iScn.nextLine();
try{
if((str.length()==5) & (((Integer)Integer.parseInt(str)) instanceof Integer)){
p("The digits of the number are: \n");
p(str.charAt(0) + " " + str.charAt(1)+ " "+ str.charAt(2)+ " "+ str.charAt(3)+ " "+ str.charAt(4) + "\n");
}
else
p("Re-launch the program & enter strictly a 5-digit number.Alphanumerics or Alphabetical input not allowed"+ "\n");
}catch(NumberFormatException e){
p("Re-launch the program & enter strictly a 5-digit number.Alphanumerics or Alphabetical input not allowed" + "\n");
}
}
private static void displayTheDigitsOfNumber_HardWay(){
Scanner iScn = new Scanner(System.in);
p("Enter a five-digit number: ");
int input = iScn.nextInt();
iScn.close();
p("Output Of displayTheDigitsOfNumber_HardWay() method \n");
p((input/10000)+" ");
p(((input%10000)/1000)+" ");
p((((input%10000)%1000)/100)+" ");
p(((((input%10000)%1000)%100)/10)+" ");
p(((((input%10000)%1000)%100)%10)+" ");
p("\n");
}
}
After I have made the call to displayTheDigitsOfNumber_HardWay() I get following error:
Enter a five-digit number: 43567
Output Of displayTheDigitsOfNumber_HardWay() method
4 3 5 6 7
Enter a five-digit number: Exception in thread "main"
java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at com.guru.chapter02.C02Exercise27.displayTheDigitsOfNumber_SimpleWay(C02Exercise27.java:25)
at com.guru.chapter02.C02Exercise27.main(C02Exercise27.java:15)