I am trying to write a program which can calculate factorial from 1-9 by iteration, but I encounter some problems while I am trying to. Please help me figure out my problems in my program, I am just learning programming.
The following is my program, please tell me what's wrong with it:
public class iterative {
static int ans=1;
public static void iteration() {
System.out.println("n n!");
for (int n=1; n<10; n++) {
while ((n-1)>0)
ans=n*(n-1);
System.out.println(n + " " + ans);
}
}
public static void main(String[] args) {
iteration();
}
}
First of all, don't use a static for ans. A local is what you want.
Secondly the factorial recurrence relationship you use is incorrect. You should do it like this.
int ans = 1;
for (int n=1; n<=9; n++) {
ans = ans*n;
System.out.println(n + " " + ans);
}
The answers above is close perfect,you also get it with the recursion:
here is code:
public class iterative {
public static int iteration(int n) {
int result;
if(n==1)return n;
else
result = n*iteration(n-1);
return result;
}
public static void main(String[] args) {
System.out.println("Result is :" + iteration(9));
}
}
I see three big problems.
Firstly, "ans" is global and is never reassigned. So over time it will display an accumulated incorrect value.
The other is that the while loop will run forever for n > 1.
Lastly, the recurrence relationship is wrong. Should be ans = ans * (n-1). See code.
The fact that you have nested loops suggests to me that you are trying to print a table of factorials.
Try this:
for (int n=1; n<10; n++) {
int ans = 1;
int x = 0;
while ((n-x)>0){
ans=ans*(n-x);
x++;
}
System.out.println(n + " " + ans);
}
Like #David's solution but shorter
for(int i=1, ans=1; i <= 9; i++, ans *= i)
System.out.println(i + " " + ans);
Your algorithm needed work as well:
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
int i = 1;
while(i < 10)
iteration(i++);
}
public static void iteration(int max) {
System.out.println("n n!");
int ans = 1;
for (int n=1; n<=max; n++) {
ans *= n;
}
System.out.println(" " + ans);
}
ideone example
Related
im trying to make a calculator and im was unable to continue because of some confusion in my codes. i was trying to make a factorial of a number, if its a positive number there is no error but every time i input a negative number it results to 1, here is my code .
import java.math.BigInteger;
import java.util.Scanner;
public class Factorial2 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = s.nextInt();
String fact = factorial(n);
System.out.println("Factorial is " + fact);
}
public static String factorial(int n) {
BigInteger fact = new BigInteger("1");
for (int i = 1; i <= n; i++) {
fact = fact.multiply(new BigInteger(i + ""));
}
return fact.toString();
}
}
i already tried making if statements but still it results to 1.i also want to make the negative factorial into a display text not the value of the negative factorial
You need to validate the input before the calculation, example:
public static String factorial(int n) {
if(n < 1) return "0";
BigInteger fact = new BigInteger("1");
for (int i = 1; i <= n; i++) {
fact = fact.multiply(new BigInteger(i + ""));
}
return fact.toString();
}
Of course you can define any default return value or throw an error:
if(n < 1) throw new RuntimeException("Input must be > 0");
So I'm new to java, please excuse any messy code etc.
I have to make a program that prints out the squared value of a start and end argument declared in the command line, as well as the squares of the values in between.
This is the code I have so far, it's very rough, but I need help getting the variables in between to print out.
public static void main(String[] args)
{
int start;
int end;
int start2;
int end2;
start = Integer.parseInt(args[0]);
end = Integer.parseInt(args[1]);
start2 = start*start;
end2 = end*end;
if (args.length == 2) {
for (int i = start; i <= end; i++){
System.out.println("The square of "+start+" is " +start2);
System.out.println("The square of "+end+ " is " +end2);
return;
}
}
Any help is much appreciated!
You can calculate the square of start to end inside the loop:
public static void main(String[] args)
{
int start = Integer.parseInt(args[0]);
int end = Integer.parseInt(args[1]);
if (args.length == 2)
for (int i = start; i <= end; i++)
System.out.println("The square of " + i + " is " + i*i);
}
public static void main(String[] args)
{
int start;
int end;
start = Integer.parseInt(args[0]);
end = Integer.parseInt(args[1]);
if (args.length == 2)
{
for (int i = start; i <= end; i++)
System.out.println("The square of "+i+" is " +i*i);
return;
}
}
you can calculate it inside the loop
public static void main(String[] args)
{
if (args.length == 2){
int start = Integer.parseInt(args[0]);
int end = Integer.parseInt(args[1]);
for (int i = start; i <= end; i++){
System.out.println("The square of " + i + " is " + i*i);
}
}
}
Note : Check the length first, and short-circuit your condition if the length isn't equal 2 before doing any operation to avoid ArrayIndexOutOfBoundsException
EDIT: HERE IS A SCREENSHOT OF THE OUTPUT
https://www.dropbox.com/s/93d09a627se3b1u/Screenshot%202015-09-16%2019.08.19.png?dl=0]
I was recently asked to make a program that can calculate and display...
1 / (1!) + 1 / (2!) + . . . 1 / (n!)
using the Scanner utility. I seem to be having a lot of trouble with this. the program itself works, but it somehow gives the same answer no matter what number I input. Here's what I have so far (And yes, it is purposely incomplete, I'm stumped).
import java.util.Scanner;
class Power2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("I will calculate 1/(1!) + 1/(2!) . . . +
1/(n!)\nWhat is the value of n?");
Double n = input.nextDouble();
Math(n);
System.out.println("e = " + Math.E);
}
public static void Math(Double E)
{
Double product = 1.0;
int x = 0;
while (E > 0)
{
product = product * E;
E--;
}
Can anyone give me a way to finish/solve this problem? Thanks a ton.
~Andrew
EDIT: This code works fine for just finding the extreme. I will work on a way to add the preceding components of the equation to this, but It's a bit tricky for me.
import java.util.Scanner;
class Power2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("I will calculate 1/(1!) + 1/(2!) . . . +
1/(n!)\nWhat is the value of n?");
Double n = input.nextDouble();
Math(n);
System.out.println("e = " + Math(n));
}
public static Double Math(Double E)
{
Double product = 1.0;
while (E > 0)
{
product *= E;
E--;
}
return product;
}
}
You are confused with too much Math.
You've got your method Math with a parameter E and the Java Math class with a constant E. You're mixing them up.
Try
public static double factorial(double v)
{
double product = 1.0;
while (v > 0)
{
product *= v;
v--;
}
return product;
}
Your code:
System.out.println("e = " + Math.E);
Math.E is a constant - it will always print the euler number hence your output.
To call the the method correctly it should be
System.out.println("e = " + math(e)"
Input 1 - Output 1
Input 2 - Output 1.5
Input 3 - Output 1.66666667
import java.util.Scanner;
class MyClass
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("I will calculate 1/(1!) + 1/(2!) . . . + 1/(n!)\nWhat is the value of n?");
double n = input.nextDouble();
double solution = doMath(n);
System.out.println("e = " + solution);
}
public static double doMath(double n) {
double ret = 0;
// the number of terms we add
for (int i = 1; i <= n; i++) {
ret += calcFaculty(i);
}
return ret;
}
// calculate every single term
public static double calcFaculty(double d){
double calc = 1;
for (int i = 1; i <= d ; i++) {
calc = calc* 1/i;
}
return calc;
}
}
Hi Andrew the program always return the same number
e = 2.718281828459045
Because the line System.out.println("e = " + Math.E); is not calling the method Math but calling to the class java.lang.Math. I dont know if is this what you find dubious.
I tried write a program that should be printing iterative sums.
But the current code is instead printing the final sum for each iteration, and I can't figure why :
package sumseries;
public class Sumseries {
public static void main(String[] args) {
System.out.println("i" + "\t\t"+ "m(i)");
System.out.println("===================");
int x=0;
for(int i=1;i<=20;i++){
System.out.println( i + "\t\t" + series(x) );
}
}
public static double series(int i){
double sum=0;
for(i=0;i<=20;i++){
sum += ((double) i)/(i+1);
}
return sum;
}
}
What is wrong here and how can I fix it ?
In your method :
public static double series(int i){//The parameter is variable i
double sum=0;
for(i=0;i<=20;i++){ // You are again initialising i as 0;
sum += ((double) i)/(i+1);
}
return sum;
}
I have written comments adjoining the lines. So you would always get the same sum whatever you might pass as parameter to this method.
You are doing 2 thing wrong.
System.out.println( i + "\t\t" + series(x),
Here you are passing 0 always to series method.
for(i=0;i<=20;i++) in series Method,
Here again you are setting value of i=0;
public static void main(String[] args) {
System.out.println("i" + "\t\t"+ "m(i)");
System.out.println("===================");
int x=0;
for(int i=1;i<=20;i++){
//Pass Value of i instead of x=0;
System.out.println( i + "\t\t" + series(i) );
}
}
public static double series(int i){
double sum=0;
//Don't Iterate it Again for 20 times, Iterate it for i Number of value only.
for(int j=0;j<=i;j++){
sum += ((double) j)/(j+1);
}
return sum;
}
I am new to Java, and am writing a program to print 6 random numbers for a lottery ticket. I am receiving an error,
-Exception in thread "main" java.lang.RuntimeException: Uncompilable source -code - cannot find symbol
- symbol: variable numbers
- location: class lotto.Lottery
- at lotto.Lottery.printNumbers(Lottery.java:52)
- at lotto.Lottery.main(Lottery.java:34)
-Java Result: 1
import java.util.Random;
import java.util.ArrayList;
public class Lottery {
static ArrayList<Integer> lottoNumbers = new ArrayList<Integer>();
static int MAX_NUMBERS = 6;
public static void main(String[] args)
{
generateNumbers();
printNumbers();
}
private static void generateNumbers()
{
int ticketNumber;
Random generateRandomNumber = new Random();
for (int count = 0; count < MAX_NUMBERS; count++)
{
ticketNumber = 1 + generateRandomNumber.nextInt(59);
lottoNumbers.add(new Integer(ticketNumber));
}
}
private static void printNumbers()
{
int count = 0;
for( Integer number : numbers )
{
if (count < 5)
if (count == 4)
System.out.print(number);
else
System.out.print(number + ", ");
else
{
System.out.println("\nPower Ball: " + number);
count++;
}
}
}
}
Your code has a compilation error, hence the program fails to run: the variable numbers is not defined anywhere. If you want to loop over the generated numbers, use lottoNumbers which was filled by the generateNumbers method. You should also increment count++ after each element is printed (I would strongly encourage you to always use curly braces after if statements to avoid bugs):
int count = 0;
for (Integer number : lottoNumbers) {
if (count < 5) {
if (count == 4) {
System.out.print(number);
} else {
System.out.print(number + ", ");
}
} else {
System.out.println("\nPower Ball: " + number);
}
count++;
}