Using two methods to get multiple user inputs in Java


Using two methods to get multiple user inputs in Java
I am working on some basic java skills are I am getting a NoSuchElementExemption when I am debugging. My goal is to ask two questions in two different methods and combine them in the main function. Could someone explain the rule that I am breaking?
The code is as follows:
import java.util.Scanner;
public class TwoInputs{
public static double test()
{
Scanner reader2 = new Scanner(System.in);
System.out.println("Enter a number ");
double n2 = reader2.nextDouble();
if (n2 %1 != 0) {
System.out.println("Number is invalid");
} else {
reader2.close();
System.out.println("You put the number " + n2);
}
return n2;
}
public static double test2()
{
Scanner reader1 = new Scanner(System.in);
System.out.println("Enter a number ");
double n1 = reader1.nextInt();
if (n1 %1 != 0) {
System.out.println("Number is invalid");
} else {
reader1.close();
System.out.println("You put the number " + n1);
}
return n1;
}
public static void main(String args) {
double sum = test();
double sum2 = test2();
System.out.println("You put the number " + sum+ "and"+ sum2);
}
}
You close System.in and try to reuse it, the link I provided above explains a workaround for this.
– Wow
4 mins ago
1 Answer
1
I think by closing the reader, the inputstream will be closed, too. I.e. you can not open an other Scanner with System.in. Try it this way:
import java.util.Scanner;
public class Main {
public static double test(Scanner scanner)
{
System.out.println("Enter a number ");
double n2 = scanner.nextDouble();
if (n2 %1 != 0) {
System.out.println("Number is invalid");
} else {
System.out.println("You put the number " + n2);
}
return n2;
}
public static double test2(Scanner scanner)
{
System.out.println("Enter a number ");
double n1 = scanner.nextInt();
if (n1 %1 != 0) {
System.out.println("Number is invalid");
} else {
System.out.println("You put the number " + n1);
}
return n1;
}
public static void main(String args) {
Scanner scanner = new Scanner(System.in);
double sum = test(scanner);
double sum2 = test2(scanner);
System.out.println("You put the number " + sum+ "and"+ sum2);
}
}
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Possible duplicate of Close a Scanner linked to System.in
– Wow
4 mins ago