无论出于何种原因,我的变量'小时'仅存在为0.当我输入96作为距离,1作为小时,43作为分钟,我的答案是133.9英里每小时。它应该是55.9223。我为询问我确定的一个显而易见的问题而道歉,但我很早就学习了java。
import java.util.Scanner;
import static java.lang.System.*;
import static java.lang.Math.*;
public class mph
{
private double distance, hours, minutes;
private double mph;
public mph()
{
setNums(0,0,0);
mph=0.0;
}
public mph(double dist, double hrs, double mins)
{
distance=dist;
hours=hours;
minutes=mins;
}
public void setNums(double dist, double hrs, double mins)
{
dist=distance;
hrs=hours;
mins=minutes;
}
public void calcMPH()
{
hours=minutes/60; //hours is not being input, it counts as zero regardless of what's entered
mph=distance/hours;
}
public void print()
{
System.out.print((int)distance+" miles in "+(int)hours+" hours and "+(int)minutes+" minutes = "+mph+" mph.\n");
}
}
-------------------单独的文件----------------
import java.util.Scanner;
import static java.lang.System.*;
import static java.lang.Math.*;
public class mphRunner
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner(in);
out.print("Enter the distance :: ");
double dist = keyboard.nextInt();
out.print("Enter the hours :: ");
double hrs = keyboard.nextInt();
out.print("Enter the minutes :: ");
double mins = keyboard.nextInt();
mph test = new mph(dist, hrs, mins);
test.calcMPH();
test.print();
}
}
如果我以某种方式弄乱了正确的格式,我很抱歉,这是我在网站上的第一篇文章。 编辑:哦,天哪,我是个白痴。
答案 0 :(得分:0)
您要将变量hours
分配给自己而不是参数hrs
。变化
hours=hours;
到
hours=hrs;
答案 1 :(得分:0)
import java.util.Scanner;
public class Q33636764
{
private static int getData(final Scanner scanner, final String message)
{
System.out.print(message);
if (scanner.hasNextInt()) { return scanner.nextInt(); }
else
{
System.out.println("Please enter an Integer!");
return getData(scanner, message);
}
}
public static void main(final String[] args)
{
final Scanner keyboard = new Scanner(System.in);
final int dist = getData(keyboard, "Enter the distance : ");
final int hrs = getData(keyboard, "Enter the hours : ");
final int mins = getData(keyboard, "Enter the minutes : ");
final Mph mph = new Mph(dist, hrs, mins);
System.out.format("%d miles in %d hours and %d minutes %.2f mph.", dist, hrs, mins, mph.calculate());
System.out.println();
}
public static class Mph
{
private final double distance;
private final double hours;
private final double minutes;
public Mph(final double distance, final double hours, final double minutes)
{
this.distance = distance;
this.hours = hours;
this.minutes = minutes;
}
public double calculate()
{
return this.distance / this.hours + this.minutes / 60;
}
}
}
Enter the distance : 100
Enter the hours : 1
Enter the minutes : 0
100 miles in 1 hours and 0 minutes 100.00 mph.