gpt4 book ai didi

java - 如何打印与变量值对应的一组字符?

转载 作者:行者123 更新时间:2023-11-29 03:27:24 25 4
gpt4 key购买 nike

我正在尝试创建一个系统,其中有人输入 0-100 之间的数字,然后程序会将数字分配到设定的边界,基本上是一个成绩存储系统。我会向您展示我的代码,然后详细说明。

public static void main(String[] args) {
//Boundary0/30/40/70 indicates which band the counter is for. e.g. 0-29, 30-39 etc
int Boundary0 = 0;
int Boundary30 = 0;
int Boundary40 = 0;
int Boundary70 = 0;
int Grade;
int count;
count = 0;
Scanner in = new Scanner(System.in);
//Read in first number
System.out.print("Enter an Integer");
Grade = in.nextInt();



while (Grade < 100){
//To count number of students
count++;
//To allocate each grade to corresponding tier
if(Grade >= 0 && Grade <= 29){
Boundary0++;
}
if(Grade >= 30 && Grade <= 39){
Boundary30++;
}
if(Grade >= 40 && Grade <= 69){
Boundary40++;
}
if(Grade >= 70 && Grade <= 100){
Boundary70++;
}
Grade = in.nextInt();
}

//To print each boundary seperately with the number of marks in each tier and overall total

System.out.println("0-29:" + " " + Boundary0 );
System.out.println("30-39:" + " " + Boundary30);
System.out.println("40-69:" + " "+ Boundary40);
System.out.println("70-100:" + " " +Boundary70);
System.out.println("Amount of Students: " + count);
}
}

当用户输入一个数字时,程序会将相应的边界变量加1

然后当用户输入大于 100 的数字时,程序停止并打印

tiers 并在每一层旁边,告诉用户每一层中有多少个值。

那么我想做的是,在代码的末尾,sout 命令所在的地方,

与其从字面上说每个部分有多少数字,我想表示

例如带*s的值

0-29: *****
30-39: ****
40-69: ********
70-100: *****

抱歉,如果我不是很清楚,我认为这可能只是我自己缺乏理解......

谢谢

最佳答案

创建一个可重用的方法,为您打印 * -

public static void printStars(int n){
for(int i = 0 ; i < n ; i++)
System.out.print("*");
}

然后这样调用它-

System.out.println("0-29:" + " " + printStars(Boundary0));
System.out.println("30-39:" + " " + printStars(Boundary30));
System.out.println("40-69:" + " "+ printStars(Boundary40));
System.out.println("70-100:" + " " +printStars(Boundary70));

关于java - 如何打印与变量值对应的一组字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20314827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com