MOOC loops ending remembering - java

I'm currently stuck with MOOC exercise 36. My problem is I can't make my program store odd and even numbers. I understand I need to use the modulus operator % 2 so the program can find if the reminder is 0 - 1 making is an even or odd number.
// program in this project exercises 36.1-36.5
// actually this is just one program that is split in many parts
Scanner reader = new Scanner(System.in);
System.out.println("Type numbers: ");
int tal; //Min reader funktion
int sum = 0;
int numbersTyped = 0;
double average = 0.0;
int even = 0;
int odd = 0;
while (true) {
tal = Integer.parseInt(reader.nextLine());
if (tal == -1){
System.out.println("Thank you and see you later!");
System.out.println("The sum is: " + sum);
System.out.println("How many numbers: " + numbersTyped);
System.out.println("Average: " + average);
System.out.println("Even numbers: " + even);
System.out.println("Odd numbers: " + odd);
break;
}
if (tal >= 0){
sum += tal;
numbersTyped++;
average = (double) sum / (double) numbersTyped;
} else if (tal > 0){
tal %= 2;
even = tal;
} else if (tal > 1) {
tal %= 2;
odd = tal;
}
}
}

try executing this code:
// program in this project exercises 36.1-36.5
// actually this is just one program that is split in many parts
Scanner reader = new Scanner(System.in);
System.out.println("Type numbers: ");
int tal; //Min reader funktion
int sum = 0;
double doubleSum =0.0d;;
int numbersTyped = 0;
double doubleNumbersTyped = 0.0d;
double average = 0.0;
int even =0;
int odd = 0;
while (true) {
tal = Integer.parseInt(reader.nextLine());
if (tal == -1){
System.out.println("Thank you and see you later!");
System.out.println("The sum is: " + sum);
System.out.println("How many numbers: " + numbersTyped);
System.out.println("Average: " + average);
System.out.println("Even numbers: " + even);
System.out.println("Odd numbers: " + odd);
break;
}
if (tal >= 0){
sum += tal;
numbersTyped++;
doubleSum = (double) sum;
doubleNumbersTyped = (double) numbersTyped;
average = doubleSum / doubleNumbersTyped;
}
if (tal > 0 && tal %2==0){
even++;
}
if (tal > 1 && tal %2!=0) {
odd++;
}
}

Scanner reader = new Scanner(System.in);
System.out.println("Type numbers:");
int sum=0;
int i=0;
int even=0;
int odd=0;
double average=0.0;
while (true) {
int number=Integer.parseInt(reader.nextLine());
if (number!=-1) {
sum+=number;
i++;
average=(double)sum/(double)i;
}
if (number==-1) {
System.out.println("Thank you and see you later!");
System.out.println("The sum is "+sum);
System.out.println("How many numbers:"+i);
System.out.println("The average is "+average);
System.out.println("Even numbers "+even);
System.out.println("Odd numbers "+odd);
break;
}
if (number%2==0) {
even++;
}
if (number%2!=0) {
odd++;
}

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.

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.

Write a program that reads an unspecified number of integers

"Count positive and negative numbers and compute the average of numbers) Write a program that reads an unspecified number of integers , determines how many positive and negative values have been read, and computes the total and average of the input values (not counting zeros). Your program ends with the input 0. Display the average as a floating-point number."
I don't know what I did wrong
import java.util.Scanner;
public class NewClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int positive = 0, negative = 0, total = 0, count = 0;
double average;
System.out.println("Enter the number: ");
int number;
while ((number = input.nextInt()) != 0) {
total += number;
count++;
if (number > 0) {
positive++;
} else if (number < 0) {
negative++;
}
}
average = total / count;
System.out.println("The number of positives is " + positive);
System.out.println("The number of negatives is " + negative);
System.out.println("The total is " + total);
System.out.printf("The average is %d ", average);
}
}
First: it should be average = (double)total / count; because int / int than you get an integer.
Second: System.out.println("The average is " + average); or System.out.printf("The average is %f ", average);
If you want the average of numbers, you cannot divide an integer total by an integer count because the result will be an integer, which does not account for decimal points.
import java.util.Scanner;
public class NewClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int positive = 0, negative = 0, total = 0, count = 0;
double average;
System.out.println("Enter the number: ");
int number;
while ((number = input.nextInt()) != 0) {
total += number;
count++;
if (number > 0) {
positive++;
} else if (number < 0) {
negative++;
}
}
average = (double) total / count;
System.out.println("The number of positives is " + positive);
System.out.println("The number of negatives is " + negative);
System.out.println("The total is " + total);
System.out.printf("The average is: " + average);
}
}
Also, you don't have to use %d in your line System.out.printf("The average is %d", average);
You can write System.out.printf("The average is: " + average); because when you print out a String, anything concatenated within the parentheses will also be converted to a String, and printed out as such
Simply multiply your int variable by 1.0 to convert it into floating point variable
average=1.0*total/count;
This should do.
And you can use following statement to display the value
System.out.println("The average of numbers is "+average);
// Scanner is in java.util package
import java.util.Scanner;
class CountPandN
{
public static void main(String args[])
{
// create a Scanner object
Scanner input = new Scanner(System.in);
// prompt user to enter numbers
System.out.println("Enter + and - numbers");
System.out.println("Enter 0 when you're finished");
// initialize the variables
int n, countP, countN, count;
n = input.nextInt();
countP = 0;
countN = 0;
count = 0;
int sum = n;
float average = (float) sum / 2;
while (n != 0)
{
n = input.nextInt();
count++;
if(n >= 0)
countP++;
if (n < 0)
countN++;
}
System.out.println("Total positive " + countP);
System.out.println("Total negative " + countN);
System.out.println("Total numbers " + count);
System.out.println("Total average " + average);
}
}
if you simply change System.out.printf("The average is %d ", average); with System.out.printf("The average is " +average); i.e. if you remove%d and use '+'instead ',' then it will work for you, and also to get answer in float you need to use typecasting. i.e. add (double) in average = (double)total / count;

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