Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Int array pushed through while loop until it reaches -1

I have to take a single line of user input, and calculate the average of all the numbers until it reaches -1 using a while loop. An example of user input could be something like 2 -1 6 which is why I’ve done it this way. I’ve figured out how to split this into an int array, but I can’t figure out how to do the while loop portion.

System.out.println("user input")
String user = scan.nextLine();
String[] string = user.split(" ");
int[] numbers = new int[string.length];
for(int i = 0;i < string.length;i++) {
    numbers[i] = Integer.parseInt(string[i]);
}
while ( > -1){
            
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Class java.util.Scanner has methods hasNextInt and nextInt.

import java.util.Scanner;

public class Averages {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter series of integers on single line separated by spaces.");
        System.out.println("For example: 2 -1 6");
        int sum = 0;
        int count = 0;
        while (scan.hasNextInt()) {
            int num = scan.nextInt();
            if (num == -1) {
                break;
            }
            sum += num;
            count++;
        }
        double average = sum / (double) count;
        System.out.println("Average: " + average);
    }
}

Note that you need to cast count to a double when calculating the average otherwise integer division will be performed and that will not give the correct average.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading