Result no initialized? - java

import java.util.*;
//Creates a program which allows the user to find the factorial of a number
public class forLoop {
public static void main (String [] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number you want the factorial from: ");
int number = input.nextInt(); // user input
input.close();
int result_2 = getFactorial(number); //initializes getFactorial method
System.out.println("The factorial of " + number + " is " + result); //prints results
}
public static int getFactorial (int num1) {
int result;
for (int times = num1; times <= 1; times--) { //repeats loop until times <=1
result = num1 * (num1 - 1); //does the factorial equation
}
return result; // returns results (here is the problem)
}
}

The compiler cannot assume that the loop would execute at least once - a necessary condition for the result to get assigned.
Change declaration of result as follows to fix the problem:
int result = 1;
This would help your code compile, but it would not fix the logical error in calculating the factorial: currently, your loop would run indefinitely because of a wrong loop condition.
You should be multiplying numbers from 1 to num1, inclusive. Change the loop condition so times >= 1 instead of times <= 1, and the loop body to result *= times to fix this error.

You need to intialize this variable:
int result;
Like this:
int result = 0; //Which ever intial value you want
Because compiler will not be sure that for loop will be always executed.

The condition of for loop is incorrect
it shoud be
for (int times = num1; times >= 1; times--)
{
result *= times; //this wil calculate right factorial
}
also initialize result to 1 before for loop

since you are assigning the function return value to result_2, you should print that instead of result
try
System.out.println("The factorial of " + number + " is " + result_2);
And you are need to initialize local variable before using them

int result;
for (int times = num1; times <= 1; times--) { //repeats loop until times <=1
result = num1 * (num1 - 1); //does the factorial equation
}
This block is causing the error. If the loop does not run even once due to this
times <=1
condition java wont have anything to print here
System.out.println("The factorial of " + number + " is " + result);
So here comes the need of initialization which acts as a default value to print.
So the solution will be to replace
int result;
with
int result=1; // note that I am not initializing with 0 as that will cause every factorial to become zero.
there is another mistake in your code instead of
times <= 1
it should be
times >= 1
Your code will probably not run even once for this error.

Just initialize int result to something:
int result = 0;
Because your loop isn't executing (times is already greater than 1), it is trying to return an uninitialized variable.

Related

I want to print all Armstrong number between a given range irrespective of the no. of digits in the number entered by user in Java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have written this program but can't find the error in this to get desired result.
I have given the range of the number by user input and want to find armstrong numbers between them.
Input: Enter the range to print armstrong number between them.
100
10000
Expected Output: Armstrong Number between 100 and 10000:
153 370 371 407 1634 8208 9474
My Program Output: Enter the Range to Print Armstrong Number between Them
100
10000
There is no Armstrong Number between 100 and 10000
import java.util.Scanner;
public class ArmstrongList {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the Range to Print Armstrong Number between Them");
int start = scanner.nextInt();
int end = scanner.nextInt();
int cubeSum = 0, digit, counter = 0;
for(int i = start; i < end; i++){
int count = 0;
int num = i;
while(num!=0) { //Count no. of digits in the Number
num /= 10;
++count;
}
int temp = i;
while(temp!=0) {
digit = temp % 10;
cubeSum = cubeSum + (int)(Math.pow(digit , count));
temp/=10;
}
if(cubeSum == i) {
System.out.println(i + " is an Armstrong number ");
if(counter == 0){
System.out.println("Armstrong Number between " + start + " and " + end + ": ");
}
System.out.println(i + " ");
counter++;
}
}
if(counter == 0) {
System.out.println("There is no Armstrong Number between " + start + " and " + end);
}
}
}
The problem is that you don't reset cubeSum to zero on each iteration.
There is no benefit in declaring variables outside the loop. Variables don't actually cost anything to declare inside a loop(*): they don't even exist at runtime. At runtime, it is just "some place in memory" where a value is stored and read from. So, declare them in the tightest scope possible, in order to avoid accidentally reusing value from previous computations.
Move the declaration of the cubeSum into the for loop, ideally immediately before the while loop where it is incremented (while you're at it, declare digit inside the loop too):
int cubeSum = 0;
while(temp!=0) {
int digit = temp % 10;
cubeSum = cubeSum + (int)(Math.pow(digit , count));
temp/=10;
}
Ideone demo
Learn to use a debugger
An even better approach could be to declare methods to calculate the cube sum (and count, similarly):
int cubeSum(int i, int count) {
int cubeSum = 0;
while(i!=0) {
int digit = i % 10;
cubeSum = cubeSum + (int)(Math.pow(digit , count));
i/=10;
}
return cubeSubm;
}
This scopes the variables even more tightly, so you don't see the intermediate computations, and get a much clearer main method, with effectively final variables:
int count = count(num);
int cubeSum = cubeSum(i, count);
if (cubeSum == i) {
// Print that it's an Armstrong number.
}
(*) The value assigned to a variable might cost something, if you create a new Whatever() on each iteration, or evaluate some expensive function; but assigning a constant primitive has almost zero cost.

1 - 100 prime or not in Java

This is a basic prime number checker. How would I loop this code so it tells me every single number from 1 to 100 and if its prime or not. For example:
1 is not a prime number
2 is a prime number
3 is a prime number
and so on until 100. This is not a user generated program just straight up if I run it it gives me all 100 numbers
int check;
int number;
boolean prime = true;
for (int i=2; i<=check/2; i++)
{
number = check%i;
if (number == 0)
{
prime = false;
}
}
if (prime == true)
{
System.out.println(check + " is a prime number");
}
else
{
System.out.println(check + " is not a prime number");
}
}
You have almost all of the code correct, you just need to put it in the right place. For example, your println statements need to be inside the for loop and your for loop needs to start at 1 and increment by 1 to 100.
for(int x = 0; x < 101; x++)
{
if(x == 2)
System.out.println(x + " is a prime number");
if(x % 2 == 0)
System.out.println(x + " is not a prime number);
else
System.out.println(x + " is a prime number);
}
I just helped a friend with almost this exact problem, so this couldn't be better timing. I don't know if your scanner is going to be used, but this works if you are just looking for prime numbers from 1-100.
For starters, it seems your Scanner isn't being used anywhere. Maybe your code is incomplete?
You can replace the Scanner part where you get the input from the user with a for loop that will give the number to you. Like so:
for(int number = 1; number <= 100; number++) {
// code for checking if number is prime or not
}
Take a look at code below, let me know if something is unclear, ask, don't just read and copy:
package com.company;
public class Main {
public static void main(String[] args) {
out:
for (int i = 1; i <= 100 ; i++) {
for (int j = 2; j <= i / 2 ; j++) {
if (i % j == 0) {
System.out.println(i + " is not prime number.");
continue out;
}
}
System.out.println(i + " is prime number.");
}
}
}
So to just walk over the code real quick:
1.) Create labeled block called out:
out:
2.) Create two nested for loops to check for our numbers being prime or not
3.) If statement in the second for loop will check if our number is not prime (if it's divisible by any number from 1 to itself but not those two numbers)
4.) In case our evaluation in if statement is false we continue looping until our second loop condition fails, then we move outside of the loop and print that number is prime:
System.out.println(i + " is prime number.");
5.) In case our evaluation in if statement is true we enter the if block, we print that number is not prime and we move program control back to the labeled block we created earlier
6.) We continue doing this repeatedly until outter loop check condition fails and our program is done with it's work.
/* Prime numbers are numbers that are divisible by 1 and by themselves. So, if you take the modulus of a number 'N' with all the number from 1 till 'N' and increase a count each time the modulus is zero, you can use a simple if condition at the end to check whether they are prime or not. In this code, I start from checking with number 1 and go till 100*/
int count ;
for(int j=1;j<=100;j++)
{
count=0;
for(int i=1;i<=j;i++)
{
if(j%i==0)
count=count+1;
}
if(count>2)
System.out.println(j+"is not a prime number");
else
System.out.println(j+"is a prime number");
}

Simulating Logarithms by repeated Integer division

I'm trying to write a program that simulates logarithms by repeated integer division. A user inputs a base number and a value X that they want to take the log of. The code runs through a loop and increments a count after each successive division. The code is set to stop after the value of X gets smaller than the base because I'm only using int type variables.
This code works fine for some numbers and bases but for others it gives the wrong value. It does " log_2(64) is 6 " however it doesn't do log_10 of 100. It gives a count of 10.
public static void main(String[] args) {
Scanner inScan = new Scanner(System.in);
int base;
int X;
int response;
int n=0;
do{
System.out.println("Java Lab 3 Logarithm Solver.");
System.out.println("Please enter a base > 1");
base = inScan.nextInt();
System.out.println("Please enter a number, X>0.");
X = inScan.nextInt();
if (X > 0 && base > 1){
System.out.println("Logarithm base " +base+ " of " +X+" is ");
for ( ; X>base ;n++){
X=(X/base);
}
System.out.println(n);
} else {
System.out.println("Invalide numbers.");
}
System.out.println("Would you like to go again? Press 1, press 0 to quit");
response = inScan.nextInt();
} while (response == 1);
}
}
You are declaring n as a global variable; I suspect that if you check your tests, this algorithm works only the first time through every time you compile and run it. Instead of having n as global, declare it in your for loop like
for(int n = 0; X < base; n++)
since it looks like you need the value of n later, I suggest having a variable with a wider scope, perhaps declared in the do-while loop, to store the n in, like
do
{
int numberOfTimesThroughLoop = 0;
...
for(...)
{
x = x/base;
numberOfTimesThroughLoop = n;
}
}
as a side note, most of the time variables (even single letter variable, like your 'X') being with a lower case character

what is wrong with my method for avg? [duplicate]

This question already has answers here:
How do I get this code to stop input when the sum exceeds 100 and still preform the sum and average?
(2 answers)
Closed 9 years ago.
Yes, I know there are a lot of methods here. It's part of the assignment. In this code everything works as intended except that when numbers are entered that equal sum<=100, the "average" output is wrong. For example: if I put in 8,10,19 and zero to exit the output is count 3 sum 37 average 9.25.... the average should be 12.3333. Now, if i enter in 8, 10, 99 the output is count 3 sum 117 and average 39 which is correct. Why is it working for sum>100 but not sum<=100??? I don't get it. What am I missing?
public static void main(String[] args) {
//Use Main Method for gathering input
float input = 1;
// Declare variable for sum
float theSum = 0;
// Declare variable for average
float average = 0;
// Declare variable for counting the number of user inputs
int counter = 0;
/* Initialize the while loop using an input of 0 as a sentinel value
* to exit the loop*/
while (input != 0) {
if (input!=0){
counter++;
}
input = Float.parseFloat(
JOptionPane.showInputDialog(
null, "Please enter a number. Enter 0 to quit: "));
// Invoke sum method and pass input and summation to sum method
theSum = (sum(input, theSum));
if (theSum > 100)
{
JOptionPane.showMessageDialog(null, "The sum of your numbers "
+ "are greater than 100!");
break;
}
}
// Invoke display method and pass summation, average, and counter variables to it
average = (avg(theSum, counter));
display(theSum, average, counter);
}
public static float sum(float num1, float sum) {
//Add the user's input number to the sum variable
sum += num1;
//Return value of sum variable as new summation variable
return sum;
}
public static float avg(float num1, float num2) {
//Declare and initialize variable for average
//Calculate average
float average = num1 / num2;
//Return value of average variable
return average;
}
public static void display(float sum, float average, int counter) {
/* I am subtracting 1 from variable counter so as not to include the sentinel value
* of 0 that the user had to enter to exit the input loop in the overall count*/
// Display the count, sum, and average to the user
if (sum > 100) {
JOptionPane.showMessageDialog(null, "Count = " + (counter) + ", Sum = " + sum + ", Average = " + average);
}
if (sum <= 100) {
JOptionPane.showMessageDialog(null, "Count = " + (counter - 1) + ", Sum = " + sum + ", Average = " + average);
}
}
}
The reason is that you're exiting the while loop in different ways depending on the total sum. If the sum is less than 100, even when you enter the number 0 to "exit", you're still going through the loop an extra time. To be honest, the entire loop needs to be completely restructured; a do...while loop would be much easier to read and debug.
The issue is because of the way you exit the while loop as mentioned by #chrylis. So in case where the sum is <= 100 the counter is 1 larger. But when you print it you get correct result because you update the counter value here:
if (sum <= 100) {
JOptionPane.showMessageDialog(null, "Count = " + (counter - 1) + ", Sum = " + sum + ", Average = " + average);
}
As you see in your example:
"if I put in 8,10,19 and zero to exit the output is count 3 sum 37 average 9.25"
it is because the counter value is 4 (so the avg will be 37/4 = 9.25), but while displaying the result you subtract counter by 1, therefore you get the count as 3.
The do-while loop will solve the issue as the condition would be checked at the last thus the loop will exit in same manner for both <=100 and '>100`.
The do-while loop would be like this:
do{
//here goes your code
}while (input != 0);
Your counter is 1 larger than necessary. Dividing by (counter - 1) would fix it.

I need to make two to the input value inclusive

/*
* Application the reads an integer and prints sum of all even integers between two and input value
*/
import java.util.Scanner;
public class evenNumbers{
public static void main(String [] args){
int number;
Scanner scan = new Scanner(System.in);
System.out.println("Enter an Integer greater than 1:");
number = scan.nextInt();
printNumber(number);
}// end main
/*declares an int variable called number and displays it on the screen*/
public static void printNumber(int number){
if (number < 2){
System.out.println("Input value must not be less than 2");
}
int sum = 2;
if(number % 2==0){
sum+= number;
}
System.out.println("Sum of even numbers between 2 and " + number + " inclusive is: " + sum);
}//end printnumber
}
I need to calculate the sum of 2 to the input number inclusive however, it only takes the last number and add two to it. COuld someone help me fix this.
You need a loop. Your comment hints at the right direction, but you should look at the Java tutorials to see how to correctly write a 'for' loop. There are three parts: the initial declaration, the terminating condition and the loop step. Remember that the ++ operator only adds one to the variable. You can add other values using +=. If you use += to add a different value (like 2) to the loop variable, you can skip the 'if' test for even numbers. You can test for boundaries inclusively using the <= and >= comparison operators (for primitives). So you want something like this (in pseudocode, not Java):
input the test value
Optional: reject invalid test value and **exit with message if it is not valid!**
initialize the sum variable to zero
for ( intialize loop variable to 2; test that loop var <= test value; add 2 to loop var )
{
add 'number' to the sum variable
}
display the sum
int sum = 0;
for (int current = 2; current <= number; current += 2)
sum += current;

Categories