Hello I am trying to reset a counter in java, as I need to print out both the number of factors of a number and the sum of the factors. When I enter multiple integer values, these counters keep adding up. Is there a way in java to reset the counters after each new integer entered? Here is my code so far.
import java.util.Scanner;
public class FindFactors {
public static void main (String args[]) {
Scanner in = new Scanner(System.in);
int num, factorcounter = 0;
int sumfactors = 0;
System.out.print("Enter a positive integer.");
while(in.hasNextInt()) {
num = in.nextInt();
if(num > 0) {
for(int i = 1; i <= num; i++) {
if(num % i == 0) {
factorcounter++;
System.out.println(i + " is a factor of " + num);
sumfactors = sumfactors + i;
}
}
System.out.println("The number of factors: " + factorcounter);
if (sumfactors / 2 == num) {
System.out.println(num + " is a perfect number!");
}
}
else {
System.out.println("Invalid Input");
}
}
}
}
You have to assign zero to your variables.
Scanner in = new Scanner(System.in);
int num,factorcounter = 0;
int sumfactors = 0;
System.out.print("Enter a positive integer.");
while(in.hasNextInt())
{
num = in.nextInt();
factorcounter = 0;
sumfactors = 0;
if(num > 0)
{
for(int i = 1; i <= num; i++)
{
if(num % i == 0)
{
factorcounter++;
System.out.println(i + " is a factor of " + num);
sumfactors = sumfactors + i;
}
}
System.out.println("The number of factors: " + factorcounter);
if (sumfactors/2 == num)
{
System.out.println(num + " is a perfect number!");
}
}
else
{
System.out.println("Invalid Input");
}
}
Related
I was making an Armstrong number checker not for only 3 digits numbers for which I used Math.pow() method but after using it the if else statement is not working also when the condition is true.
Here is the code:
import java.util.Scanner;
import java.lang.Math;
class Main {
////////////////////////////////////////////
////////////////////////////////////////////
public static void main(String args[])
{
System.out.println("Hello world!");
Scanner sc = new
Scanner(System.in);
int num = sc.nextInt();
int numc = num ;
double rem = 0;
double cu = 0;
int val = 0;
int val2 = 0;
while(num != 0){
rem = num%10;
while(numc != 0){
numc /=10;
int i = 0;
i++;
val2 += i;
}
cu = Math.pow(rem,val2 );
val += cu;
num /= 10;
}
if(val == numc){
System.out.println("Yes its a "+val2+" Armstrong number because its returning " + val+"after Calculations ");
}
else{
System.out.println("No its not a "+val2+" digit Armstrong number because its returning " + val +" after Calculations ");
}
}
}
///////////////////////////////////////////
And this is the Compilation of my code:
if(val == numc){ - This if part is the root cause of your problem . you are dividing numc by 10 for calculations . So at the end it will become 0 . so you will be checking if val == 0 which goes to the else loop.
So I would suggest to assign the input from the user to another variable which you can use for checking the final if - else part.
Like int input = num and at the end if(val==input){ . This would resolve your issue.
The num and numc become zero due to "/= 10" operation. Hence the if condition fails.
Also you need not compute the length of integer every time.
Don't have the reputation to comment hence giving a full fledged solution.
Following is my solution to your problem.
All the best!
import java.util.Scanner;
import java.lang.Math;
class Main {
////////////////////////////////////////////
////////////////////////////////////////////
public static void main(String args[]) {
System.out.println("Hello world!\n");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int numc = num;
double rem = 0;
double cu = 0;
int val = 0;
int val2 = countNumOfDigits(num);
while (num != 0) {
rem = num % 10;
cu = Math.pow(rem, val2);
val += cu;
num /= 10;
}
if (val == numc) {
System.out.println("Yes its a " + val2 + " digit Armstrong number because its returning " + val
+ "after Calculations ");
} else {
System.out.println("No its not a " + val2 + " digit Armstrong number because its returning " + val
+ " after Calculations ");
}
}
private static int countNumOfDigits(int number) {
if (number < 100000) {
if (number < 100) {
if (number < 10) {
return 1;
} else {
return 2;
}
} else {
if (number < 1000) {
return 3;
} else {
if (number < 10000) {
return 4;
} else {
return 5;
}
}
}
} else {
if (number < 10000000) {
if (number < 1000000) {
return 6;
} else {
return 7;
}
} else {
if (number < 100000000) {
return 8;
} else {
if (number < 1000000000) {
return 9;
} else {
return 10;
}
}
}
}
}
}
import java.util.Scanner;
public class BA4 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Hello Drews, how many total grades do you want to process?");
int numberOfGrades = keyboard.nextInt();
int[] storeGrades = new int[numberOfGrades];
for (int i = 0; i < numberOfGrades; i++) {
System.out.println("Please enter grade " + (i + 1) + ": ");
storeGrades[i] = keyboard.nextInt();
}
System.out.println("Total score is: " + (getTotalScore(storeGrades)));
System.out.println("Lowest score is: " + (getLowestScore(storeGrades)));
System.out.println("Highest score is: " + (getHighestScore(storeGrades)));
System.out.println("Average score is: " + (averageScore(String.format("%.2f", storeGrades))));
}
public static int getTotalScore(int[] storeGrades) {
int sum = 0;
for (int i = 0; i < storeGrades.length; i++) {
sum += storeGrades[i];
}
return sum;
}
public static int getLowestScore(int[] storeGrades) {
int getLowestScore = 0;
for (int i = 0; i > storeGrades.length; i++) {
getLowestScore = storeGrades[i];
}
return getLowestScore;
}
public static int getHighestScore(int[] storeGrades) {
int getHighestScore = 0;
for (int i = 0; i < storeGrades.length; i++) {
getHighestScore = storeGrades[i];
}
return getHighestScore;
}
public static double averageScore(double[] storeGrades) {
double averageScore = 0;
for (int i = 0; i < storeGrades.length; i++) {
averageScore = (double) storeGrades[i];
}
return averageScore;
}
public static int printGrade(int[] storeGrades) {
int printGrade;
if (printGrade > 89) {
String gradeSoFar = "A";
System.out.println("Your grade so far is an " + gradeSoFar);
}
else if ((printGrade > 79) && (printGrade < 90)) {
String gradeSoFar = "B";
System.out.println("Your grade so far is a " + gradeSoFar);
}
else if ((printGrade > 69) && (printGrade < 80)) {
String gradeSoFar = "C";
System.out.println("Your grade so far is a " + gradeSoFar);
}
else if ((printGrade > 59) && (printGrade < 70)) {
String gradeSoFar = "D";
System.out.println("Your grade so far is a " + gradeSoFar);
}
else if ((printGrade > 0) && (printGrade < 60)) {
String gradeSoFar = "F";
System.out.println("Your grade so far is an " + gradeSoFar);
}
return printGrade;
}
}
I am trying to figure out where I am going wrong. I have a couple of errors which leads me to believe I really just don't understand methods as well as I thought I did.
The goal is to create 5 methods displaying to the user the total, lowest, highest and average scores, and then to print the letter grade. Thank you for your assistance to this noobie java coder! :)
You are passing in a String when you should be passing in a Double[] into averageScore function in this line:
System.out.println("Average score is: " + (averageScore(String.format("%.2f", storeGrades))));
and you did not initialize the printGrade variable inside the printGrade function, you need to give it an initial value if you are going to use it in a comparison.
That's all the errors that
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
double score = 0, avg, sum = 0;
int index = 0, count = 0, num = 0;
readInput(keyboard, num);
double Test[] = new double[num];
System.out.print("\n");
while(count < Test.length)
{
System.out.printf("Enter your test score #%d:", count + 1);
try
{
score = keyboard.nextDouble();
}
catch(java.util.InputMismatchException e)
{
System.out.print("You have entered a non-numerical value, please try again\n");
keyboard.next();
continue;
}
if (score >= 0)
{
Test[count] = score;
sum = sum + score;
}
else
{
System.out.print("You have entered an invalid grade, please try again\n");
continue;
}
count++;
}
double maxValue = Test[0];
for (int i = 1; i < Test.length; i++)
{
if (Test[i] > maxValue)
{
maxValue = Test[i];
}
}
double minValue = Test[0];
for (int i = 1; i < Test.length; i++)
{
if (Test[i] < minValue)
{
minValue = Test[i];
index = i;
}
}
System.out.print("\nThe highest value is: " + maxValue + "\n");
System.out.print("The lowest value is: " + minValue + "\n");
avg = sum / Test.length;
System.out.printf("Your grade average is: %.1f \n\n", avg);
System.out.print("Would you like to drop the lowest grade: Y or N:");
char choice = keyboard.next().charAt(0);
if (choice == 'Y' || choice == 'y')
{
double newSum = sum - minValue;
double newAvg = newSum / (Test.length - 1);
System.out.print("\nYour old scores were: ");
System.out.print(Test[0]);
for (int i = 1; i < Test.length; i++)
{
System.out.print(", " + Test[i]);
}
System.out.print("\n\nYour new scores are: ");
for (int i = 0; i < Test.length; i++)
{
if (index != 0 && i != index)
{
if (i >= 1)
{
System.out.print(", ");
}
System.out.print(Test[i]);
}
else if (i != index)
{
if (i >= 2)
{
System.out.print(", ");
}
System.out.print(Test[i]);
}
}
System.out.printf("\n\nYour new average is: %.1f\n", newAvg);
}
else if (choice == 'N' || choice == 'n')
{
System.out.print("Your average has stayed the same.\n");
return;
}
else
{
System.out.print("You have entered an invalid response. Bye.\n");
return;
}
}
public static int readInput(Scanner keyboard, int num)
{
System.out.print("How many scores would you like to enter:");
try
{
num = keyboard.nextInt();
}
catch(java.util.InputMismatchException e)
{
System.out.print("You have entered a non-numerical value.\n");
readInput(keyboard, num);
}
if (num < 0)
{
System.out.print("You have entered a negative value.\n");
readInput(keyboard, num);
}
else if (num == 0)
{
System.out.print("If you have no test grades then you do not need this program.\n");
readInput(keyboard, num);
}
return num;
}
}
The program keeps failing and telling me I'm returning the value wrong. num needs to put into the array around line 10 but I'm having trouble getting the value to return. I need to protect against user input error which is why I'm using the Input Mismatch Exception but in order to return them to the beginning if they mess up I was told I needed to use a separate function. However, this sometimes results in an infinite loop of the function. If anyone can help with a new way of doing this or how to fix what I am currently doing that would be a huge help.
I have been trying to figure out why isn't my code working. If I don't do it through a method and put this code in the main method then it keeps repeating. I want to ask the user for a new number every time. And then see if the number is odd or even. If odd then increase the odd count add all the numbers that the user enters. The user should be asked to enter values until the number 0 is entered.
package Week1;
import java.util.Scanner;
public class Task12 {
public void numbers() {
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
System.out.println("Enter number");
int oddnumbers = 0;
do {
int count = 0;
count = count + i;
System.out.println("The total is:" + count);
if (i % 2 == 0) {
System.out.println("The number is Even");
} else if (i != 9) {
oddnumbers += i;
System.out.println("The number is odd");
System.out.println("the count of odd numbers is :" + oddnumbers);
} else
System.out.println("The number is odd");
System.out.println("the count of odd numbers is :" + oddnumbers);
} while (i != 0);
}
public static void main(String[] args) {
Task12 n = new Task12();
n.numbers();
}
}
You should probably have the reading of a number "i = sc.nextInt();" inside the loop, and the variable count outside, like this:
package Week1;
import java.util.Scanner;
public class Task12 {
public void numbers() {
Scanner sc = new Scanner(System.in);
int oddnumbers = 0;
int count = 0;
int i=0;
do {
System.out.println("Enter number");
i = sc.nextInt();
count = count + i;
System.out.println("The total is:" + count);
if (i % 2 == 0) {
System.out.println("The number is Even");
} else if (i != 9) {
oddnumbers += i;
System.out.println("The number is odd");
System.out.println("the count of odd numbers is :" + oddnumbers);
} else
System.out.println("The number is odd");
System.out.println("the count of odd numbers is :" + oddnumbers);
} while (i != 0);
}
public static void main(String[] args) {
Task12 n = new Task12();
n.numbers();
}
}
This code gives the answer to tour spec/question
Reason for not working: You should take input inside do while loop and then check for odd.
public int numbers() {
Scanner sc = new Scanner(System.in);
int num = 0;
int oddSum = 0;
do {
System.out.println("Enter number");
num = sc.nextInt();
if(num == 0) {
break;
} else if (num % 2 != 0) {
oddSum += num;
}
} while (num != 0);
sc.close();
return oddSum;
}
public static void main(String[] args) {
Test n = new Test();
System.out.println(n.numbers());
}
This program checks if a user's input number is prime.
My problem is in the if statement. For some reason the Boolean is never switched. If the number is prime, it will just give both results.
What am I missing?
import java.util.Scanner;
public class Prime
{
public static void main(String[] args)
{
System.out.println("Enter a number to check if it is prime:");
Scanner kb = new Scanner(System.in);
int n = kb.nextInt();
boolean more = true;
do
{
for (int i = 2; i <= n; i++)
{
if (n <=1 || n%i==0)
{
System.out.println(n + " is not prime");
more = false;
}
}
}
while (more);
System.out.println(n + " is prime");
}
}
Remove the print which is inside if() and use the below code after the do while loop
if(more)
System.out.println(n + " is prime");
else
System.out.println(n + " is not prime");
and also you dont need a do while loop remove it.Complete Code
System.out.println("Enter a number to check if it is prime:");
Scanner kb = new Scanner(System. in );
int n = kb.nextInt();
boolean more = true;
for (int i = 2; i <= n / 2; i++) {
if (n <= 1 || n % i == 0) {
more = false;
break;
}
}
if (more) System.out.println(n + " is prime");
else System.out.println(n + " is not prime");
Demo
It's possible to check prime numbers with few lines using a for loop. It's better for performance.
Code to check prime numbers:
boolean isPrime = true;
for (int i = 2; i < n && isPrime; i++) {
isPrime = !(n % i == 0);
}
Full class according to your example:
import java.util.Scanner;
public class Prime {
public static void main(String[] args) {
System.out.println("Enter a number to check if it is prime:");
Scanner kb = new Scanner(System.in);
int n = kb.nextInt();
boolean isPrime = true;
for (int i = 2; i < n && isPrime; i++) {
isPrime = !(n % i == 0);
}
System.out.println(n + " is prime - " + isPrime);
}
}
Try this:
public static void main(String[] args) {
System.out.println("Enter a number to check if it is prime:");
Scanner kb = new Scanner(System.in);
int n = kb.nextInt();
boolean prime = true;
for (int i = 2; i <n; i++)
{
if (n <=1 || n%i==0)
{
prime = false;
break;
}
}
if(prime)
{
System.out.println(n + " is prime");
}
else
{
System.out.println("Not prime");
}
}
The following logic is working. Please try this.
int count=0;
for(i=2;i<=n/2;++i)
{
if(n%i==0)
{
count=1;
break;
}
}
if (count==0)
System.out.println(i+" is a prime number.");
else
System.out.println(i+" is not a prime number.");
If the count got increased, the given number is divisible by some other numbers. Or else It should be a prime number.
Thank you...
You don't need to check all the way up to n, just up to the square root. which if you calculate before should make your loop take less iterations and be faster.
Try this code with simple for loop.
boolean isPrime(int n) {
for(int i=2;i<n;i++) {
if(n%i==0)
return false;
}
return true;
}
Try this:
System.out.println("Enter a number to check if it is prime:");
Scanner kb = new Scanner(System.in);
int n = kb.nextInt();
boolean isPrime = true;
if (n < 1)
isPrime = false;
else
for(int i = 2; 2 * i < n; i++) {
if (n % i == 0) {
isPrime = false;
break;
}
}
System.out.println( n + " is " + (isPrime? "" : "not ") + "prime");