包含中的数据类型错误

时间:2015-12-19 20:57:56

标签: java

我正在尝试编写一些代码来验证用户的行条目。我需要确保用户输入了“:”,因为这是行分隔符,但是我收到了错误。

这是错误:

  

String类型中包含(CharSequence)的方法不适用于参数(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());


               }

           }
      }

 }

2 个答案:

答案 0 :(得分:5)

而不是

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

使用

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

来自String java doc

  

包含
  public boolean contains(CharSequence s)
  当且仅当此字符串包含指定的char值序列时,才返回true   的参数
  s - 搜索的序列   的返回
  如果此字符串包含s,则返回true,否则返回false

如果您看到包含方法的source code

  

当且仅当此字符串包含指定的字符串时,才返回true   char值序列。参数:s要搜索的序列   返回:如果此字符串包含s,则返回true,否则返回false抛出:   如果s为null,则为NullPointerException   1.5

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

答案 1 :(得分:1)

你的角色需要用双引号才能成为一个字符串

":"