문제

I keep trying to add (many times) +1 to a number (the number is zero) already in an array which is zero but it is not working.

int i=0;//var for arrays
int [] countArray = new int[10];


/////////////////////
//__________ ask for values --------------

System.out.println("Hello please enter the number you would" +
        " like to be sorted separated by commas. \n" +
        "Example: \" 2,3,5,83,2 \".\t only use" +
        " commas. to separate numbers\n");


//-----------   save values -----
Scanner scan = new Scanner(System.in);

String allInput = scan.nextLine();//single string object with all input

String [] arr = allInput.split(",");//string array that holds all values
//as String
int [] numbersArray =new int[arr.length] ;//numbers

for ( String w: arr){//change Strings to Int
    numbersArray[i]= Integer.valueOf(arr[i]);
    i++;
}

//__ set all number in count to zero because necessary

i=0;
for ( int x: countArray){//set all numbers to zero
countArray[i]=0;        

i++;

} //everything zeroed


i=0;

This works now, thank you guys:

for (int x = 0; x < numbersArray.length; x++){


if (numbersArray[x] >=10 && numbersArray[x] <=100)  {  
countArray[(numbersArray[x]-1)/10]++;}
else{

    if (numbersArray[x] >=0 && numbersArray[x] <=10)
    {
 countArray[1 -1]++;}
}



}
도움이 되었습니까?

해결책

Instead of using a for-each loop to edit all the values, try to iterate through them using a standard for loop. Here is a shorthand version of what you wrote. Try this:

for (int x = 0; x < numbersArray.length; x++){
    countArray[(numbersArray[x]-1)/10]++;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top