[英]How to print out an array?
好的,所以这是一个应该能够打印出一个数组,并说出通过扫描仪输入数字0-9的次数的代码,如果给出了负数,则是要停止程序并打印所有内容,然后如您所见,该程序非常好,并且可以用数字全部打印出数组,但是我想知道如何将我的数组打印为“ x”而不是数字? 假设数字5被输入了5次,它应该打印出来:“数字5出现xxxxx次,同样,如果数字1被按下1次,它应该打印出来”数字1出现x次。 关于如何执行此操作的任何提示/解决方案? 提前致谢。 (编辑idk,为什么星星图标消失了,但可以说我想要x。
import java.util.Scanner;
public class q31{
public static void main(String args[]) {
System.out.println(1 + ":" + "\t" + "Integer 0-9");
Scanner keyboard = new Scanner(System.in);
int[] a = new int [10];
int counter=0;
int input;
input=keyboard.nextInt();
boolean exit=true;
while (exit==true) {
counter++;
System.out.println((counter+1)+":" + "\t" + "Integer 0-9");
if (input>-1 && input <10){
a[input]++;
}
input=keyboard.nextInt();
if(input<0) {
exit=false;
for(int i = 0; i < a.length; i++)
{
System.out.println("the number " + i + " appears " + a[i] + "times");
}
}
}
}
尝试改变
System.out.println("the number " + i + " appears " + a[i] + "times");
至
System.out.print("the number " + i + " appears ");
for(int n = 0; n < a[i]; n++)
System.out.print("x");
System.out.println(" times");
您需要使用数组a[i]
中位置i处的数字来控制循环。 该循环可以为每次迭代执行System.out.print("x")
。
下面是一些代码-由于我认为这可能是家庭作业,因此我将循环的实现留给了您。
System.out.print("the number " + i + " appears ");
//create loop
System.out.print("x");
// end loop
System.out.println(" times");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.