When I declare a field and declare a method after creating one class, if I need a scanner in several methods, should I declare and close the scanner for each method??
And I created several classes, and I wonder how to declare a scanner when I need a scanner for each class!
import java.util.Scanner;
class example
{
inta,b,c;//any field for example
public void ex1
{
Scanner scanner = new Scanner(System.in);
this.a=scanner.nextInt();
}
public void ex2
{
Scanner scanner = new Scanner(System.in);
this.b=scanner.nextInt();
}
}```
You don't do that, but repeat it with a repeat statement of for, while.
Each class should be designed to receive input from only one place, even if required.
It usually has the following structure.
Scanner scanner=new Scanner(System.in);
while (true) {
System.out.println("Insert question code:");
String question = scanner.nextLine();
If(question.equals("quit"){ // exit when quit is entered
break;
}
System.out.println("Insert answer code:");
String answer = scanner.nextLine();
if(answer.equals("quit")){
break;
}
service.storeResults(quest, answer); // Delegate to the class to process
}
613 GDB gets version error when attempting to debug with the Presense SDK (IDE)
915 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
573 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
574 Who developed the "avformat-59.dll" that comes with FFmpeg?
© 2024 OneMinuteCode. All rights reserved.