从单个方法多次返回Scanner

时间:2017-01-03 23:39:48

标签: java class methods java.util.scanner

使我的代码更清洁我想知道我是否可以将扫描仪输入分成不同的方法。然而,一旦我这样做,我遇到了很多错误,无法执行任务。

主要代码:

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

1 个答案:

答案 0 :(得分:0)

idkeywordpricetaskInput范围内的局部变量,在方法终止后您无法与它们相关联。一种可能的方法是使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();
    }
}