我一直在尝试使用Scanner来询问用户输入,然后将其写入对象以保存它们。 但是我遇到了静态和非静态变量的冲突。我对Static的理解是,如果我把我的类写成静态,它会阻止我改变它,但是我也不能让我的Main语句不是静态的。
import java.util.Scanner;
class Booking{
public class Ticket{
int Amount; //To be used to record how many of a specific ticket are needed.
int Price =6;
public void SetAmount(int Order){
this.Amount = Order;
}
}
public static void main(String args[]) {
Scanner myScanner = new Scanner(System.in);
Ticket Booking = new Ticket();
System.out.println("How many tickets would you like?")
int AmountBooked = scan.nextInt();
Booking.SetAmount(AmountBooked);
}
}
我很确定此代码中还有其他错误但是随着时间的推移,我已经尝试重新运行它,并且有很多不同的部分注释掉了我确定错误是在“Ticket Booking = new Ticket”行中);”所以如果可以集中精力,我会很感激。
答案 0 :(得分:0)
嵌套类不能是公共的,它必须是私有的或默认的。如果你想在静态函数(在你的情况下为main)中访问它,它需要是静态的。所以,改变
public class Ticket
to
private static class Ticket
您正在创建Ticket类的对象并将其命名为Booking。预订是您的公共类的名称,因此您无法重复使用它来命名您的对象,这将导致冲突。将您的变量重命名为其他标识符,例如“obj”或“ticket”。
另外,替换
scan.nextInt();
with
myScanner.nextInt();
答案 1 :(得分:0)
您需要进行预订SetAmount
方法static
。或者您需要设置预订方法的对象来执行调用方法SetAmount
。
如下代码:
import java.util.Scanner;
class Booking{
public static class Ticket{
int Amount; //To be used to record how many of a specific ticket are needed.
int Price =6;
public void SetAmount(int Order){
this.Amount = Order;
System.out.println("SetAmount="+Order);
}
}
public static void main(String args[]) {
Booking.Ticket ticket=new Booking.Ticket();
Scanner scanner = new Scanner(System.in);
System.out.println("How many tickets would you like?");
int AmountBooked = scanner.nextInt();
ticket.SetAmount(AmountBooked);
}
}
答案 2 :(得分:0)
你走在正确的轨道上,试着记住你的名字如何扫描一些对象)并正确使用它们(当应用完成后关闭它!)
添加/覆盖 toString ,这样您就可以获得有关对象状态的人类可读想法
public class PWTest {
public static void main(String args[]) {
Scanner myScanner = new Scanner(System.in);
Ticket booking = new Ticket();
System.out.println("How many tickets would ...");
int amountBooked = myScanner.nextInt();
booking.setAmount(amountBooked);
System.out.println(booking);
myScanner.close();
}
}
class Ticket {
int amount;
int price = 6;
public void setAmount(int Order) {
amount = Order;
}
@Override
public String toString() {
return "Ticket [amount=" + amount + ", price=" + price + "]";
}
}
并查看名称约定suggested by oracle