Display occurrence of number based off user input... array, java
I am trying to have a user enter in any amount of numbers they like then based upon their input use an array to count each occurrence of the numbers entered by the use开发者_JAVA百科r. I know where i have my occurrence counter per say i am missing my return statement as that was one of the things i am confused on, basically i am kind of stumped, yes this is homework and i do want to learn so i do not expect the full answer, just some input , thanks
package chapter_6;
import java.util.Scanner;
/** * * @author jason */ public class Six_Three {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] num = createArray();
// prompt user for numbers
System.out.println("Enter integers between 1 and 100: ");
int data = input.nextInt();
}
// create array based off user input
public static int[] createArray() {
int[] num = new int[data];
return num;
}
// count each occurence of input numbers from user
public static int[] countNumbers(int[] data) {
for (int i = 0; i < data.length; i++)
return ?
}
}
use this
Map<Integer,Integer>occur = new HashMap<Integer,Integer>();
for(int i=0; i< data.length;++i){
int num = data[i];
if(occur.containsKey(num) ){
int old_counter = occur.get(num);
map.put(num,old_counter++);
}
else
map.put(num,1);
}
Your code has some problems. First of all, you cannot access the variable data
in any method except main, since that was where it was created. Secondly, your current code is only asking the user for one number, you'll need a loop to ask for multiple numbers. Here's some psuedocode.
Create an array with 100 spots and initialize them all to 0
Ask the user how many numbers they want to enter
Create a for loop that runs until the user has entered the amount of numbers specified
Read in a number and store it in a variable (we'll call it n).
Add 1 to the (n-1)th spot in the array (For example, if the number entered was 7, set myarray[6] = myarray[6] + 1 )
Create a for loop that loops from 1-100
Print out how many of each number was found
精彩评论