我试图为我的Java类创建一个简短的程序,要求我计算一个玩家的击球平均值。出于某种原因,当我去除两个变量时,即使用户输入数据,我也得到0.0。我添加了print语句来尝试调试我的代码但数字在用户输入后出现,但是当我将它们传递给battingAvg时它们并没有分开。其他人可以发现我的错误吗?
import java.util.Scanner;
public class Problem42 {
public static void main(String[] args) {
//Keyboard input for hits & number of at-bats
Scanner numberOfHits = new Scanner( System.in);
System.out.print("How many hits does the batter have?");
int hits = numberOfHits.nextInt();
System.out.println(hits);
Scanner numberOfBats = new Scanner( System.in);
System.out.print("What is the batters number of at-bats?");
int atBats = numberOfBats.nextInt();
// Calculating the batting average
double battingAvg = (hits) / (atBats);
System.out.println(battingAvg);
//Eligibility for the All Stars Game
if (battingAvg > .300) {
System.out.println("Player is eligible for All Stars Game.");
} else {
System.out.println("Player is ineligible for All Stars Game.");
}
numberOfHits.close();
numberOfBats.close();
}
}
答案 0 :(得分:-1)
double battingAvg = (hits) / (atBats);
由于hits
和atBats
是整数,因此会发生整数除法。将其中任何一个加倍以获得double
结果。
double battingAvg = hits / (double)atBats;