我正在做一个练习,我向用户询问10个数字(代表他们的10个最好的朋友权重。我应该说明他们输入的数字是最少的。
我对做循环有点新意,所以我尝试做一个for循环。我应该把它改成做吗?
这是我的代码。我试图制作一个先前的重量变量,如果重量小于之前的重量数,那么重量将成为新的最低重量。但我不认为它正常工作,因为它说最低的是0,所以我认为问题是以前的重量和重量变量搞砸了。
我确实看到他们被分配到相同的值,因为他们彼此相等,但我不知道如何修复它!我尝试将之前的总数放在循环的顶部,但后来我需要初始化变量,这违背了它的目的。
import java.util.Scanner;
public class ExtraProblem13 {
public static void main(String[] args) {
// TODO Auto-generated method stub
double low = 0;
double weight;
double previousWeight;
String sWeight;
Scanner input = new Scanner (System.in);
for (int i = 1; i <= 10; i ++) {
System.out.print("Enter your best friend # " + i + "'s weight: ");
sWeight = input.nextLine();
weight = Double.parseDouble(sWeight);
previousWeight = weight;
if (weight < previousWeight) {
low = weight;
}
}
input.close();
System.out.println("The lowest weight that you entered was " + low);
}
}
答案 0 :(得分:1)
您可以执行以下操作: -
Double min=0;
for (int i = 1; i <= 10; i ++) {
System.out.print("Enter your best friend # " + i + "'s weight: ");
sWeight = input.nextLine();
weight = Double.parseDouble(sWeight);
if(i==1){
min=weight;
}
else if(min>weight){
min=weight;
}
}
min将在节目结束时具有最低权重。
答案 1 :(得分:1)
<强>问题强>
您正在将 weight 的线索分配给 previousWeight ,然后再进行比较。条件if(weight&lt; previousWeight)是无用的。
<强>解决方案强>
无需使用单独的变量previousWeight。使用低存储已输入的最小数量,如果输入重量的任何较低维度,则更新它。同样使用nextDouble()而不是nextLine(),它将节省将其转换为double所需的能量:-p
<强>代码强>
import java.util.Scanner;
public class ExtraProblem13 {
public static void main(String[] args) {
// TODO Auto-generated method stub
double low;
double weight;
Scanner input = new Scanner (System.in);
low = 9999; //some large number
for (int i = 1; i <= 10; i ++) {
System.out.print("Enter your best friend # " + i + "'s weight: ");
Weight = input.nextDouble();
if (weight < low) {
low = weight;
}
}
input.close();
System.out.println("The lowest weight that you entered was " + low);
}
}
答案 2 :(得分:0)
将此与您的代码进行比较:
import java.util.Scanner;
public class ExtraProblem13 {
public static void main(String[] args) {
// TODO Auto-generated method stub
double low = Double.MAX_VALUE; // You want to set this to a high number
double weight;
Scanner input = new Scanner (System.in);
for (int i = 1; i <= 10; i ++) {
System.out.print("Enter your best friend # " + i + "'s weight: ");
weight = input.nextDouble();
if (weight < low) {
low = weight;
}
}
input.close();
System.out.println("The lowest weight that you entered was " + low);
}
}
可以应用进一步的优化,并且可以增强代码,但这超出了本问题的范围。