我一直在尝试编码电影院项目,但我无法弄清楚。当我运行程序时,它只会输出最后一个值进入固定套件,因此即使他们的年龄不正确,也可以让他面前的每个人进入电影院。我相信这与不是数组的人对象有关,但是我不确定该如何解决这个想法?
import java.util.Scanner;
public class Cinema
{
public static void main(String[] args)
{
QueueWithArray q = new QueueWithArray();
Person person = new Person();
Scanner kybd = new Scanner(System.in);
System.out.print("Join (j), leave (l) or end (e)? ");
String action = kybd.nextLine();
while (!action.equalsIgnoreCase("e"))
{
if (action.equalsIgnoreCase("j"))
{
System.out.print("Enter your name: ");
String name = kybd.nextLine();
person.setName(name);
q.add(name);
System.out.println("What is your age? ");
int age = kybd.nextInt();
person.setAge(age);
kybd.nextLine();
System.out.println(name + " is going to the cinema and is " + age + " years old.");
}
else if (action.equalsIgnoreCase("l"))
{
if (!q.isEmpty())
{
if (person.getAge() >= 15 )
{
System.out.println(q.remove() + " has left the queue and entered the cinema");
}
else
{
System.out.println(q.remove() + " has left the queue, but is not old enough to watch the film");
}
}
else
{
System.out.println("Queue empty");
}
}
else
{
System.out.println("Invalid operation");
}
System.out.print("Join (j), leave (l) or end (e)? ");
action = kybd.nextLine();
}
}
}
您应该拥有第二个列表,以存储人的年龄。
想象一下您有一个Pidgeonhole,您可以在其中放一张纸上的纸。与指定的年龄有关。
当涉及到每个人时,您每次都会阅读同一张纸。取而代
之类的东西System.out.print("Enter your name: ");
String name = kybd.nextLine();
System.out.println("What is your age? ");
int age = kybd.nextInt();
qName.add(name);
qAge.add(age);
kybd.nextLine();
或一种更好的方法:
System.out.print("Enter your name: ");
String name = kybd.nextLine();
System.out.println("What is your age? ");
int age = kybd.nextInt();
Person person = new Person(name, age);
qPerson.add(person);
kybd.nextLine();