我的任务要求我编写一个简单的 Java 程序来盘点计算机软件。设计一个程序,让用户输入软件名称和库存数量。
然后程序应该对项目进行排序,以便记录按库存数量排序,并按数字顺序显示所有记录。
我必须使用两种方法!一种获取用户输入并存储在数组中的方法,以及一种按从小到大排序并显示的方法!
这是我的代码。我不确定下一步该怎么做。我不确定如何使用selection sort对其进行排序,但这就是我需要使用的。那里的那个是我从一堂课中使用的!我确定displayInfo方法是错误的,因为我不知道如何初始化inputInfo方法中尚未使用的任何变量(我需要数组和东西)。当我在 main 中调用displayInfo方法时它不起作用。
我希望这是有道理的。真的不知道怎么解释...
请帮忙!
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
public class ComputersRUs {
public static void inputInfo() throws IOException
{
BufferedReader userInput = new BufferedReader (new InputStreamReader(System.in));
System.out.print("How many softwares would you like to input? ");
String software = userInput.readLine();
int softwareNum = Integer.parseInt(software);
int[] softArray = new int[softwareNum];
String [] name = new String [softwareNum];
int [] quantity = new int[softwareNum];
//loop through number of softwares
for (int i = 0; i < softwareNum; i++)
{
System.out.println("Input name of software: ");
String softwareName = userInput.readLine();
name[i] = softwareName;
System.out.println("Input quantity of software: ");
String quantityString = userInput.readLine();
int softwareQuantity = Integer.parseInt(quantityString);
quantity[i] = softwareQuantity;
System.out.println("There are " + quantity[i] + " of the " + name[i] + " software.");
}
}
//method to sort and display info
public static void displayInfo(int[] arr)
{
//sort by quantity
for(int i=0; i<arr.length; i++)
{
for(int j=i+1; j<arr.length; j++)
{
if(arr[i] > arr[j] )
{
int temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
//output
for(i=0; i<=arr.length; i++)
{
System.out.println(arr[i] + " ");
}
}
}
//main
public static void main(String[] args) throws IOException {
//input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//loop to stop when user requests
String quit = "n";
while("n".equals(quit))
{
//display menu
System.out.println("'COMPUTERS R US' Software Inventory - Main Menu");
System.out.println("1) Input information");
System.out.println("2) Display information in order");
System.out.println("3) Quit program");
System.out.print("Please choose an option by inputting the number of your choice: ");
String choiceString = br.readLine();
int choice = Integer.parseInt(choiceString);
if(choice == 1)
{
inputInfo();
}else if(choice == 2)
{
displayInfo();
}else if(choice == 3)
{
System.out.println("Are you sure you want to quit? (y/n) ");
quit = br.readLine();
}else
{
System.out.println("Not a valid option.");
}
}
}
}
谢谢!