我正在尝试创建一个程序,提示用户输入名称(三个选项x,y或z中的一个)和某个变量(小于10)。如果这两个输入均为真,则会将名称和数字打印为:("您选择x乘以2")
我被困了,因为我是java扫描器类(和java)的新手,并且不知道如何使用if语句检查两个因素来配置代码。
帮助?
到目前为止我的代码:我知道很多错误:
import java.util.Scanner;
public class ScannerAndKeyboard {
public static void main(String[] args)
{ Scanner s = new Scanner(System.in);
System.out.print("Welcome");
System.out.print( "Enter your name: " );
String name = s.nextLine();
System.out.println( "Hello " + name + "!" );
System.out.print("Please Enter letter and number: " );
if(s.nextLine().equals(X) && s.nextInt() <= 10)
System.out.println( "You choose x10");
}
}
答案 0 :(得分:0)
这应该适合你:
import java.util.Scanner;
public class ScannerAndKeyboard {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print("Welcome");
System.out.print( "Enter your name: " );
String name = s.nextLine();
System.out.println( "Hello " + name + "!" );
System.out.print("Please Enter letter and number: " );
String X = s.useDelimiter("\\s").next();
int num = s.nextInt();
if((X.equalsIgnoreCase("x") || X.equalsIgnoreCase("y") ||
X.equalsIgnoreCase("z")) && num < 10)
System.out.println( "You choose "+X+num);
}
}
我通过验证以下输入进行了测试(您可以修改提示):
WelcomeEnter your name: Alvin
Hello Alvin!
Please Enter letter and number: X 9
You choose X9
答案 1 :(得分:-1)
从您的代码中,我没有看到名为X
的变量。所以我假设你想要一个角色比较。
if(s.nextLine().equals("X") && s.nextInt() <= 10)
用双引号包裹X
,它可以解决您的问题。
修改强>
如果您需要添加变量并检查x,y or z
,请执行以下操作:
import java.util.Scanner;
public class ScannerAndKeyboard {
public static void main(String[] args)
{ Scanner s = new Scanner(System.in);
System.out.print("Welcome");
System.out.print( "Enter your name: " );
String name = s.nextLine();
System.out.println( "Hello " + name + "!" );
System.out.print("Please Enter letter and number: " );
String X = s.nextLine();
if((X.equalsIgnoreCase("x") || X.equalsIgnoreCase("y") || X.equalsIgnoreCase("z")) && s.nextInt() <= 10)
System.out.println( "You choose "+X+" 10");
}
}
编辑2
如果要在同一行,请执行以下操作:
import java.util.Scanner;
public class ScannerAndKeyboard {
public static void main(String[] args)
{ Scanner s = new Scanner(System.in);
System.out.print("Welcome");
System.out.print( "Enter your name: " );
String name = s.nextLine();
System.out.println( "Hello " + name + "!" );
boolean stat = true;
while(boolean)
System.out.print("Please Enter letter and number: " );
String X = s.nextLine();
String[] X1 = X.split(" ");
if((X1[0].equalsIgnoreCase("x") || X1[0].equalsIgnoreCase("y") || X1[0].equalsIgnoreCase("z")) && Integer.parseInt(X1[1]) <= 10)
System.out.println( "You choose "+X1[0]+" "+X1[1]);
stat = false;
}
else {
System.out.println("Invalid Input!");
}
}