2016-08-12 66 views
-1

無論我在控制檯中輸入「Y」或「N」,它總是跳入到else語句中,掃描器是否設置錯誤或者該腳本有什麼問題?更改字符串不工作的掃描器 - Java

import java.util.*; 
import java.lang.*; 
import java.io.*; 

class StartingClass { 
public static void main(String arg[]){ 

    System.out.println("The Best Encryption Bot 2016"); 

    StringBuffer passWord = new StringBuffer(); 
    Scanner input = new Scanner(System.in); 
    System.out.println("Please enter the phrase you want to encrypt: "); 
    passWord.append(input.nextLine()); 
    System.out.println("Original: " + passWord); 

    for(int i = 0; i < passWord.length(); i++) { 
     int temp = 0; 
     temp = (int)passWord.charAt(i); 
     temp = (int) (temp * 4); 
     passWord.setCharAt(i, (char)temp); 
    } 
    System.out.println("Encrypted: " + passWord); 

    System.out.println("Do you want to unencrypt a phrase ? Y/N"); 
    Scanner Encrypt = new Scanner(System.in); 
    String unencrypt = Encrypt.nextLine(); 


    if (unencrypt == "Y") { 
     StringBuffer deCrypt = new StringBuffer(); 
      Scanner deinput = new Scanner(System.in); 
      System.out.println("Please enter the phrase you want to Decrypt: "); 
      deCrypt.append(deinput.nextLine()); 
      System.out.println("Original: " + deCrypt); 

      for(int i = 0; i < passWord.length(); i++) { 
       int temp = 0; 
       temp = (int)deCrypt.charAt(i); 
       temp = (int) (temp/4); 
       deCrypt.setCharAt(i, (char)temp); 
       } 
      System.out.println("UnEncrypted: " + passWord); 
      } else { 
       System.out.println("Ok"); 
      } 

    } 

} 

的問題是在if語句,其中的解密方法== 「Y」

+0

System.in上已經有掃描儀。爲什麼要申報另一個?另一個... – Fildor

+0

你正在比較2個字符串。這應該使用'equals(String)'來完成,比如'unencrypt.equals(「Y」)' –

回答

0

的原因是因爲那不是你如何比較字符串:

使用此來比較:

if (unencrypt.equals("Y")){ 
    //do something 
} else{ 
    //do something else 
} 
0

嘗試使用unencrypt.equals("Y")而不是==