英文:
Sorting arrays from lowest to highest numbers with ratios using methods in Java
问题
我正在编写一个程序,该程序接收配料的数量。程序如下:
import java.util.Scanner;
public class Restaurant {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int count = scan.nextInt();
}
}
英文:
I am writing a program that takes in the number of ingredients. The prog
This is my code:
import java.util.Scanner;
public class Restaurant {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int count = scan.nextInt();
}
答案1
得分: 0
将这个sortCalories函数更改为以下方式。还需要将价格数组作为第二个参数传递,就像这样:sortCalories(calories, price, ingredientName);
:
public static void sortCalories(double[] calories, double[] price, String[] ingredientName) {
double temp;
String temp1;
for (int p = 0; p < calories.length; p++) {
for (int j = p + 1; j < calories.length; j++) {
if (calories[p] / price[p] > calories[j] / price[j]) {
temp = calories[p];
calories[p] = calories[j];
calories[j] = temp;
temp = price[p];
price[p] = price[j];
price[j] = temp;
temp1 = ingredientName[p];
ingredientName[p] = ingredientName[j];
ingredientName[j] = temp1;
}
}
}
}
英文:
Change this sortCalories function to the one below. Also you need to pass price array as second parameter like this sortCalories(calories,price, ingredientName);
:
public static void sortCalories(double[] calories,double[] price, String[] ingredientName) {
double temp;
String temp1;
for (int p=0; p<calories.length; p++) {
for (int j=p+1; j<calories.length; j++) {
if(calories/price
>calories[j]/price[j]) {
temp = calories
;
calories
= calories[j];
calories[j] = temp;
temp = price
;
price
= price[j];
price[j] = temp;
temp1 = ingredientName
;
ingredientName
= ingredientName[j];
ingredientName[j] = temp1;
}
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论