當前位置:編程學習大全網 - 編程軟體 - 求壹個JAVA程序,輸入任意多個10以內的正整數, 輸入-1表示輸入結束。輸出每個整數出現的次數,用數組做

求壹個JAVA程序,輸入任意多個10以內的正整數, 輸入-1表示輸入結束。輸出每個整數出現的次數,用數組做

1. Scanner輸入

2. if判斷是否結束

3. 遍歷數組

import java.util.Arrays;

import java.util.Scanner;

public class ShuZu{

public static void main(String[] args) {

int a = 0;

int[] aa= new int[0];

Scanner cin = new Scanner(System.in);

for(;;){

System.out.println("請輸入10以內的整數,-1表示結束");

String s1 = cin.nextLine();

try{

a = Integer.parseInt(s1);

//a = cin.nextInt();

if(a == -1){

cout(aa);

break;

}

else if(a>=0 && a<=10){

if(aa.length == 0)

aa = new int[]{a};

else{

aa = Arrays.copyOf(aa, aa.length+1);//因為要求用數組,否則直接String簡單些

aa[aa.length-1] = a;

}

}

else

System.out.println("請輸入10以內的整數");

}catch(Exception e){

System.out.println("您輸入的不是數字,請重新輸入");

}

System.out.println(Arrays.toString(aa));

}

}

private static void cout(int[] aa) {

int tem = 0;

outer:

for(int i=0;i<aa.length;i++){

int count = 1;

tem = aa[i];

for(int j=0;j<i;j++){

if(tem == aa[j]){

continue outer;

}

}

for(int j=i+1;j<aa.length;j++){

if(tem == aa[j]){

count++;

}

}

System.out.println(tem +"\t次數:"+ count);

}

}

}

  • 上一篇:中國哪個大學的IT好 600分左右 也可以往下點
  • 下一篇:清點物品時應該清點什麽?
  • copyright 2024編程學習大全網