我是java编程的新手,我想在if语句中比较java Scanner String。我怎样才能做到这一点?
这就是我这样做的方式,但它没有给我预期的输出:
Scanner oper = new Scanner(System.in);
String op;
System.out.println("Enter operator(+,-,*,/,%): ");
op = oper.nextLine();
if (op=="+")
{
System.out.println("Answer is: "+fnum+snum);
}
我没有包含变量fnum和snum的代码。
答案 0 :(得分:4)
op.equals("+")
.. .equals()
是如何比较Java中序数相等的两个字符串。
所以你的代码应该是这样的:
if ("+".equals(op))
{
System.out.println("Answer is: "+fnum+snum);
}
==
将比较String
对象的两个引用,而不是String
对象的内容
答案 1 :(得分:0)
谢谢,但是如果我们有两个Scanner对象,然后尝试比较它们,我们将如何做?
import java.util.Scanner;
public class Jeb {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
print("User Name :");
String userName = input.nextLine();
print("Confirm :");
String userNameConfirm = input.nextLine();
print(userNameConfirm + " " + userName);
if(userName == userNameConfirm) { // Here it is my Problem !
print("Good !");
print("Ok, " + userNameConfirm + " Password Please :");
print("Note : It is completely Random ! Don't write any Strange Characters or Numbers You will get an error !");
String pass = input.nextLine();
print("confirm :");
String confirmPass = input.nextLine();
if(pass == confirmPass) {print("Well, there are nothing to write !");} else if(pass != confirmPass) {print("Not similar to your previous password !");}
} else if(userName != userNameConfirm){
print("You cannot Login Using this different user names.");
}
}
private static void print(String text) {
System.out.println(text);
}
}
我想告诉您,当您确认用户名实际上相同时,两个Scanner字符串之间的比较是怎么回事(我在Java中不是,但是),但是如果执行此操作,您将无法跳过其他if语句! 对不起,英语不好!