[英]comparison of java scanner string
我是Java編程的新手,我想在if語句中比較Java掃描程序字符串。 我怎樣才能做到這一點?
這就是我這樣做的方式,但是沒有給我我期望的輸出:
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的代碼。
op.equals("+")
.. .equals()
是在Java中比較兩個字符串的序數相等性的方法。
因此,您的代碼應如下所示:
if ("+".equals(op))
{
System.out.println("Answer is: "+fnum+snum);
}
==
將比較的兩個引用String
對象中,而不是內容String
對象
謝謝,但是如果我們有兩個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語句! 對不起,英語不好!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.