2016-04-11 65 views
1

我是一個在網上練習的程序員在線編程的小菜鳥。我目前正在研究這個練習,這需要我在用戶輸入的任何參數字符串中找到substring「rat」。我知道這可能是一個菜鳥的錯誤,但我不知道如何解決錯誤。Java錯誤:「無法找到符號」位置變量

問題:

如果我們調用的方法ratSmeller與參數「百家樂」,該方法應該返回true,如果我們的說法「墊」調用它的方法必須返回false,並且必須返回如果用單詞「rat」進行調用,則爲true。現在你可以假設「鼠」總是以小寫字母出現。

import java.util.Scanner; 

public class Rats { 
public boolean ratSmeller(String line) { 

    boolean found; 
    String[] strArray = new String[] {line}; 
     if (strArray.indexOf("rat") != -1) { 
      found = true; 
      }else{ 
      found = false; 
      } 
      return found; 

} 

public static void main(String args[]) { 
    Scanner scanner = new Scanner(System.in); 
    System.out.println("Enter a word and we will tell you if it contains the string 'rat' in it: "); 
    String word = scanner.nextLine(); 
    Rats rats = new Rats(); 
    System.out.println("Output: "); 
    System.out.println(rats.ratSmeller(word)); 
} 
} 

我唯一的錯誤是這樣的:

Line 11 cannot find symbol if (strArray.indexOf("rat") != -1) {^symbol: method indexOf(String) location: variable strArray of type String[] 

不知道如何解決這一問題?請幫忙。謝謝!

回答

2
if (strArray.indexOf("rat") != -1) { 

這不會編譯,因爲strArray是一個Array對象。它沒有indexOf方法。 String類具有該方法。

你可能想檢查字符串是否有它。

if (line.indexOf("rat") != -1) { 

除此之外,你是過度使用變量和行String[] strArray = new String[] {line};是完全多餘的。我沒有看到任何理由刪除單個元素的數組。

+1

這是答案,我會補充說,你使用混淆你的變量命名。你的變量'word'實際上是一行文本。 –

+0

@AndrewAitken準確地說,這個陣列在這裏我不需要。這完全是多餘的。 –

0

編輯您的功能ratSmeller:

boolean found=false; 

    if (line.indexOf("rat") != -1) 
    { 
     found = true; 
    } 

    return found; 
0

陣沒有的indexOf方法。試試看,代替你的代碼。 希望它會工作 -

public boolean ratSmeller(String line) { 

boolean found; 
List<String> strArray = new ArrayList<String>(); 
strArray.add(line); 
    if (strArray.indexOf("rat") != -1) { 
     found = true; 
     }else{ 
     found = false; 
     } 
     return found; 
    } 
相關問題