Perfect number from input - java

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";
}

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.

MOOC loops ending remembering

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++;
}

How do I display even and odd numbers based on user input? - java

Please help... I need to write a program that displays even and odd numbers based on user input, but it loops forever during my last print statement.
Here is what I have so far, what's wrong?
import java.util.Scanner;
public class Integer {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = 0;
int odd = 0;
int even = 0;
System.out.println("How many numbers will be entered?");
n = input.nextInt();
while (n < 0 || n > 100) {
System.out.println("ERROR! Valid range 0-100. RE-Enter:");
n = input.nextInt();
}
while(n >= 0) {
System.out.println("Now enter " + n + " integers: ");
int num = input.nextInt();
while(num > 0) {
for(int i = 0; i <= n; i++){
if (i % 2 == 0) {
even++;
}
else {
odd++;
}
System.out.println("You entered " + odd + " odd numbers and " + even + " even numbers.");
}
}
}
}
}
Scanner input = new Scanner(System.in);
int n = 0;
int odd = 0;
int even = 0;
System.out.println("How many numbers will be entered?");
n = input.nextInt();
while (n < 0 || n > 100) {
System.out.println("ERROR! Valid range 0-100. RE-Enter:");
n = input.nextInt();
}
while (n > 0) {
System.out.println("Now enter integer " + n + ": ");
int num = input.nextInt();
if (num % 2 == 0) {
even++;
} else {
odd++;
}
n--;
}
System.out.println("You entered " + odd + " odd numbers and " + even + " even numbers.");
Explanation:
You handle n inputs from user and just check if the input is odd or even with an if-statement. You were over-complicating it.
You have a couple of issues with too many while loops. You don't decrement n anywhere but you also loop on num while it's greater than 0. So it will loop forever if they stick something other than 0 in there.
System.out.println("Now enter " + n + " integers: ");
while(n >= 0) {
int num = input.nextInt();
if(num > 0) {
if (num % 2 == 0)
even++;
else
odd++;
}
n--;
}
System.out.println("You entered " + odd + " odd numbers and " + even + " even numbers.");
The infinite/forever loops is happening because of input.nextInt() and this is due to the behavior of next() method of Scanner class.
next(), nextInt() and its other variations do not move the cursor to the next line (end of current line - instead reads the first complete token with default delimiter as whitespace). nextLine() method on the other hand reads the whole input and moves the cursor to the next line.
Your code can be fixed by adding input.nextLine() to move the cursor to the beginning of the line before taking the next input. See below modified code.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = 0;
int odd = 0;
int even = 0;
System.out.println("How many numbers will be entered?");
n = input.nextInt();
while (n < 0 || n > 100) {
System.out.println("ERROR! Valid range 0-100. RE-Enter:");
n = input.nextInt();
}
for(int i = 0 ; i < n; i++) {
System.out.println("Now enter integer " + (i+1) + " of " + n + " integers: ");
int num = input.nextInt();
while(num < 0) {
System.out.println("ERROR! Valid range 0-100. RE-Enter:");
num = input.nextInt();
}
//this line is needed to move the input cursor to next line (due to use of nextInt() above)
input.nextLine();
if(i%2==0) {
even++;
} else {
odd++;
}
}
System.out.println("You entered " + odd + " odd numbers and " + even + " even numbers.");
}

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);

number of integers in output? simple java program

I'm working on a simple java code that outputs all factors of a user-inputted number. How do I count and then display the number of factors outputted?
System.out.println("Enter an integer to be factored:");
int d = Stdin.readInt();
System.out.println("The Factors of " + d + " are:");
for(int w = 1; w <= d; w++ ){
if(d % w == 0){
System.out.println(w);
}
}
In the code above, it's the number of integers outputted in 'w' For instance, if the number inputted is 8 and its factors are 1,2,4,8, how do I write a code that says '8 has 4 factors' ?
Thanks
You simply need a variable to count factors:
System.out.println("Enter an integer to be factored:");
int d = Stdin.readInt();
int nFactors = 0;
System.out.println("The Factors of " + d + " are:");
for(int w = 1; w <= d; w++ ){
if(d % w == 0){
System.out.println(w);
++nFactors;
}
}
System.out.println(d + " has " + nFactors + " factors");
You need a counter variable. Here is the code:
int counter =0;
for(int w = 1; w <= d; w++ ){
if(d % w == 0){
counter++;
System.out.println(w);
}
System.out.println(d + " has " + counter + "factors ");
Try with this code:
import java.util.Scanner;
public class EmbalzadoFactorial {
public static Scanner sc;
public static void main(String[] args) {
int Number, i;
sc = new Scanner(System.in);
System.out.print("Please Enter any number to Find Factors: ");
Number = sc.nextInt();
System.out.println("The factors are: ");
for(i = 1; i <= Number; i++) {
if(Number%i == 0) {
System.out.format(" %d ", i);
System.out.print ("and");
System.out.format("%s %n ", i);
}
}
}
}

Categories