java - 错误 : incompatible type when trying to use compareTo to compare one string to another

标签 java bluej

这是我接受 50 个名字和卷号的代码。并按字母顺序打印它们。它为 if(name[j].compareTo(small)) 提供错误类型不兼容

import java .io.*;
class student
{
    public void main()throws IOException
    {
      BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
      String name[]=new String[50];
      int mark[]=new int[50];
      int i;
      for( i=0;i<=49;i++)
      {
        System.out.println("plz ntr d name of d studnt");
        name[i]=br.readLine();
        System.out.println("plz ntr d marks of d studnt");
        mark[i]=Integer.parseInt(br.readLine());
        int j,pos=0;
        String temp, small;
        for(i=0;i<49;i++)
        {
          small=name[i];
          pos=i;
          for(j=i+1;j<49;j++)
          {
            if(name[j].compareTo(small))
              pos=j;
          }
        }
        temp=name[i];
        name[i]=name[pos];
        name[pos]=temp;
      }
      for(i=0;i<=49;i++)
      {
        System.out.println((i+1)+" "+name[i]+" "+mark[i]);
      }
    }
 }

最佳答案

compareTo 返回一个 int 而不是 boolean

你想要的是:

if(name[j].equals(small)) {

编辑此外,您应该检查是否为空:

if (name[j] != null && name[j].equals(small)) {

关于java - 错误 : incompatible type when trying to use compareTo to compare one string to another,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8804850/

相关文章:

java - Eclipse:在调试期间自动加载 html/JS 更改

java - 添加对 war build 的额外依赖

java - BigDecimal 中的 setcal

java - 如何通过android应用程序发送短信?

java - 如何使用 JPA 和实体对象生命周期

java - 如何正确使用Java中的add方法?

java - BlueJ 和键盘输入

java - 有什么简单的方法来处理这个java游戏中的ConcurrentModificationException吗?

java - 如何迭代字符串列表以将每个单词的最后一个字母更改为大写?

java - 使用数组而不是ArrayList。用户必须写入数组提供的确切数据数。