Error: incompatible type when trying to use compareTo to compare one string to another

StackOverflow https://stackoverflow.com/questions/8804850

  •  26-10-2019
  •  | 
  •  

سؤال

This is my code to accept 50 names and roll no. and print them alphabetically . It is giving error incompatible type for 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 returns an int not a boolean.

What you want is:

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

EDIT Also, you should check for null:

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

نصائح أخرى

CompateTo returns an integer, not a boolean. Your code should be something like if(name[j].compareTo(small) >1) ...

You can still use compareTo but the entire expression needs to return a boolean. An if statement requires a true or false to make its decision (not a number).

if(name[j].compareTo(small) == 0)

This is equivalent to .equals. You can also use > 0 for instance to see if name[j] is greater than small as defined by compareTo.

there are an obvious error , for instance , when the outer for loop begin , the outer i is zero, name[0] is your input , for instance 'zzzzz', the mark[0] is 3443, for example . so the inner loop begin , it begin from zero t0 49 , and make a comopare between name[0-49] and the small , that , the pre name[i]... because there are only one element in name array ... so the maybe just make a compare beteen null and other some String ... the error alose so obvious..... i think this is the main error , you can check it for yourself..... bery you .....

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top