Java报错illegal start of type import java.util.Scanner如何解决
报错排查
- 核心触发原因:
import语句位置不符合Java语法规范。Java要求所有import导入语句必须放在源文件最顶部、所有类定义的外部,你将import java.util.Scanner;写在了LabExer2类的大括号内部,属于类作用域内的非法语句,直接触发编译报错。 - 额外语法违规:你的源文件名为
LabExer2.java,Java规定单个源文件中最多只能有一个public修饰的类,且类名必须和文件名完全一致,你在LabExer2内部额外定义了public class Main,也属于语法错误。 - 隐性逻辑问题:
setItemName方法参数为newItemName,但赋值语句错误写为this.itemName = itemName,会导致赋值失效;getTotalCost方法仅返回单价,未乘以商品数量,不符合方法语义。
修复方案
修改后可正常编译运行的代码如下:
import java.util.Scanner; public class LabExer2 { private String itemName; private double itemPrice; private int itemQuantity; private double amountDue; public void setItemName(String newItemName) { this.itemName = newItemName; } public void setTotalCost(int quantity, double price) { this.itemQuantity = quantity; this.itemPrice = price; } public String getItemName() { return itemName; } public double getTotalCost() { return itemPrice * itemQuantity; } public void readInput() { } public void writeOutput(){ } public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.println("Enter the name of the item you are purchasing "); String itemName = s.nextLine(); System.out.println("Enter the quantity and price seperated by a space "); int itemQuantity = s.nextInt(); double itemPrice = s.nextDouble(); System.out.println("You are purchasing " + itemQuantity + " " + itemName + "(S)" + " at " + itemPrice + " each."); } }
修改后重新编译即可解决原有报错,同时修复了隐性逻辑问题。
内容的提问来源于stack exchange,提问作者DJ Bumbay
相关产品推荐
相关产品推荐

