微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Java中使用Arrays.sort对字符串变量进行排序时出错

如何解决Java中使用Arrays.sort对字符串变量进行排序时出错

当我尝试对学生的姓名进行排序时,出现一个我无法解决错误。你能看看吗?当我问用户后,我想按字母顺序对学生的姓名进行排序。

示例输入/输出

Select Your Class Size!

A 6x5 Classroom or a 3X10 classroom?
 Enter '6x5' or '3x10' please!

6x5

Ok,so you have selected 6x5
Your classroom size looks like this:

XXXXXX
XXXXXX
XXXXXX
XXXXXX
XXXXXX

Now Enter The Number Of Students!
3

Enter the first names of the 3 students!

hussain
sadra
mirisan

The Student Names Have Been Sorted In An Alphabetical Order
The Names And Seat Location Of The Student Are As Follows:

hussain Seat Location: (1)(1)
sadra Seat Location: (1)(2)
mirisan Seat Location: (1)(3)

Do You Want To Assign Seats By Alphabetical Order? (y/n)

y

hussain Seat Location: (1)(1)
mirisan Seat Location: (1)(2)
sadra Seat Location: (1)(3)

我得到NullPointerExeption却不知道为什么,而不是按照字母顺序对名称进行组织和排序。

我得到的输出

Select Your Class Size!

A 6x5 Classroom or a 3X10 classroom?
 Enter '6x5' or '3x10' please!

6x5

Ok,so you have selected 6x5
Your classroom size looks like this:

XXXXXX
XXXXXX
XXXXXX
XXXXXX
XXXXXX

Now Enter The Number Of Students!
3

Enter the first names of the 3 students!

hussain
sadra
mirisan

The Student Names Have Been Sorted In An Alphabetical Order
The Names And Seat Location Of The Student Are As Follows:

hussain Seat Location: (1)(1)
sadra Seat Location: (1)(2)
mirisan Seat Location: (1)(3)

Do You Want To Assign Seats By Alphabetical Order? (y/n)

y
Exception in thread "main" java.lang.NullPointerException
    at java.base/java.util.ComparableTimsort.countRunAndMakeAscending(ComparableTimsort.java:320)
    at java.base/java.util.ComparableTimsort.sort(ComparableTimsort.java:188)
    at java.base/java.util.Arrays.sort(Arrays.java:1249)
    at Main.main(Main.java:139)

代码

import java.util.*;
import java.io.*;


// Create a class and method
public class Main {
  public static void main(String[] args) {

    // Clear the screen
    System.out.print("\033[H\033[2J");
    System.out.flush();

    // Create scanner object
    Scanner inp = new Scanner(system.in);

    // Create a print statement
    System.out.println("Select Your Class Size!\n");
    System.out.println("A 6x5 Classroom or a 3X10 classroom?\n Enter '6x5' or '3x10' please!\n");

    String Class1 = "6x5";
    String Class2 = "3x10";

    Double input[] = new Double[1];

    String selectClassSize = inp.next();

    int indexOfx = selectClassSize.indexOf('x');
    int xcount = 0;

    boolean containsx = indexOfx == 0 || indexOfx == (selectClassSize.length() - 2);

    if (containsx) {
      input[xcount] = Double.parseDouble(selectClassSize.replace("x",""));
      
      System.out.println("\nOk,so you have selected " + Class1);
      System.out.println("Your classroom size looks like this:\n");

      int rows = 6;
      int columns = 5;
      int classSize[][] = new int [rows][columns];
      
      for(int i = 0; i < classSize[0].length; i++){
        for(int j = 0; j < classSize.length; j++){
            System.out.print("X");
      }
      System.out.println();
    }
      xcount++;

    } else {
      System.out.println("\nOk,so you have selected " + Class2);
      System.out.println("Your classroom size looks like this:\n");

      int rows2 = 3;
      int columns2 = 10;
      int classSize2[][] = new int [rows2][columns2];
        for(int x = 0; x < classSize2[0].length; x++){
          for(int y = 0; y < classSize2.length; y++){
              System.out.print("X");
      }
      System.out.println();
      }
    }

    // Create a scanner variable
    System.out.println("\nNow Enter The Number Of Students!");

    int numOfStudents = inp.nextInt();

    // Create a counter variable to count upto the numOfStudents and break the loop
    int counter = 0;

    System.out.println("\nEnter the first names of the " + numOfStudents + " students!\n");
     try {

      // Initialize the new objects
      FileWriter fw = new FileWriter("StudentNames");
      BufferedWriter bw = new BufferedWriter(fw);

      String[] names = new String[numOfStudents];
      String[] seats = new String[numOfStudents];
      
      int row = 0,column = 1;
      
      // Output the first names in the 
      for (int x = 0; x < numOfStudents; x++) {
          names[x] = inp.next();
          if(containsx) {
              if(row >= 6) {
                  column++;
                  row = 0;
              }
          }
          else {
              if(row >= 3) {
                  column++;
                  row = 0;
              }
          }
          seats[x] = "("+Integer.toString(column)+")" + "("+Integer.toString(++row)+")";
          bw.write(names[x]+" Seat Location: "+seats[x]);
          bw.newLine();
      }
      
      bw.close();
      fw.close();

      // Catch any errors
    } catch (Exception e) {
      System.out.println("An Error Occured!");
    }
     try {

      // Initialize the new objects
      FileReader fr = new FileReader("StudentNames");
      BufferedReader br = new BufferedReader(fr);

      String line = br.readLine();

      // Start a while loop to output the data from the file
      System.out.println("\nThe Student Names Have Been Sorted In An Alphabetical Order");
      System.out.println("The Names And Seat Location Of The Student Are As Follows:\n");
      
      while (line != null) {
          System.out.println(line);
          line = br.readLine();
        }
      br.close();
      fr.close();

      // Catch any errors
    } catch (Exception e1) {
      System.out.println("An Error Occured!");
    }
    System.out.println("\nDo You Want To Assign Seats By Alphabetical Order? (y/n)\n");
    String letter = inp.next();
      String[] names = new String[numOfStudents];
      if (letter.equals("y")){
        Arrays.sort(names);
        System.out.println(Arrays.toString(names));
    }
  }
}

解决方法

查看代码中的内联注释。 您应该已经在String[] names = new String[numOfStudents];块之外声明了if。这样做很好用。

import java.util.*;
import java.io.*;

public class Main
{
     public static void main(String[] args) {

    // Clear the screen
    System.out.print("\033[H\033[2J");
    System.out.flush();

    // Create scanner object
    Scanner inp = new Scanner(System.in);

    // Create a print statement
    System.out.println("Select Your Class Size!\n");
    System.out.println("A 6x5 Classroom or a 3X10 classroom?\n Enter '6x5' or '3x10' please!\n");

    String Class1 = "6x5";
    String Class2 = "3x10";

    Double input[] = new Double[1];

    String selectClassSize = inp.next();

    int indexOfx = selectClassSize.indexOf('x');
    int xcount = 0;

    boolean containsx = indexOfx == 0 || indexOfx == (selectClassSize.length() - 2);

    if (containsx) {
      input[xcount] = Double.parseDouble(selectClassSize.replace("x",""));
      
      System.out.println("\nOk,so you have selected " + Class1);
      System.out.println("Your classroom size looks like this:\n");

      int rows = 6;
      int columns = 5;
      int classSize[][] = new int [rows][columns];
      
      for(int i = 0; i < classSize[0].length; i++){
        for(int j = 0; j < classSize.length; j++){
            System.out.print("X");
      }
      System.out.println();
    }
      xcount++;

    } else {
      System.out.println("\nOk,so you have selected " + Class2);
      System.out.println("Your classroom size looks like this:\n");

      int rows2 = 3;
      int columns2 = 10;
      int classSize2[][] = new int [rows2][columns2];
        for(int x = 0; x < classSize2[0].length; x++){
          for(int y = 0; y < classSize2.length; y++){
              System.out.print("X");
      }
      System.out.println();
      }
    }

    // Create a scanner variable
    System.out.println("\nNow Enter The Number Of Students!");

    int numOfStudents = inp.nextInt();

    // Create a counter variable to count upto the numOfStudents and break the loop
    int counter = 0;

    System.out.println("\nEnter the first names of the " + numOfStudents + " students!\n");
    String[] names = new String[numOfStudents]; // -->declare it outside try{}
     try {

      // Initialize the new objects
      FileWriter fw = new FileWriter("StudentNames");
      BufferedWriter bw = new BufferedWriter(fw);

      
      String[] seats = new String[numOfStudents];
      
      int row = 0,column = 1;
      
      // Output the first names in the 
      for (int x = 0; x < numOfStudents; x++) {
          names[x] = inp.next();
          if(containsx) {
              if(row >= 6) {
                  column++;
                  row = 0;
              }
          }
          else {
              if(row >= 3) {
                  column++;
                  row = 0;
              }
          }
          seats[x] = "("+Integer.toString(column)+")" + "("+Integer.toString(++row)+")";
          bw.write(names[x]+" Seat Location: "+seats[x]);
          bw.newLine();
      }
      
      bw.close();
      fw.close();

      // Catch any errors
    } catch (Exception e) {
      System.out.println("An Error Occured!");
    }
     try {

      // Initialize the new objects
      FileReader fr = new FileReader("StudentNames");
      BufferedReader br = new BufferedReader(fr);

      String line = br.readLine();

      // Start a while loop to output the data from the file
      System.out.println("\nThe Student Names Have Been Sorted In An Alphabetical Order");
      System.out.println("The Names And Seat Location Of The Student Are As Follows:\n");
      
      while (line != null) {
          System.out.println(line);
          line = br.readLine();
        }
      br.close();
      fr.close();

      // Catch any errors
    } catch (Exception e1) {
      System.out.println("An Error Occured!");
    }
    System.out.println("\nDo You Want To Assign Seats By Alphabetical Order? (y/n)\n");
    String letter = inp.next();
      if (letter.equals("y")){
        Arrays.sort(names);
        System.out.println(Arrays.toString(names));
    }
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。