使我的代码更清洁我想知道我是否可以将扫描仪输入分成不同的方法。然而,一旦我这样做,我遇到了很多错误,无法执行任务。
主要代码:
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);
}
}
答案 0 :(得分:0)
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();
}
}