这是我正在为我的一门课程编写的击球平均程序。
击球平均数总是小于1,因为它总是一个百分比
示例:在输入中输入时,返回.363636363
我的问题是如何将小数位设置为3,并让数字作为一个没有小数的整数出现,即363
我将平均值乘以1000,得出363.636363,但我需要输出格式仅显示363或364,因为它将四舍五入。
import java.util.*;
import java.util.Scanner;
public class Baseball{
Scanner scan = new Scanner(System.in);
private int singles, doubles, triples, homeruns, hits, atbat;
private double average;
public void getStats(String name){
System.out.print("Number of at bats: ");
atbat = scan.nextInt();
System.out.print("Singles: ");
singles = scan.nextInt();
System.out.print("Doubles: ");
doubles = scan.nextInt();
System.out.print("Triples: ");
triples = scan.nextInt();
System.out.print("Homeruns: ");
homeruns = scan.nextInt();
}
public double calcAvg(){
hits = singles + doubles + triples + homeruns;
average = ((double)hits / (double)atbat);
return average;
}
public void printAll(String name){
System.out.println("Player statistics for " + name + ":");
System.out.println("Number of at bats: " + atbat);
System.out.println("Singles: " + singles);
System.out.println("Doubles: " + doubles);
System.out.println("Triples: " + triples);
System.out.println("Homeruns: " + homeruns);
System.out.println("");
System.out.println("Total hits: " + hits);
System.out.println("Players batting average: " + (double)average*1000);
}
}
import java.util.*;
import java.util.Scanner;
class Average{
public static void main(String[]args){
Baseball player1 = new Baseball();
new Scanner(System.in);
Scanner sc = new Scanner(System.in);
String name;
System.out.println("Enter Players Name:");
name = sc.nextLine();
player1.getStats(name);
player1.calcAvg();
player1.printAll(name);
}
}