easy for loop not working - java

So I was trying to make
(EX) Enter some values: 1 -2 -3 2 5
num of positive num is 5 num of neg num is -3
total is 3 avg is .6
I wanted to make it like this but when i run it,
it doesn't work
what part is error???
import java.util.*;
public class Welcome {
public static void main(String [] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter an int value, the program exits if the input is 0: ");
int num = input.nextInt();
int countpos = 0;
int countneg = 0;
int totalnum = 0;
int total = 0;
double avg = 0.0;
while(num != 0){
if(num < 0)
countpos++;
else
countneg++;
total = total + num;
totalnum++;
}
System.out.print("num of pos is: " + countpos);
System.out.print("num of neg is: " + countneg);
System.out.print("total is: " + total);
System.out.print("the avg is: " + total / totalnum );
}
}

you have to do num = input.nextInt(); in the loop too
while(num != 0){
if(num < 0)
countpos++;
else
countneg++;
total = total + num;
totalnum++;
num = input.nextInt();
}

Related

Java - How to only count the inputted positive numbers

I am trying to find sum and averags of user inputed numbers and i also Need my program to only sum the positive numbers entered.
It needs to calculate only the positive numbers sum and ignore the negative inputs, would i put my num=0 or not?
import java.util.Scanner;
public class J12ForSumPos {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int maxNumbers, i, num, average;
int sum = 0;
System.out.print("Enter Max Numbers: ");
maxNumbers = console.nextInt();
System.out.println();
for (i = 1; i <= maxNumbers; i = i + 1) {
System.out.print("Enter Value " + i + ": ");
num = console.nextInt();
sum = sum + num;
}
average = sum / maxNumbers;
if (sum >= 0) {
System.out.println();
System.out.println("Sum: " + sum);
System.out.println();
System.out.println("Average: " + average);
System.out.println();
} else {
System.out.println("Sum is: " + sum * 0);
System.out.println();
System.out.println("Cannot Calculate Average - no positives entered");
}
}
}
You can try something like this:
Scanner console = new Scanner(System.in);
int maxNumbers = 0;
int totalSum = 0; // Sum of all numbers (positive and negative)
int totalAverage = 0; // Average of all numbers (positive and negative)
int positiveSum = 0; // Sum of all positive numbers
int positiveAverage = 0; // Average of all positive numbers
int positiveNumberCount = 0; // Amount of positive numbers entered
System.out.print("Enter Max Numbers: ");
maxNumbers = console.nextInt();
System.out.println();
for(int i=1; i<=maxNumbers; i=i+1)
{
System.out.print("Enter Value " + i + ": ");
int num = console.nextInt();
if(num >= 0) {
positiveSum = positiveSum + num;
positiveNumberCount = positiveNumberCount + 1;
}
totalSum = totalSum + num;
}
positiveAverage = positiveSum / positiveNumberCount;
totalAverage = totalSum / maxNumbers;
It's up to you to decide whether or not to include 0 as a positive or a negative number, or exclude it. In my example it's being treated as a positive number.

Varied amounts of input data

Problem: Statistics are often calculated with varying amounts of input data. Write a program that takes any number of non-negative integers as input, and outputs the average and max. A negative integer ends the input and is not included in the statistics.
Ex: When the input is:
15 20 0 5 -1
the output is:
10 20
You can assume that at least one non-negative integer is input.
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner (System.in);
int num = 0;
int count = 0;
int max = 0;
int total = 0;
int avg = 0;
do {
total += num;
num = scnr.nextInt();
count = ++count;
if (num >= max) {
max = num;
}
} while (num >= 0);
avg = total/(count-1);
System.out.println(avg + " " + max);
}
}
I had a lot of trouble with this problem. Is there any way I could have done this without having to do count -1 while computing the average?
Also, is this this the most efficient way I could have done it?
How about this? If you have questions from the implementation, please ask.
public static void main(String[] args) throws IOException {
Scanner scnr = new Scanner(System.in);
int count = 0, max = 0, total = 0;
int num = scnr.nextInt();
while (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);
}
If you use while loop instead of do-while loop, you don't have to count the negative number input anymore. And no, it's not the most efficient way, but it's a good start!
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner (System.in);
int userNum;
int maxNum = 0;
int totalSum = 0;
int averageNum;
int count = 0;
userNum = scnr.nextInt();
while (userNum >= 0) {
if (userNum > maxNum) {
maxNum = userNum;
}
totalSum += userNum;
++count;
userNum = scnr.nextInt();
}
averageNum = totalSum / count;
System.out.println("" + averageNum + " " + maxNum);
}
}
int Num;
int max = 0;
int total = 0;
int average;
int count = 0;
Num = scnr.nextInt();
while (Num >= 0) {
if (Num > max) {
max = Num;
}
total += Num;
++count;
Num = scnr.nextInt();
}
average = total / count;
System.out.println("" + average + " " + max);
}
}

how to exclude negative numbers from average calculation in while loop

I have a program that accepts user inputs and calculate Max, Min, and Average. The program closes when the user inputs any negative number. How do i exclude the negative number from the average calculation? Here is what i have so far.
// variable
double n = 1;
double ave = 0;
double sum = 0;
double max = Double.MIN_VALUE;
double min = Double.MAX_VALUE ;
int count = 0;
double neg;
//creat scanner object
Scanner input = new Scanner(System.in);
//loop
while (n > 0) {
System.out.print("Input an income (any negative number to quit): ");
n = input.nextDouble();
sum = sum + n;
count++;
ave = sum / count;
if(n<0) neg = n;
if(n>max && n >= 0 ) max = n;
if(n<min && n >= 0) min = n;
if(n>0) ave = n; }
System.out.print(" Average " + ave + "\n Maximum " + max + "\n Minimum " + min);
}
}
Add an if condition:
n = input.nextDouble();
if(n < 0)
break;
sum = sum + n;
The following code only sums the input numbers when n is not negative.
import java.util.Scanner;
public class sample {
public static void main(String[] args) {
double n = 1;
double ave = 0;
double sum = 0;
double max = Double.MIN_VALUE;
double min = Double.MAX_VALUE;
int count = 0;
double neg;
Scanner input = new Scanner(System.in);
// loop
while (n > 0) {
System.out.print("Input an income (any negative number to quit): ");
n = input.nextDouble();
if(n >= 0){
sum = sum + n;
count++;
}
if (n < 0)
neg = n;
if (n > max && n >= 0)
max = n;
if (n < min && n >= 0)
min = n;
if (n > 0)
ave = n;
}
System.out.print(" Average " + ave + "\n Maximum " + max
+ "\n Minimum " + min);
}
}
Try this:
double n = 1;
double ave = 0;
double sum = 0;
double max = Double.MIN_VALUE;
double min = Double.MAX_VALUE ;
int count = 0;
// create scanner object
Scanner input = new Scanner(System.in);
// loop until n is negative
while (n >= 0) {
System.out.print("Input an income (any negative number to quit): ");
n = input.nextDouble();
if (n >= 0) {
if (n > max) max = n;
if (n < min) min = n;
sum = sum + n;
count++;
}
}
if (count > 0)
ave = sum / (double) count;
System.out.print(" Average " + ave + "\n Maximum " + max + "\n Minimum " + min);

min max in array issue

So I have a program I wrote that finds the max and min value of a five number set. It works for the most part but when I enter a set of numbers like {5,6,7,8,9} then it outputs 9 as the max, but outputs 0 for the min. Any thoughts or suggestions.
import java.util.Scanner;
public class MinMax {
public static void main (String [] args) {
#SuppressWarnings("resource")
Scanner in = new Scanner (System.in);
final int NUM_ELEMENTS = 5;
double[] userVals = new double[NUM_ELEMENTS];
int i = 0;
double max = 0.0;
double min = 0.0;
System.out.println("Enter five numbers.");
System.out.println();
while (i < NUM_ELEMENTS) {
System.out.println("Enter next number: ");
userVals[i] = in.nextDouble();
i++;
System.out.println();
}
for (i = 0; i < userVals.length; i++) {
if (userVals[i] > max) {
max = userVals[i];
}
else if (userVals[i] < min) {
min = userVals[i];
}
}
System.out.println("Max number: " + max);
System.out.println("Min number: " + min);
}
}
Default your min to a number out of range (like Double.MAX_VALUE), and max to Double.MIN_VALUE. You might also simplify your code by removing the second loop; you can perform the logic in one loop and you might use Math.max(double, double) and Math.min(double, double). Something like,
Scanner in = new Scanner(System.in);
final int NUM_ELEMENTS = 5;
double[] userVals = new double[NUM_ELEMENTS];
System.out.println("Enter five numbers.");
System.out.println();
double min = Double.POSITIVE_INFINITY;
double max = Double.NEGATIVE_INFINITY;
for (int i = 0; i < NUM_ELEMENTS; i++) {
System.out.println("Enter next number: ");
userVals[i] = in.nextDouble();
min = Math.min(min, userVals[i]);
max = Math.max(max, userVals[i]);
}
System.out.println("Max number: " + max);
System.out.println("Min number: " + min);
Intialize your min variable to non-zero max value. Means max value that you can have in your input from console.

control structure, repetition exercise: How to get the sum of the digits of a number?

Guys can you please help me answer this exercise using for loop without using string methods.
Write a program that prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits. For example, the program should output the individual digits of 3456 as 3 4 5 6 and the sum as 18,and output the individual digits of -2345 as 2 3 4 5 and the sum as 14.
This is the code:
package MyPackage;
import java.util.*;
public class Integer
{
public static void main(String args[])
{
Scanner console = new Scanner (System.in);
int input;
int sum = 0;
int num1 = 0;
int counter = 1;
String num = "";
System.out.print("enter a number: ");
input = console.nextInt();
if (input == (-input))
{
input = input * (-1);
num = String.valueOf(input);
num1 = num.length();
System.out.print("the digits of " + input + " are: ");
for (int i = 0; i < num1; i++ )
{
String var = num.substring(i,counter);
int var1 = Character.getNumericValue(var.charAt(0));
System.out.print(var + " ");
sum = sum + var1;
counter++;
}
System.out.println();
System.out.println("the sum is: " + sum);
}
else
{
num = String.valueOf(input);
num1 = num.length();
System.out.print("the digits of " + input + " are: ");
for (int i = 0; i < num1; i++ )
{
String var = num.substring(i,counter);
int var1 = Character.getNumericValue(var.charAt(0));
System.out.print(var + " ");
sum = sum + var1;
counter++;
}
System.err.println();
System.out.println("the sum is: " + sum);
}
}
}
Iterating all the digits from right to left is easy enough - you just keep dividing by 10 and keeping the remainder.
Since you need to print them from left to right, but there don't seem to be any constraint on the memory usage, you could just keep them in a list, and print it backwards:
int num = ...; // inputed from user
List<Integer> digits = new LinkedList<>();
int sum = 0;
// Extract the digits and the sum
while (num != 0) {
int digit = num % 10;
digits.add (digit);
sum += digit;
num /= 10;
}
// Print backwards:
System.out.print ("The digits are: ");
for (int i = digits.size() - 1; i >= 0; --i) {
System.out.print (digits.get(i) + " ");
}
System.out.println();
System.out.println("Their sum is: " + sum);

Categories