so i'm created a program that display the name and grade of students from a file, and also a boolean that checks to see if the names are in alphabetical order. The problem is that i've created a files that has a name in alphabetical order but it still returns false

class Assignment
{
//------------------------------------------------------------------------------
   public static void main (String [] args) throws Exception
   {
      Scanner kb = new Scanner(System.in);

      System.out.print("\nEnter name of a file of Students: ");
      String filename = kb.nextLine();

      Section sec = new Section(filename);

      System.out.println("\nIn forward order:");
      sec.print(System.out);

      System.out.println("\nhasNamesAscending() --> " +
                         sec.hasNamesAscending());
   } 
//------------------------------------------------------------------------------
} // end class Assignment
////////////////////////////////////////////////////////////////////////////////
class Section
{
   private String filename;
//-----------------------------------------------------------------------
   public Section ( String filename )
   {
      this.filename = filename;
   }
//-----------------------------------------------------------------------
   public void print ( PrintStream ps ) throws Exception
   {
      Scanner sc = new Scanner(new File(filename));

      while ( sc.hasNext() )
      {
         Student s = Student.read(null,sc);
         ps.println(s);
      }
   }
//-----------------------------------------------------------------------
	public boolean hasNamesAscending() throws Exception
	{
		Scanner sc = new Scanner(new File(filename));
		
		if (!sc.hasNext()) return true;
		
		char lastN = sc.nextLine().charAt(0);
		
		while (sc.hasNext())
		{
			char firstN = sc.nextLine().charAt(0);
			if(!firstN.equals(lastN)) return false;
		}
		return true;
	}
//-----------------------------------------------------------------------
} // end class Section
/////////////////////////////////////////////////////////////////////////

In my first look I found that firstN and lastN are of char type ,not in looking in the logic, so try using (==) instead of equals
good luck

I've fixed my code and it looks a lil better but there is still the issue of having the false as a result when it's not

public boolean hasNamesAscending() throws Exception
	{
		Scanner sc = new Scanner(new File(filename));
		
		if (!sc.hasNext()) return true;
		int last = sc.nextLine().compareTo(sc.nextLine());
		while (sc.hasNext())
		{		
			int next = sc.nextLine().compareTo(sc.nextLine());;
			if( next < last)return false;
			
			last = next;
		}
		return true;
	}
This article has been dead for over six months. Start a new discussion instead.