【问题标题】:Arrays.sort() not functioning properly in javaArrays.sort() 在 java 中无法正常运行
【发布时间】:2021-02-09 01:02:00
【问题描述】:

所以我有以下 ClassSeat 程序,我必须自动为学生分配座位并按字母顺序对他们的姓名进行排序。我不知道名称的排序是否按字母顺序正常工作,我的输出似乎与我的预期输出不匹配。我必须使用 Arrays.sort() 来整理名称,但我的输出如下所示:

我的输出:

Select Your Class Size!

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

3x10

Ok, so you have selected 3x10
Your classroom size looks like this:

XXX
XXX
XXX
XXX
XXX
XXX
XXX
XXX
XXX
XXX

Now Enter The Number Of Students!
8

Enter the first names of the 8 students!

Hussain
Omer
Zebra
Animal
here
k
l
m

The Names And Seat Location Of The Student Are As Follows:

Hussain Seat Location: (1)(1)
Omer Seat Location: (1)(2)
Zebra Seat Location: (1)(3)
Animal Seat Location: (2)(1)
here Seat Location: (2)(2)
k Seat Location: (2)(3)
l Seat Location: (3)(1)
m Seat Location: (3)(2)

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

y
Animal Seat Location: (1)(1)
Hussain Seat Location: (1)(2)
Omer Seat Location: (1)(3)
Zebra Seat Location: (2)(1)
here Seat Location: (2)(2)
k Seat Location: (2)(3)
l Seat Location: (3)(1)
m Seat Location: (3)(2)

Exit The Program? (y/n)

y

预期输出:

Select Your Class Size!

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

3x10

Ok, so you have selected 3x10
Your classroom size looks like this:

XXX
XXX
XXX
XXX
XXX
XXX
XXX
XXX
XXX
XXX

Now Enter The Number Of Students!
8

Enter the first names of the 8 students!

Hussain
Omer
Zebra
Animal
here
k
l
m

The Names And Seat Location Of The Student Are As Follows:

Hussain Seat Location: (1)(1)
Omer Seat Location: (1)(2)
Zebra Seat Location: (1)(3)
Animal Seat Location: (2)(1)
here Seat Location: (2)(2)
k Seat Location: (2)(3)
l Seat Location: (3)(1)
m Seat Location: (3)(2)

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

y
Animal Seat Location: (1)(1) omer zebra
here Seat Location: (1)(2)
Hussain Seat Location: (1)(3)
k Seat Location: (2)(1)
l Seat Location: (2)(2)
m Seat Location: (2)(3)
omer Seat Location: (3)(1)
zebra Seat Location: (3)(2)

Exit The Program? (y/n)

y

为什么名称排序不正确?

代码:

 // Import util packages
import java.util.*;

// Import io packages 
import java.io.*;

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

    // Create a while loop so that once the user wants to exit the program, the loop breaks, and if the user does not want to exit the program, the program restarts
    while(true){
    
    // Clear the screen
    System.out.print("\033[H\033[2J");
    System.out.flush();

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

    // Create print statements
    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");

    // Create variables to be used in the print statements 
    String Class1 = "6x5";
    String Class2 = "3x10";

    // Create a double array variable with the limit of 1 so that it can be used to recognize the "x" in the string 
    Double input[] = new Double[1];

    // Allow the user to choose what classSize they would like
    String selectClassSize = inp.next();

    // Creat an indexofx to find the "x" in the selectClassSize variable
    int indexOfx = selectClassSize.indexOf('x');
    
    // Create a counter variable to count/find the "x"
    int xcount = 0;

    // Create a boolean variable that has the requirements in it, and finds the first index and the last index
    // Subtract 2 from the length because "x" will be located in the middle of a 3 word string
    boolean containsx = indexOfx == 0 || indexOfx == (selectClassSize.length() - 2);

    // Validate x at beginning or end 
    if (containsx) {

      // Use the double array and counter to find the "x" in the string 
      input[xcount] = Double.parseDouble(selectClassSize.replace("x", ""));
      
      // Create print statements 
      System.out.println("\nOk, so you have selected " + Class1);
      System.out.println("Your classroom size looks like this:\n");

      // Initialize variables to use in the for loop, start with the 6x5 classSize
      int rows = 6;
      int columns = 5;

      // Create a multi-dimensional array to include both the rows and columns
      int classSize[][] = new int [rows][columns];
      
      // Create a for loop to print a visual representation of the 6x5 classSize
      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++;

    // Otherwise, do the same thing for 3x10 classSize
    } else {
      System.out.println("\nOk, so you have selected " + Class2);
      System.out.println("Your classroom size looks like this:\n");

      // Initialize variables to use in the for loop, but this time for the 3x10 classSize
      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 print statement
    System.out.println("\nNow Enter The Number Of Students!");

    // Create a scanner variable to allow the user to enter the number of students in the class 
    int numOfStudents = inp.nextInt();

    // Create a print statement 
    System.out.println("\nEnter the first names of the " + numOfStudents + " students!\n");

    // Initialize String array variables to be used in the for loop and inside the try-catch block 
    String[] names = new String[numOfStudents];
    String[] seats = new String[numOfStudents];

     try {

      // Initialize the new objects
      FileWriter fw = new FileWriter("StudentNames");
      BufferedWriter bw = new BufferedWriter(fw);
      
      // Create int variables to output the seat location 
      int row = 0;
      int column = 1; 
      
      // Use a for loop to allow the user to enter names, and the program to assign seats automatically, save both the information in a new textfile called "StudentNames"
      for (int x = 0; x < numOfStudents; x++) {
          names[x] = inp.next();

          // if "x" is validated to be found, basically call this boolean from before that checks the possiblity of "x"
          if(containsx) {

              // For the 6x5 classSize, if row is greater than 6 or equal to 6, start a new row and count the number of columns, accordingly 
              if(row >= 6) {
                  column++;

                  // Set row to 0
                  row = 0;
              }
          }

          // Otherwise, for the 3x10 classSize, if the row if greater or equal to 3, then start a new row and count the number of columns, accordingly
          else {
              if(row >= 3) {
                  column++;

                  // Set row to 0
                  row = 0;
              }
          }

          // Assign a array, and use Integer.toString to return the String with a specified Integer parameter (column) and (rows)
          seats[x] = "("+Integer.toString(column)+")" + "("+Integer.toString(++row)+")";

          // Write it onto the textfile called "StudentNames"
          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!");
    }

    // Create another try-catch block to read the file 
     try {

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

      String line = br.readLine();

      // Create a print statement 
      System.out.println("\nThe Names And Seat Location Of The Student Are As Follows:\n");
      
      // Start a while loop to output the data from the file
      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!");
    }

    // Create a print statement 
    System.out.println("\nDo You Want To Assign Seats By Alphabetical Order? (y/n)\n");

    // Allow the user to type "y" or "n" to see the names sorted in alphabetical order
    String letter = inp.next();

      // start a if statement for the input "y" and sort the names using Arrays.sort();
      if (letter.equals("y")){
        Arrays.sort(names); // Use Arrays.sort() function

        // Use a for loop to print the names in alphabetical order
        for (int x = 0; x < numOfStudents; x++){
        System.out.println(names[x]+" Seat Location: "+seats[x]);
        }
        
        // Create a print statement
        System.out.println("\nExit The Program? (y/n)\n");
        
        // Allow the user to type out "y" or "n" to exit the program
        String enter3 = inp.next();

        // Use an if statement to break the program 
        if (enter3.equals("y")){
          break;
      }else{
        continue;
      }

        // if the user types "n" as they do not want to see the names in an alphabetical order, then the user can exit the program
        }else{
        System.out.println("\nExit The Program? (y/n)\n");
        String enter2 = inp.next();
        if (enter2.equals("y")){
          break;
        }else{
          continue;
        }
      }
    }
  }
}

【问题讨论】:

  • 您应该针对全新的要求发布一个新问题。您编辑的问题与原始问题没有任何关系;如何证明现有的答案是合理的?
  • 我会这样做,但由于我必须在大约 20 分钟内提交此作业,因此我必须等待 1 小时 30 分钟才能发布新问题。这就是为什么。对此感到抱歉

标签: java arrays sorting multidimensional-array restart


【解决方案1】:

您需要将整个代码放入循环中,如下所示:

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

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

    // ...put here the remaining lines of code

    System.out.println("\nExit The Program?\n");
    enter2 = inp.next();
    if (enter2.equals("y")) {
        System.out.println("\nHave A Nice Day!\n");
        break;
    }
} while (enter2.equalsIgnoreCase("n"));

【讨论】:

  • 您好 Arvind,感谢您的回答!但是我在一开始就包含了一个 while 循环,当用户输入 y 退出程序并使用 Continue 时,我打破了循环;当他们想留在节目中时。我还有一个问题:我按字母顺序排列的名字似乎不能正常工作,你能看看我更新的代码吗?提前致谢!
【解决方案2】:

这基本上是不可能的,但它是可能的

一旦您的程序退出,它就无法继续某事,因为它不再运行。但是您可以在初始程序实例结束之前启动一个新程序实例。您可以通过执行操作系统命令来做到这一点。要执行命令,您可以使用例如ProcessBuilder

以下是此类代码的示例:

How can I restart a Java application?

如果您不想重新启动整个程序,而只是重新运行您的例程,您可以按照 @Arvind 的建议进行操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-06
    • 2013-07-29
    • 2020-08-07
    • 1970-01-01
    • 2016-02-17
    • 2010-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多