我正在尝试创建一个&#34; Class&#34;:Sandwich.Java 和&#34; Application&#34;:testSandwich.java。 < / p>
我的任务是包含在Sandwich.java中获取和设置3个字段的值的方法: 主要成分,面包类型,价格。 然后使用该应用程序,在数组中实例化五个Sandwich对象。 (五阵)
Sandwich.java:
public class Sandwich {
public String mainIngredient = "";
public String breadType = "";
public Double price;
String getMainIngredient(){
return mainIngredient;
}
void setMainIngredient(String mainIng){
mainIngredient = mainIng;
}
void setBread(String wheat){
breadType = wheat;
}
void setPrice(double mainPrice){
price = mainPrice;
}
testSandwich.java:
public class TestSandwich {
public static void main(String args[]) {
Sandwich[] sandwiches = new Sandwich[5];
for(int i = 0; i < 5; i++){
sandwiches[i] = new Sandwich();
System.out.println("Choose a Main Ingredient: ");
String userInput = user_input.next();
sandwiches[i].setBread(userInput);
System.out.println("Choose a Bread: ");
userInput = user_input.next();
sandwiches[i].setMainIngredient(userInput);
System.out.println(sandwiches[i].getMainIngredient());
System.out.println("");
当前错误输出:
选择主要成分:
线程中的异常&#34; main&#34; java.lang.RuntimeException:无法编译的源代码 - 错误的sym类型:user_input.next
at practical.TestSandwich.main(TestSandwich.java:24)
Java结果:1
建立成功(总时间:1秒)
问题: 如何修复错误以及如何获得我要查找的结果?
答案 0 :(得分:1)
抛出Exeption是因为你根本没有发起Scanner user_input
。在main()
函数开头尝试此操作:
Scanner user_input = new Scanner( System.in );
这是一个如何处理Scanner对象和用户输入的基本教程: http://www.homeandlearn.co.uk/java/user_input.html
我强烈建议您在发布问题之前做一些研究。你也应该明白你的程序是什么,否则你根本不会理解你的问题(就像这次一样)。