This is a question for the Java Scanner!

Asked 2 years ago, Updated 2 years ago, 123 views

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();
    }
}```

java scanner method object class

2022-09-22 12:42

1 Answers

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
}


2022-09-22 12:42

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.