只是一个功能很少的银行代码,我只是想学习循环的方法。似乎在所有具有if的行上都会出现“不兼容的操作数类型String和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");
}
}
}
答案 0 :(得分:1)
您无法将字符串与整数进行比较,因为它们是两种不同的数据类型。您必须将字符串转换为整数才能执行此操作。 像这样:
if(Integer.parseInt( confirm ) == 1)
或者,您可以在将用户输入存储在字符串变量中之前对其进行转换。
int confirm = Integer.parseInt(in.nextLine());
您还可以将用户输入读取为整数而不是字符串。
int confirm = in.nextInt();
对于值0207,将其作为字符串进行比较会因为前导0而更明智。如果将其作为整数进行比较,则会丢失此信息。要比较字符串,可以使用equals()方法。
if(pin.equals("0207"))
答案 1 :(得分:1)
您的代码存在多个问题。以rsa2
为例:
if(pin == 0207)
是一个字符串,因此无法将其与此类数字进行比较pin
而不是equals()
==
是一个八进制字面值,即十进制数字为135. 要将此更改0207
修改为pin == 0207
,并将其他字符串比较(例如pin.equals( "0207" )
)也相应地修复。
您也可以尝试将字符串解析为数字,例如confirm == 1
但由于Integer.parseInt( confirm) == 1
可能意味着要使用,因此您需要在此使用0207
。
答案 2 :(得分:1)
由于Scanner#nextLine()
返回String
而导致错误,因此,当您致电时:
String confirm = in.nextLine();
confirm
是String
然后您正在尝试比较:
if(confirm == 1)
换句话说:
if (String == int)
你应该:
按如下方式更改if
:
if (confirm.equals("1"))