简体   繁体   中英

Read in 5 numbers from a user and compute the frequency of positive numbers entered

Having difficulty trying to write code for this problem above. Please find the code below. Have to read in 5 numbers and compute the frequency of positive numbers entered.

import java.util.Scanner;

public class Lab02Ex2PartB {

    public static void main (String [] args){
        Scanner input = new Scanner(System.in);
        System.out.println("Please enter a  positive integer");
        int number = input.nextInt();
        for(int i = -2 ; i < 4 ; i++) 
            System.out.println("Positive Count is: " + i); 
    }           
}

Your problem is that you have a task that needs to be repeated (about the user entering a value); but your loop (the perfect mean to do things repeatedly) ... doesn't cover that part!

for(int i=-2 ; i<4 ; i++) System.out.println("Positive Count is: " +i);

Instead, do something like:

for (int loops = 0; loops < 5; loops++) {
  int number = input.nextInt();

Then of course, you need to remember those 5 values, the easiest way there: use an array; Turning your code into:

int loopCount = 5;
int numbers[] = new[loopCount]; 
for (int loops = 0; loops < loopCount; loops++) {
  numbers[loops] = input.nextInt();

And then, finally, when you asked for all numbers, then you check the data you got in your array to compute frequencies. A simple approach would work like this:

for (int number : numbers) {
  if (number > 0) {
    System.out.println("Frequency for " + number + " is: " + computeFrequency(number, numbers));
  }

with a little helper method:

private int computeFrequency(int number, int allNumbers[]) {
  ... 

Please note: this is meant to get you going - I don't intend to do all your homework for you. You should still sit down yourself and figure what "computing the frequency" actually means; and how to do that.

Try this one, Remember if you only want to know the frequency(not storing)

import java.util.Scanner;
public class Lab02Ex2PartB {

    public static void main (String [] args){

    int i = 1;// is a counter for the loop
    int positive =0;// counts positive numbers
            while(i<=5){
                Scanner input = new Scanner(System.in);
                System.out.println("Please enter a whole positive number");
                int number = input.nextInt();
                if(number > 0){
                    positive ++;
                }
                i++;
            }
    System.out.println("Positive Count is: "+ positive);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM