2016-02-26 19 views
-1

我有一個實驗室,我必須爲我的計算機類做我有一個錯誤,我似乎無法弄清楚。我收到第一個if聲明的錯誤,if(something.indexOf(x) = "a")。我想將其他if聲明更改爲該形式。陣列發生意外的類型錯誤

我得到的錯誤是:

意想不到的類型 要求:變量:發現;值

Scanner in = new Scanner(System.in); 
String[] input = new String[1000]; 
String[] output = new String[1000]; 
int x = 0;// All purpose counter 
int y = 0;//Second purpose counter 
boolean ends = false; 
boolean starts = false; 
/** 
* This method is supposed to take the dna array and create an rna array from it to return 
* to the main method wherever this method is called. 
* 
* @param String[] input  The array that contains the dna sequence 
* @return String[] output The array that contains the mRNA we just created in this method 
*/ 
public void makeRNA() 
{ 
    System.out.println("Enter a simple DNA Sequence, make sure the amount of variables are a multiple of 3."); 
    String something = in.nextLine(); 
    while(x < 1000) 
    { 
     if(something.indexOf(x) = "a") 
     { 
      output[x] = "u"; 
     } 
     else if(input[x] == "c") 
     { 
      output[x] = "g"; 
     } 
     else if(input[x] == "g") 
     { 
      output[x] = "c"; 
     } 
     else if(input[x] == "t") 
     { 
      output[x] = "a"; 
     }    
     x++; 
    } 
    for(x = 0 ; x < 1000; x++) 
    { 
     System.out.println(output[x]); 
    } 

} 

回答

3

這個問題似乎是在這裏:if(something.indexOf(x) = "a")

  • 要獲取指數x你需要使用charAt()的字符。
  • 而不是賦值運算符,您需要使用==(比較運算符)。因此charAt()返回一個字符。因此請將"a"更改爲'a'

所以,你的語句應該終於看起來像: if(something.charAt(x) == 'a')

1

if(something.indexOf(x) = "a")=是賦值運算符。除非賦值結果爲布爾值,否則在if語句中需要==運算符。

indexOf()返回int,所以你不能用"a"使用==,使用equals()字符串比較。

java if語句不能像c或C++一樣工作。

+0

然後我得到的錯誤不兼容的類型:INT和Java。 lang.String –

+0

這是因爲'indexOf()'返回一個int並且「a」是一個字符串 – Ramanlfc

+0

我猜你打算使用'.charAt()'? –

0

Ramanlfc是說使用==而不是正確的,因爲=只是一個單一的等號是賦值運算符。

但是,我不確定你的IF語句是否在做你想讓他們做的事情。 indexOf()方法返回一個整數,你試圖使用==(等於)將它與一個字符串(一個對象)進行比較。如果你想比較兩個字符串,使用.Equals()方法。你不能在對象上使用==,這是一個字符串。但是,您可以在字符上使用==,因爲它們是基本類型。要指定一個char使用單引號而不是雙引號(雙引號指定一個字符串,該字符串當前是如何設置if語句的)。我假設java將使用char的十六進制值與數字進行比較。再次,我不確定你想要達到什麼,但只是一些有用的建議!

我假設你想要的東西,像下面這樣: 如果(stringMsg.charAt(INDEXVALUE)==「A」)

這得到字符在串並檢查是否在規定值它是一樣的(等於)char a。記住字符串中的字符是數字0到(長度 - 1)。

0

問題是這行代碼:

if(something.indexOf(x) = "a") // it should be "==" instead of "=" 

正確的代碼是:

if(something.indexOf(x) == "a") 

請注意,if(something.indexOf(x) = "a") will always return true in java.

+0

你的答案不會被編譯。 'indexOf()'將返回一個'int',並且將它與'String'進行比較。 – Atri