java—从单个方法返回多个新的scanner

zbdgwd5y  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(332)

为了使我的代码更干净,我想知道是否可以将扫描器输入分离到另一个方法。然而,当我这么做的时候,我遇到了很多错误,无法完成任务。
主要代码:

public static void main(String[] args){
    Task taskObject = new Task();

    taskObject.taskInput();
    taskObject.taskOutput(id, keyword, price);
}

任务类代码:

import java.util.Scanner;

public class Task{
    public task taskInput(){
        Scanner scan = new Scanner(System.in);

        System.out.println("\nEnter the id: ");
        int id = scan.nextInt();

        System.out.println("\nEnter the keyword: ");
        String keyword = scan.nextLine();

        System.out.println("\nEnter the price: ");
        double price = scan.nextDouble();

        return task(id, keyword, price);
    }

    public void taskOutput(int id, String keyword, double price){       
        System.out.println(id);
        System.out.println(keyword);
        System.out.println(price);
    }
}
1tuwyuhd

1tuwyuhd1#

id , keyword 以及 price 局部变量在 taskInput ,并且在方法终止后无法与它们关联。一种可能的方法是 Task 对象有状态,并将其另存为成员:

import java.util.Scanner;

public class Task{
    private int id;
    private String keyword;
    private double price;

    public void taskInput(){
        Scanner scan = new Scanner(System.in);

        System.out.println("\nEnter the id: ");
        id = scan.nextInt();

        System.out.println("\nEnter the keyword: ");
        keyword = scan.nextLine();

        System.out.println("\nEnter the price: ");
        price = scan.nextDouble();
    }

    public void taskOutput() {
        // Note that id, keyword and price are now members       
        System.out.println(id);
        System.out.println(keyword);
        System.out.println(price);
    }

    public static void main(String[] args){
        Task taskObject = new Task();

        taskObject.taskInput();
        taskObject.taskOutput();
    }
}

相关问题