gpt4 book ai didi

java - 使用冒泡法对数组进行升序排序。其他数组则位于不同的索引处

转载 作者:行者123 更新时间:2023-12-02 02:10:14 25 4
gpt4 key购买 nike

该程序假设读取包含商品、代码和价格的文件。我将其输出到屏幕上其在数组中表示的索引。例如 Item[0]、Code[0] 、Price[0] 贯穿每个可能的索引。该程序假设使用冒泡排序方法对 Code 值从小到大进行排序。到目前为止我已经得到了正确的结果。我的问题是如何让所有三个变量都到达那里。例如,如果 wine 、1298、8.99 都在各自的索引 [3] 中,那么当将 Code 值放入冒泡排序时,它会交换到索引 [0]。如何让价格和商品的索引也切换到索引[0]。这是我的问题。到目前为止,我们刚刚在类里面学习了基本的java,所以我还不知道任何高级的东西。

import java.io.File;
import java.util.Scanner;
import java.util.*;

public class test2 {

public static void main(String[] args) throws Exception {

File file = new File("C:\\Users\\Isiah\\Desktop\\xfiles.txt");
Scanner input = new Scanner(file);

System.out.println("Item \t Code \t Price");

String[] Item = new String[7];
int[] Code = new int[7];
double[] Price = new double[7];

int c = 0;
while (input.hasNext()) {
Item[c] = input.next();
Code[c] = input.nextInt();
Price[c] = input.nextDouble();
System.out.println(Item[c] + "\t" + Code[c] + "\t" + Price[c]);
c++;

}
input.close();

// Call Bubble Method

bubbleSort(Code, Item, Price);

System.out.println(" ");
System.out.println("Code \t Item \t Price");



for (int i = 0; i < Item.length; i++) {
System.out.println(Code[i]);



}
}

// Bubble Sort Method
static void bubbleSort(int Code[], String[] Item, double Price[]) {
int n = Code.length;
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - i - 1; j++)
if (Code[j] > Code[j + 1]) {
// swap temp and score[i]
int temp = Code[j];
Code[j] = Code[j + 1];
Code[j + 1] = temp;

}
}
}




Item Code Price
beer 1357 12.99
apple 2357 0.5
bread 2123 1.25
wine 1298 8.99
pants 3009 6.99
sugar 2111 2.69
socks 3123 11.89

Code Item Price
1298
1357
2111
2123
2357
3009
3123

最佳答案

使用当前代码,您必须交换所有数组中的项目。因此,当您交换 Code[i]Code[j] 时,也交换 Item[i]Item[j] 价格[i]价格[j]

一种更面向对象的方法是定义一个带有 CodeItemPrice 字段的类,例如 Thing :

class Thing {
int code;
String item;
double price;
}

然后对其中的数组进行排序:Thing[]

关于java - 使用冒泡法对数组进行升序排序。其他数组则位于不同的索引处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50124776/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com