i tried to creating a new scanner after i closed the former in the main. but it gives error. i thought that i created a new scanner in the method than i closed it so it would read the new inputs through my method but it did not. what is the issue here? chatgpt couldn't illuminate me :(
package gross_calculator;
import java.util.Scanner;
public class GrossPayCalculator {
static void story() {
System.out.println("Which season the day is of?");
Scanner scanner1 = new Scanner(System.in);
String season = scanner1.nextLine();
System.out.println("How is that day?");
String adjective = scanner1.nextLine();
System.out.println("What is the number?");
int number = scanner1.nextInt();
System.out.println("On a "+adjective+" "+season+" day,\nyou read "+number+" pages of book.");
scanner1.close();
}
public static void main(String[] args) {
int hours = 0;
System.out.println("How many hours did you work?: ");
Scanner scanner = new Scanner(System.in);
hours = scanner.nextInt();
double payRate = 0;
System.out.println("What is your pay rate?: ");
payRate = scanner.nextDouble();
scanner.close();
double grossPay = hours*payRate;
System.out.println("Gross pay: "+grossPay);
story();
}
}
error message:
How many hours did you work?:
23
What is your pay rate?:
12,2
Gross pay: 280.59999999999997
Which season the day is of?
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at java_essentials/gross_calculator.GrossPayCalculator.story(GrossPayCalculator.java:11)
at java_essentials/gross_calculator.GrossPayCalculator.main(GrossPayCalculator.java:36)
Use a single
Scannerobject, and don't close it since you are reading fromSystem.inSee the comments on this answer for further clarification.
Example Usage: