我试图将扫描仪设置为字符串eventType,以便它习惯于用户的输入,但是我在编辑器上始终收到错误消息。我添加了第一个if语句,以了解我要执行的操作。
import java.util.Scanner;
public class main {
public static void main (String[] args) {
int whatToEat;
int partySize;
String eventType;
Scanner sc = new Scanner(System.in);
String eventType = sc.next();
Scanner scnr = new Scanner(System.in);
whatToEat = scnr.nextInt();
Scanner scnr1 = new Scanner(System.in);
partySize = scnr1.nextInt();
if (eventType.equals("Casual") && partySize == 1) {
System.out.println("Since you're hosting a casual event for "
+ partySize +
"participants, you should serve sandwiches prepared in the mircowave. ");
答案 0 :(得分:1)
如果我进行了更改,那么此代码对我来说很好用。您将两次定义String变量eventType
。如果将行String eventType = sc.next();
更改为eventType = sc.next();
(去掉单词'String'),此代码似乎可以正常工作。
请注意,给您的班级main
命名不是一个好主意,但是在这种情况下,这似乎没问题。
您无需为每个输入创建一个新的Scanner对象。这是您的代码版本,可解决我提到的小问题:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String eventType = sc.next();
int whatToEat = sc.nextInt();
int partySize = sc.nextInt();
if (eventType.equals("Casual") && partySize == 1) {
System.out.println("Since you're hosting a casual event for "
+ partySize +
" participants, you should serve sandwiches prepared in the mircowave. ");
}
}
}
结果:
Casual
1
1
Since you're hosting a casual event for 1 participants, you should serve sandwiches prepared in the mircowave.