Arrays.sort()在Java中无法正常工作

huangapple go评论93阅读模式
英文:

Arrays.sort() not functioning properly in java

问题

// 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("3[H3[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");

            // ... (omitting the rest of the code for brevity)
            // ... (the provided code mainly deals with user input, seat assignments, and sorting)

            // 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]);
                }

                // ... (omitting the continuation of user input and program exit logic)
            } else {
                // ... (omitting the continuation of user input and program exit logic)
            }
        }
    }
}
英文:

so I have the following ClassSeat program where I have to automatically assign seats to students and sort their names alphabetically. I do not know if the sorting of the names is working properly in alphabetical order, my output does not seem to match my expected output. I have to use Arrays.sort() to sort out the names but here is what my output looks like:

My output:

Select Your Class Size!

A 6x5 Classroom or a 3X10 classroom?
 Enter &#39;6x5&#39; or &#39;3x10&#39; 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

Expected Output:

Select Your Class Size!

A 6x5 Classroom or a 3X10 classroom?
 Enter &#39;6x5&#39; or &#39;3x10&#39; 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

Why is not sorting the names properly?

Code:

 // 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(&quot;\033[H\033[2J&quot;);
System.out.flush();
// Create scanner object
Scanner inp = new Scanner(System.in);
// Create print statements
System.out.println(&quot;Select Your Class Size!\n&quot;);
System.out.println(&quot;A 6x5 Classroom or a 3X10 classroom?\n Enter &#39;6x5&#39; or &#39;3x10&#39; please!\n&quot;);
// Create variables to be used in the print statements 
String Class1 = &quot;6x5&quot;;
String Class2 = &quot;3x10&quot;;
// Create a double array variable with the limit of 1 so that it can be used to recognize the &quot;x&quot; 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 &quot;x&quot; in the selectClassSize variable
int indexOfx = selectClassSize.indexOf(&#39;x&#39;);
// Create a counter variable to count/find the &quot;x&quot;
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 &quot;x&quot; 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 &quot;x&quot; in the string 
input[xcount] = Double.parseDouble(selectClassSize.replace(&quot;x&quot;, &quot;&quot;));
// Create print statements 
System.out.println(&quot;\nOk, so you have selected &quot; + Class1);
System.out.println(&quot;Your classroom size looks like this:\n&quot;);
// 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 &lt; classSize[0].length; i++){
for(int j = 0; j &lt; classSize.length; j++){
System.out.print(&quot;X&quot;);
}
System.out.println();
}
xcount++;
// Otherwise, do the same thing for 3x10 classSize
} else {
System.out.println(&quot;\nOk, so you have selected &quot; + Class2);
System.out.println(&quot;Your classroom size looks like this:\n&quot;);
// 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 &lt; classSize2[0].length; x++){
for(int y = 0; y &lt; classSize2.length; y++){
System.out.print(&quot;X&quot;);
}
System.out.println();
}
}
// Create a print statement
System.out.println(&quot;\nNow Enter The Number Of Students!&quot;);
// 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(&quot;\nEnter the first names of the &quot; + numOfStudents + &quot; students!\n&quot;);
// 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(&quot;StudentNames&quot;);
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 &quot;StudentNames&quot;
for (int x = 0; x &lt; numOfStudents; x++) {
names[x] = inp.next();
// if &quot;x&quot; is validated to be found, basically call this boolean from before that checks the possiblity of &quot;x&quot;
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 &gt;= 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 &gt;= 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] = &quot;(&quot;+Integer.toString(column)+&quot;)&quot; + &quot;(&quot;+Integer.toString(++row)+&quot;)&quot;;
// Write it onto the textfile called &quot;StudentNames&quot;
bw.write(names[x]+&quot; Seat Location: &quot;+seats[x]);
bw.newLine();
}
bw.close();
fw.close();
// Catch any errors
} catch (Exception e) {
System.out.println(&quot;An Error Occured!&quot;);
}
// Create another try-catch block to read the file 
try {
// Initialize the new objects
FileReader fr = new FileReader(&quot;StudentNames&quot;);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
// Create a print statement 
System.out.println(&quot;\nThe Names And Seat Location Of The Student Are As Follows:\n&quot;);
// 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(&quot;An Error Occured!&quot;);
}
// Create a print statement 
System.out.println(&quot;\nDo You Want To Assign Seats By Alphabetical Order? (y/n)\n&quot;);
// Allow the user to type &quot;y&quot; or &quot;n&quot; to see the names sorted in alphabetical order
String letter = inp.next();
// start a if statement for the input &quot;y&quot; and sort the names using Arrays.sort();
if (letter.equals(&quot;y&quot;)){
Arrays.sort(names); // Use Arrays.sort() function
// Use a for loop to print the names in alphabetical order
for (int x = 0; x &lt; numOfStudents; x++){
System.out.println(names[x]+&quot; Seat Location: &quot;+seats[x]);
}
// Create a print statement
System.out.println(&quot;\nExit The Program? (y/n)\n&quot;);
// Allow the user to type out &quot;y&quot; or &quot;n&quot; to exit the program
String enter3 = inp.next();
// Use an if statement to break the program 
if (enter3.equals(&quot;y&quot;)){
break;
}else{
continue;
}
// if the user types &quot;n&quot; as they do not want to see the names in an alphabetical order, then the user can exit the program
}else{
System.out.println(&quot;\nExit The Program? (y/n)\n&quot;);
String enter2 = inp.next();
if (enter2.equals(&quot;y&quot;)){
break;
}else{
continue;
}
}
}
}
}

答案1

得分: 1

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

String enter2;
do {
// 清屏
System.out.print("\033[H\033[2J");
System.out.flush();
// 创建扫描器对象
Scanner inp = new Scanner(System.in);
// ...在这里放入剩余的代码行
System.out.println("\n退出程序吗?\n");
enter2 = inp.next();
if (enter2.equals("y")) {
System.out.println("\n祝您有美好的一天!\n");
break;
}
} while (enter2.equalsIgnoreCase("n"));
英文:

You need to put the whole code inside a loop as shown below:

String enter2;
do {
// Clear the screen
System.out.print(&quot;\033[H\033[2J&quot;);
System.out.flush();
// Create scanner object
Scanner inp = new Scanner(System.in);
// ...put here the remaining lines of code
System.out.println(&quot;\nExit The Program?\n&quot;);
enter2 = inp.next();
if (enter2.equals(&quot;y&quot;)) {
System.out.println(&quot;\nHave A Nice Day!\n&quot;);
break;
}
} while (enter2.equalsIgnoreCase(&quot;n&quot;));

答案2

得分: 0

基本上这是不可能的,但它在某种程度上是可能的。

一旦您的程序退出,它就没有办法再去执行任何操作,因为它不再运行。但是您可以在初始程序实例结束之前启动一个新的程序实例。您可以通过执行操作系统命令来实现这一点。要执行命令,您可以使用例如 ProcessBuilder

以下是一个示例,展示了这种代码的样子:

链接:https://stackoverflow.com/questions/4159802/how-can-i-restart-a-java-application

如果您不想重启整个程序,而只是想重新运行您的例程,您可以采纳 @Arvind 的建议。

英文:

Essentially this is not possible, but it is kind of possible.

Once your program has quit, there is no way it can still do something, because it does not run anymore. But you can initiate a new program instance right before the initial program instance ends. You do so by executing an OS command. To execute a command you can use e.g. the ProcessBuilder.

Here is an example what such code will look like:

https://stackoverflow.com/questions/4159802/how-can-i-restart-a-java-application

If you do not want to restart the whole program, but merely rerun your routine, you can follow the advice by @Arvind.

huangapple
  • 本文由 发表于 2020年10月27日 02:16:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/64542767.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定