好吧,我得到了这个工作循环,让用户插入随机数,如果数字是0或如果已经达到循环长度然后它将停止,现在我必须输出所有输入的数字和输入量(示例1,2,3金额= 3)。我如何输出数组?我只从println得到0。
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int [] a1 = new int[100];
int i = 0;
int tal;
while(true){
System.out.println("Insert number (0-end):");
tal = scan.nextInt();
if(tal == 0 || a1[i] == a1.length){
break;
}else{
tal += a1[i];
}
}//End of while
System.out.println("The inserted numbers are are: " + a1[i]);
}//
答案 0 :(得分:0)
使用ArrayList而不是数组来收集数字输入,然后迭代它以打印它们使用其内置的lenght方法输出数量
答案 1 :(得分:0)
几个问题:
a1[i] = scan.nextInt();
这样的数组中,并将tal初始化为0,并在if条件而不是tal中使用a1 [i]。你可以点击以下内容:
在tal += a1[i];
增加i之后的值:
i++;
现在打印你的元素,使用如下的循环:
System.out.print("The inserted numbers are are:");
for (int j=0; j<i; j++) {
System.out.print(" " + a1[j]);
}
System.out.println();
答案 2 :(得分:0)
首先,将tal存储在数组中并在每次存储时递增i。最后遍历数组以打印输入的元素
import java.util.Scanner;
public class Tset {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int [] a1 = new int[100];
int i = 0;
int tal;
while(true){
System.out.println("Insert number (0-end):");
tal = scan.nextInt();
if(tal == 0||i>=100){
break;
}else{
a1[i]=tal;
i++;
}
}//End of while
System.out.println("The inserted numbers are are: ");
for(int j=0;j<i;j++){
System.out.println(a1[j]+"\t");
}
System.out.println("amount is: " +i);
}//
}
答案 3 :(得分:0)
我不确定你要做什么,但这可能有所帮助。
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] a1 = new int[100];
int i = 0;
int tal = 0;
int tmp;
do {
System.out.println("Insert number (0-end):");
tmp = scan.nextInt();
a1[i] = tmp;
tal += a1[i++];
} while (tmp != 0 && i < a1.length);
System.out.println("The inserted numbers are : ");
for (int j = 0; j < i-1; j++) {
if (j == i-2) {
System.out.print(a1[j] + ".");
} else {
System.out.print(a1[j] + ", ");
}
}
System.out.println("The sum is : " + tal);
}