不兼容的操作数类型字符串和int
问题描述:
只是一个功能很少的银行的代码,我只是试图学习循环的方式。似乎得到“不兼容的操作数类型字符串和整数”错误的所有行上有一个if,否则如果。不兼容的操作数类型字符串和int
import java.util.Scanner;
public class Bank
{
//create variables
int pac;
int confirm;
int pin;
int Bal_or_Exit;
public static void main(String args[])
{
//Receive any PAC and create if loop for continue or exit
Scanner in = new Scanner(System.in);
System.out.println("Please Enter your Personal Access Code (P.A.C)");
String pac = in.nextLine();
System.out.println(pac + " is the P.A.C you have just entered.");
System.out.println("Press 1 to continue, Press 2 to cancel");
String confirm = in.nextLine();
if(confirm == 1)
//if loop created for confirm or exit...create another if loop for a pin of 0207
{
System.out.println("Please Enter your Pin");
String pin = in.nextLine();
if(pin == 0207)
//if loop created for pin, only access if pin=0207..access granted and
option of viewing Account Balance or Exit
{
System.out.println("Welcome!");
System.out.println("Press 1 for Balance");
System.out.println("Press 2 to Exit");
String Bal_or_Exit = in.nextLine();
//if 1 is pressed, display balance of €2965.33
if(Bal_or_Exit == 1)
{
System.out.println("Your balance is €2965.33");
}
//if 2 is pressed, display goodbye message
else if(Bal_or_Exit == 2)
{
System.out.println("GoodBye, Have a Nice a Day!");
}
//if anything else is pressed display error message
else
{
System.out.println("We're Sorry, An Error has Occured");
}
}
//if pin is anything except 0207 , display wrong pin message
else
{
System.out.println("The PIN you Have entered is incorrect");
}
}
//if confirm = 2 (exit), display exit and goodbye message
else if(confirm == 2)
{
System.out.println("You have selected exit");
System.out.println("Have a Nice Day!");
}
//if confirm is not = 1 or 2, display error message
else
{
System.out.println("We're Sorry, An Error has Occured");
}
}
}
答
您有错误,由于Scanner#nextLine()
返回String
,所以,当你拨打:
String confirm = in.nextLine();
confirm
是String
,然后你想比较:
if(confirm == 1)
在其他字:
if (String == int)
您应该:
-
更改
if
如下:if (confirm.equals("1"))
答
不能将字符串与整数进行比较,因为它们是两种不同的数据类型。您必须将字符串转换为一个整数才能完成此操作。 像这样:
if(Integer.parseInt(confirm ) == 1)
另外,您可以将其存储在字符串变量之前投的用户输入。
int confirm = Integer.parseInt(in.nextLine());
您还可以将用户输入读取为整数而不是字符串。
int confirm = in.nextInt();
对于价值0207这将是更明智的把它作为比较,因为0领先,如果你比较它作为一个整数此信息会迷路的字符串。要比较字符串,你可以使用equals()方法。
if(pin.equals("0207"))
答
您的代码有多个问题。以if(pin == 0207)
为例:
-
pin
是一个字符串,因此它不能相比的一些像 - 串需要通过
equals()
进行比较,而不是==
-
0207
是八进制直译,即十进制这将是数135
要修复到pin.equals("0207")
和TH这种变化pin == 0207
e其他字符串比较也相应地如confirm == 1
。
您也可以尝试将字符串解析为数字,例如Integer.parseInt(confirm) == 1
,但由于0207
可能是因为它的原因,因此无论如何您都需要使用String
。
首先第一,Java的**不是**的Javascript – Frakcool
'如果(针== 0207) ',哇,慢慢地。一个'int'没有前导零,它只会保存'207'。因此,您不应该使用'int'来表示PIN。 – domsson
这是作业/作业吗?我认为你应该咨询你的导师/同学/课本/教程。 – domsson