Java - How to only count the inputted positive numbers - java

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.

Related

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.

Java-Number of scores needs to be one less in answer

So here is my code:
package e7;
import java.util.Scanner;
public class Q1 {
public static void main(String[] args)
{
double[] scores = new double[10];
double sum = 0.0D;
int count = 0;
Scanner sc = new Scanner(System.in);
do {
System.out.print("Enter a new score (-1 to end): ");
scores[count] = sc.nextDouble();
if (scores[count] >= 0.0D)
sum += scores[count];
}
while (scores[(count++)] >= 0.0D);
System.out.println("The total number of scores is: " + count );
double average = sum / (count - 1);
int numOfAbove = 0;
int numOfBelow = 0;
for (int i = 0; i < count - 1; i++) {
if (scores[i] >= average)
numOfAbove++;
else
numOfBelow++;
}
System.out.printf("Average is " + "%.2f\n",average);
System.out.println("Number of scores above or equal to the average " + numOfAbove);
System.out.println("Number of scores below the average " + numOfBelow);
}
}
How do make it display the correct number of scores calculated? If I input 2 numbers and then do the -1 one to end it keeps saying 3 scores. Should only be two. How do I fix this? Thanks
System.out.println("The total number of scores is: " + count );
You probably want:
System.out.println("The total number of scores is: " + (count - 1));
You could also change your loop from a do while to a while loop as follows,
while (true) {
System.out.print("Enter a new score (-1 to end): ");
double tempDouble = sc.nextDouble();
if (tempDouble >= 0.0D)
scores[count] = tempDouble;
sum += scores[count];
count++;
else
break;
}
That way as if your double input isn't correct it would break out of the while loop when the user entered -1. You might have to tweak it a bit for your use case.

why is my count increasing when entering 0, it should exit the loop

I been working on this all night but couldn't make anything out it. I want my code to sum all the numbers the user enter, count how many times the user enters the number. then calculate the average.
and then find the max and min, easy right. well yeah if i was to be allowed to use arrays but this is for review and I hate while loops.
here's my code.
double integer = 1;
//double num = 0;
double sum = 0.0;
double average = 0.0;
Scanner input = new Scanner(System.in);
int count = 0;
// double char1=0;
double min = integer;
double max = integer;
// char letter = 'q';
while (integer != 0) {
System.out.println("Please enter an integer: ");
integer = input.nextInt();
sum += integer;
count++;
System.out.println("The sum of your numbers is: " + sum);
System.out.println("The number of values entered is: " + count);
System.out.println("");
if (integer > max)
max = integer;
else if (integer < min)
min = integer;
}
Here's the output:
Please enter an integer:
3
The sum of your numbers is: 3.0
The number of values entered is: 1
Please enter an integer:
2
The sum of your numbers is: 5.0
The number of values entered is: 2
Please enter an integer:
1
The sum of your numbers is: 6.0
The number of values entered is: 3
Please enter an integer:
0
The sum of your numbers is: 6.0
The number of values entered is: 4
The average of your sum is: 1.5
The max integer is: 3.0
The min integer is: 0.0
when the count increases by 1 my average comes out wrong. but why is 0 been counted as part of count and why my min always output 0 and not what the user enters. any and all help is much appreciated.
p.s. i have tried numerous ways but it doesnt work. if i try to change my count to start at -1 it solves my problem at hand with average but the count increases anyways so i know its incorrect. also the min problem stays there.
thanks guys
You need to add if condition to avoid increment when you enter 0.
You can use this code
// setting starting min and max value.
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
while (integer != 0) {
System.out.println("Please enter an integer: ");
integer = input.nextInt();
sum += integer;
if (integer != 0) { // added if condition
count++;
System.out.println("The sum of your numbers is: " + sum);
System.out.println("The number of values entered is: " + count);
System.out.println("");
if (integer > max)
max = integer;
if (integer < min) // changed 'else if' to 'if'
min = integer;
}
}
System.out.println("Max : " + max);
System.out.println("Min : " + min);
Try this:
For these cases it is best to use the conditional do while. And initialize min at the maximum value allowed.
double integer;
double sum = 0.0;
Scanner input = new Scanner(System.in);
int count = 0;
double min = Double.MAX_VALUE;
double max = 0;
do {
System.out.print("Please enter an integer: ");
integer = input.nextInt();
if (integer >0) {
sum += integer;
count++;
System.out.println("The sum of your numbers is: " + sum);
System.out.println("The number of values entered is: " + count);
System.out.println("");
if (integer > max)
max = integer;
if (integer < min)
min = integer;
}
} while (integer != 0);
System.out.println("avg: "+sum/count);
System.out.println("max: "+max);
System.out.println("min: "+min);
you will need to add an extra if condition to make it work.
I have made few changes as below in your code and it is working as expected.
double integer = 1;
//double num = 0;
double sum = 0.0;
double average = 0.0;
Scanner input = new Scanner(System.in);
int count = 0;
double min = integer;
double max = integer;
while (true) {
System.out.println("Please enter an integer: ");
integer = input.nextInt();
if(integer != 0)
{
sum += integer;
count++;
System.out.println("The sum of your numbers is: " + sum);
System.out.println("The number of values entered is: " + count);
System.out.println("");
if (integer > max)
max = integer;
else if (integer < min)
min = integer;
}
else
break;
}
double integer = 1;
double sum = 0.0;
double average = 0.0;
Scanner input = new Scanner(System.in);
int count = 0;
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
while (integer != 0) {
System.out.println("Please enter an integer(press zero to exit): ");
integer = input.nextInt();
if (integer > 0){
sum += integer;
count++;
if (integer > max)
max = integer;
if (integer < min)
min = integer;
}
}
System.out.println("The sum of your numbers is: " + sum);
System.out.println("Your count number is: " + count);
average = sum / count;
System.out.println("The average of your sum is: " + average);
System.out.println("The max integer is: " + max);
System.out.println("The min integer is: " + min);
}
}
You may try the below code
import java.util.Scanner;
public class ComputeDemo {
public static void main(String[] args) {
double integer = 1;
//double num = 0;
double sum = 0.0;
double average = 0.0;
Scanner input = new Scanner(System.in);
int count = 0;
// double char1=0;
double min = integer;
double max = integer;
// char letter = 'q';
while (integer != 0) {
System.out.println("Please enter an integer: ");
integer=input.nextInt();
if(integer>0)
{
sum += integer;
count++;
System.out.println("The sum of your numbers is: " + sum);
System.out.println("The number of values entered is: " + count);
System.out.println("");
if (integer > max)
max = integer;
else if (integer < min)
min = integer;
}
else
{
min=0;
System.out.println("The sum of your numbers is: " + sum);
System.out.println("The number of values entered is: " + count);
System.out.println("");
}
}
}
}

Perfect number from input

I'm trying to print out if a number is perfect or not by having the user enter in a number. When I enter a perfect number like 6, for example, it tells me that it is not a perfect number and can't figure out why. My final code needs to print out like 6 = 1 + 2 + 3. But I'm not that far yet.
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a positive integer: ");
int n = scanner.nextInt();
int sum = 0;
for(int i = 1;i<n;i++){
if(n%2==0)
sum += i;
}
if(sum==n){
System.out.println(n + " is a positive number");
}
else {
System.out.println(n + " is not a positive number");
}
if(n%2==0)
should be
if(n%i==0)
Otherwise your sum would be the sum of all numbers from 1 to n-1 for even n, or 0 for odd n.
Your code would look like:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int n = scanner.nextInt();
int sum = 0;
for(int i = 1;i<n;i++){
if(n%i==0)
sum += i;
}
if(sum==n){
System.out.println(n + " is a perfect number");
System.out.print(n+" = ");
for(int i=1;i<n;i++)
if(n%i==0) System.out.print((i!=1?" + ":" ") + i);
}
else {
System.out.println(n + " is not a perfect number");
}
Formatting the output without using the ternary operator:
System.out.println(n + " is a perfect number");
System.out.print(n+" = ");
for(int i=1;i<n;i++)
if(n%i==0) {
if (i==1)
System.out.print(i);
else
System.out.print(" + " + i);
}
Check this out. :)
public static String isPerfect(int num){
int product = 1;
for (int x=1; x<num; x++){
product *= x;
if (product == num){
return num + " is a perfect number";
}
}
return num + " is a not perfect number";
}

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