0

I've had a ton of issues with this program, added a while hasNextInt, multiple other things and i've finally got the code working, but my output is just the first input, instead of max/avg of the inputs. Could somebody let me know where i'm messing up?


public class LabProgram {
   public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);
        int count = 0, max = 0, total = 0;

        int num = scnr.nextInt();
        
            if (num >= 0) {
               count++;
               total += num;
               max = Math.max(max, num);
               num = scnr.nextInt();
         }

        int avg = count == 0 ? 0 : total/count;
        System.out.println(avg + " " + max);
    }
}
Chibb
  • 1
  • 1

1 Answers1

1

you are not using a loop to get numbers from the console. Also, logic for avg may result in the wrong answer. find below solution.

 Scanner scnr = new Scanner(System.in);
 int count = 0, max = 0, total = 0;

 System.out.println("Enter any other characters expect numbers to terminate:");

while(scnr.hasNextInt()) {
   int num = scnr.nextInt();
   if (num >= 0) {
       count++;
       total += num;
       max = Math.max(max, num);
   }
   }
  double avg = count == 0 ? 0 : (double)total/(double)count; // to print correct  avg
  System.out.println(avg + " " + max);

sample Output:

Enter any other characters expect numbers to terminate:
3
3
34
a
13.333333333333334 34
backdoor
  • 776
  • 1
  • 3
  • 15