I have really tried to find the answer through the threads but still hope to get some feed back.
The code below is bad style I think but I don't know why it shoot me a
java.util.NoSuchElementException
after enter the number since I make two Scanner objects for two methods and I should be able to start a new input. And if I erase the input.close()
in inputAndPrintNumber(), it works and compile correctly. I really hope to know why and how to fix it if I still use two Scanner obj and without erasing the input.close()
if possible.
import java.util.*;
public class t{
public static void main(String [] args){
inputAndPrintNumber();
inputAndPrintString();
}
public static void inputAndPrintNumber(){
Scanner input = new Scanner(System.in);
String s = input.nextLine();
System.out.print(s);
input.close();
}
public static void inputAndPrintString(){
Scanner input2 = new Scanner(System.in);
int a = input2.nextInt();
System.out.print(a);
}
}
I don't even sure whether the code below is better or any better idea?
import java.util.*;
public class t{
public static Scanner input = new Scanner(System.in);
public static void main(String [] args){
inputAndPrintNumber();
inputAndPrintString();
input.close();
}
public static void inputAndPrintNumber(){
String s = input.nextLine();
System.out.print(s);
}
public static void inputAndPrintString(){
int a = input.nextInt();
System.out.print(a);
}
}