2015-12-19 71 views
-2

我正在嘗試編寫一些代碼來驗證用戶的行條目。我需要確保用戶輸入了「:」,因爲這是行分隔符,但是我收到錯誤。包含的數據類型錯誤

這是錯誤:

The method contains(CharSequence) in the type String is not applicable for the arguments (char)

有沒有什麼辦法可以解決這個問題?

import java.util.Scanner; 
import java.lang.*; 
public class REQ2 
{ 
    public static void main (String[] args) 
    { 

    String playername;  
    String line; 
    String[] list = new String[100]; 
    int count = 0; 
    int score; 
    int time; 
    int totalScore =0; 

    Scanner sc = new Scanner(System.in); 


     System.out.println("Please enter your name"); 

     playername = sc.nextLine(); 

     if(playername.equals("")) 
     { 
      System.out.println("Player name was not entered please try again"); 
      System.exit(0); 
     } 

     System.out.println("Please enter your game achivements (Game name:score:time played) E.g. Minecraft:14:2332"); 

     while (count < 100){ 

      line = sc.nextLine(); 

      if(line.equals("quit")){ 
        break; 
        } 

      if(!(line.contains(':'))){ //error on this line 
       System.out.println("Please enter achivements with the proper \":\" sepration\n"); 
      } 

      list[count]=line; 
      System.out.println("list[count]" + list[count]); 

      count++; 

     for (int i=0; i<count; i++){ 
      line=list[i]; 
      String[] elements =line.split(":"); 

      if (line.length() !=3){ 
       System.out.println("Error please try again, Please enter in the following format:\nGame name:score:timeplayed"); 
        break; 
     } 

      score = Integer.parseInt(elements[1].trim());   
      time=Integer.parseInt(elements[2].trim()); 


       } 

      } 
     } 

} 
+1

一個'char'不是'CharSequence',所以你不能傳遞一箇中,而是傳遞一個'String' :'if(!line.contains(「:」)){' – azurefrog

回答

1

你性格需要在雙引號使其成爲字符串

":" 
5

,而不是

if(!(line.contains(':'))){ //error on this line 

使用

if(!(line.contains(":"))){ //error on this line 

由於從字符串Java文檔

contains
public boolean contains(CharSequence s)
Returns true if and only if this string contains the specified sequence of char values.
Parameters:
s - the sequence to search for
Returns:
true if this string contains s, false otherwise

如果你看到的source code contains方法

Returns true if and only if this string contains the specified sequence of char values. Parameters: s the sequence to search for Returns: true if this string contains s, false otherwise Throws: NullPointerException if s is null Since: 1.5

2114 public boolean More ...contains(CharSequence s) { 
2115  return indexOf(s.toString()) > -1; 
2116 } 
+0

如果解決方案幫助您解決問題,請將解決方案標記爲「已接受」 – Naruto