Java百分比计算以及显示方法“以掷硬币实验为例”

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/Hollen0318/article/details/102743241

以掷硬币为例的百分比计算示例

import java.io.*; 
import java.util.Scanner;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class Q7 {

	public static void main(String[] args)
			throws FileNotFoundException {//寻找不到文件
		// TODO Auto-generated method stub 
		Scanner input = new Scanner (new File("/Users/apple/Documents/Class Folders/Java/Lab6/Q7.txt"));//这里是读取了文件
		while(input.hasNextLine()) {
			int heads= 0;
			int count = 0;
			String line = input.nextLine();
			Scanner lineScan = new Scanner (line);
			while(lineScan.hasNext()) {
			String wOrd = lineScan.next();
			String word = wOrd.toLowerCase();
			if (word.equals("h")) {
				heads++;
				count++;
			}else if(word.contentEquals("t")){
				count++;
			}
			}
			String result = percent(heads,count);
			System.out.println(heads+" heads("+result+")");
			if((2*heads)>=count) {
				System.out.println("You win!");
	
			}
			System.out.println();
			}
	}
		public static String percent (int d,int e) {
		double result = (double)d/e;	
		DecimalFormat nf = (DecimalFormat)NumberFormat.getPercentInstance();
		nf.applyPattern("0.0%");
		nf.setMaximumFractionDigits(1);
		return nf.format(result);
		}
}


猜你喜欢

转载自blog.csdn.net/Hollen0318/article/details/102743241
今日推荐