Reading Non-Negative Integer And Computing Its Factorial

Oct 3, 2014

I am attempting to write a program that reads a nonnegative integer and computes and prints its factorial. So far I have: Java Code: import java.util.Scanner;

public class Chapter3point37 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int nonNegative = 5;
int count=1;
int product=1;
int factor=1;
System.out.println("Input a nonnegative integer: ");
nonNegative = input.nextInt();

[code]...

how I should correctly prompt the user to input the values.

View Replies


ADVERTISEMENT

Create Class Called Factorial Algorithm Which Will Compute / Print Factorial Of Integer Number On Screen

Dec 27, 2014

1)A factorial of a number X is equal to X*(X-1)*(X-2)*...*1.For example,3! is equal 3*2*1=6.Create a class called Factorial Algorithm which will compute and print the factorial of an integer number on the screen

2)Write a Java program to accept eight integers and a search element from the user and display whether the element is found or not.(Hint:use bubble sorting and binary search)

View Replies View Related

Read Integer From Keyboard Until Negative Number Is Entered

Apr 8, 2014

Basically i have a question ask me to write a program that read integer from keyboard until a negative number is entered, and then print out the max and min out of the number i have entered.

This is what i have done already which works, but i need to ignore the negative number when print out max and min...which i dont know how to do so. when i compile this program now it will always give me the negative number i enter at the end as minimum. which i need to ignore

Also if negative number is entered at once the program should print a error message say max and min are undefined.

public static void main(String[] args) {

Scanner in = new Scanner(System.in);
int large = Integer.MIN_VALUE;
int small = Integer.MAX_VALUE;
while(true) {
System.out.print("Enter a integer: ");
int n = in.nextInt();

[Code] ....

View Replies View Related

Accept Array Of Non-negative Integers And Return Second Largest Integer

May 22, 2015

Write a function that accepts an array of non-negative integers and returns the second largest integer in the array.

Return -1 if there is no second largest.

The signature of the function is int f(int[ ] a)

Examples:

if the input array isreturn{1, 2, 3, 4}3{{4, 1, 2, 3}}3{1, 1, 2, 2}1{1, 1}-1{1}-1{}-1 

In the signature what I understood is, I should write my function with the given signature,

The return type is "int"

method name is "f"

parameter is "a" right ?
 
Writing my doubts beside the particular line in the code

public static void main()  // In the answer why they didn't use the class ?

In main method why they didn't use parameters ?(String[] args)

{
a1(new int[]{1, 2, 3, 4}); // what is "a1" here is it array name ? this line initializing the array ?
a1(new int[]{4, 1, 2, 3});
a1(new int[]{1, 1, 2, 2});
a1(new int[]{1, 1});
a1(new int[]{1});
a1(new int[]{});


static int a1(int[] a) // what is "a" here parameter ? and "a1" is method name ? why they used the array name and method name same ?

{
int max1 = -1;
int max2 = -1;
for (int i=0; i<a.length; i++)

[Code] .....

View Replies View Related

Reading Entire Integer Text File And Putting Inside Array?

Apr 5, 2014

I have an assignment on sorting, i kno i can get the sorting down but im having an issue with inputing the 512 ints in a file into an array. the instructor provided us with a file with 4 equal sets of ints. i tried to make my array of size [scan.nextInt()] and it cuts off the last 21 ints. and skips the first int. how can i get all of the integers in the text file into my array? this is what i have so far. if i hard code the array to size 50000 and then try to print the array it compiles but errors out when running it.

System.out.println("Please Enter text file in this format, XXXXX.txt :");
String file =fileName.nextLine();
Scanner scan = new Scanner(new File(file));
int [] data = new int[scan.nextInt()]; <-------here it skips first int
int count= data.length;
for (int i=0; i<data.length-1;i++) {
data[i]=scan.nextInt();
}
System.out.print(Arrays.toString(data));

rst 4 ints in output are: 501, 257, 390, 478...., supposed to be 492,501,390....and last ints are: ....88, 83, 79, 0 and supposed to be :88 83 79 77 76 72 71 71 66 57 56 48 48 41 33 30 23 23 18 17 15 13 9....it replace last ints with 0. why ? and how do i fix this. attached it the text file

View Replies View Related

Calculating Factorial Of Int Number

Mar 2, 2014

I'm working on some exercises and I'm having some problems with a method. I want to create a method to calculate the Factorial of an int number. I already wrote code that asks the user to input an int number and it calculates the Factorial, and it works fine

i.e.: if I input 5 it outputs

5! = 120

as it should. Here's the code:

import java.util.Scanner;
public class Factorial1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number;
int total = 1;
 
[Code] ....

Now I want to make a method to re-use this code in other programs and I wrote this program:

public class TestClass {
public static void main(String[] args) {
System.out.print(factorial(5));
}
  public static int factorial(int x) {
int total = 0;

[Code] ....

But when I run this program it outputs 0 instead of 120. What is wrong with this code as it compiles just fine but doesn't work as intended.

View Replies View Related

Doing Factorial Of Number Within Certain Constraints

Feb 5, 2014

I'm suppose to be doing a factorial of a number within certain constraints (say a number between 5 and 10). I get the factorial easy enough but I'm getting it for every number no matter what I put in.

textio is used instead of scanner for our class.

Java Code:

public class Factorial {
public static void main(String[] args) {
int max = 0;
int x = 0;
long y = 0;

[Code] .....

Ideally I should be able to put in a number outside the range and the program will do nothing until I put a number in with the correct value.

View Replies View Related

Factorial - Writing Iterative Program Recursively

Apr 30, 2015

It was quite recently that Data Structures was introduced to me, so I started out writing some iterative programs recursively.I found some strange output which shouldn't have come out but if you take a look at these three codes

long factorial(long n)
{
if(n == 1)
{
return 1;
}
else
{
result = n*factorial(n-1);

[Code] ....

These are three versions of the code, achieving the same objective of obtaining a given number and returning the factorial, but in spite of the changes made to the code, they produce the same result. I needed a reason as to why it is so? I tried to dry run all the codes but at some point or the other I got confused, and had to start all over again and couldn't come up with a proper result.

View Replies View Related

Computing FFT In Java

May 7, 2015

I'm trying to divide the array into two parts and then compute. And save the changes made in a global array f, The problem is the code does't work for the second call. The changes are overshadowed. How can I start computing and make necessary changes so that the calculation is retained?

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

[code]....

View Replies View Related

Computing FFT In Java

May 7, 2015

I'm trying to divide the array into two parts and then compute. And save the changes made in a global array f, The problem is the code does't work for the second call. The changes are overshadowed. How can I start computing and make necessary changes so that the calculation is retained?

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

[code]....

View Replies View Related

Simple For Loop - Determine Factorial Of A Number Entered By User

Jun 28, 2014

I'm trying to learn Java and my current project is to write a short program to determine the factorial of a number entered by the user. I haven't looked. There may be a method that will do it, but I want to use a for loop specifically.

What I have compiles just fine. I'm actually pretty thrilled just with that. Here is what I have:

class factorial {
public static void main( String[] args) {
Scanner scan = new Scanner(System.in );
int num;
int product = 1;

[Code] ....

View Replies View Related

Numerically Computing Binomial Coefficient

Jan 29, 2015

So I was given the program that calculates N!/[R!(N-R)!] and it has an overflow error after it passes N=18 and then starts spiting out incorrect answer. I'm supposed to figure out a way to protect the user from getting erroneous results when computing the formula (i.e. N!/[R!(N-R)!]).

HERE IS THE PROGRAM:

public class Combination {
private static final int defaultNMax = 30;
public Combination() {}
int compute(int N, int R) {
int i;
int numerator;
int denominator;
numerator = 1;

[Code] .....

HERE ARE THE RESULTS IF YOU WANT TO SEE THEM:

N=1C(1,0)=1
N=2C(2,1)=2
N=3C(3,1)=3
N=4C(4,2)=6
N=5C(5,2)=10
N=6C(6,3)=20
N=7C(7,3)=35

[Code] .....

View Replies View Related

Java Computing Height Of Stack

Jun 2, 2015

Compute the height of a stack. Then determine whether that value is found in the stack element .

View Replies View Related

Computing New String - Memory Out Of Heap Error

Sep 28, 2014

Given a string, compute a new string where identical chars that are adjacent in the original string are separated from each other by a "*". My implementation :

package com.tcs.dash;
public class StringBuild {
public String edit(String userIp){
StringBuilder builder = new StringBuilder(userIp);
String replaceText = "";
for(int i = 0; i < builder.length() - 1; i++){
if(builder.charAt(i) == builder.charAt(i+1)){
replaceText = builder.charAt(i) + "*" + builder.charAt(i+1);
builder = builder.replace(i, i+1, replaceText);
}
}
return builder.toString();
}
}

I am getting error at line 13. An exception actually.

I/P given = aaaa

Console:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Unknown Source)
at java.lang.AbstractStringBuilder.expandCapacity(Unknown Source)
at java.lang.AbstractStringBuilder.ensureCapacityInternal(Unknown Source)
at java.lang.AbstractStringBuilder.replace(Unknown Source)
at java.lang.StringBuilder.replace(Unknown Source)
at com.tcs.dash.StringBuild.edit(StringBuild.java:13)
at com.tcs.dash.StringBuildExample.main(StringBuildExample.java:14)

View Replies View Related

Computing Square Root Of A Number Without Using Loops?

Sep 2, 2014

Some algorithm in computing the square root of a number without using any loops?

View Replies View Related

Finite Element In Java - Computing Stiffness Matrix For ISOTROPIC Case

Apr 2, 2014

I build some finite element in java. I try to optimize my running time. I do some double loop and use inside the loop in if else statement and also in switch case .

The loop is very long, sometimes become ~500 X 500.

You think that if i avoid from the if statement and the switch case inside the loop i will improve the time calculation by at least 10%?There is something that i must to avoid ?

// Computing stiffness matrix.
switch (materialType) {
case ISOTROPIC:
// Computing stiffness matrix for ISOTROPIC case.
for (int row = 0, nvfi2 = nvfi * 2, index = 0, fieldsNvf = fields * nvfi; row < fieldsNvf; row++) {
if (row == nvfi) {
leftZeroMatrix = 3;

[Code] ....

View Replies View Related

Can't Seem To Get Value For Integer 1 And Integer 2 To Pass With SetValue Method

Aug 10, 2014

public class MyInteger {
private int value;
public MyInteger(int number){
value = number;
System.out.println("Constructor created with value of " + value);

[code]....

I can't seem to get the value for integer1 and integer2 to pass with the setValue method. I get a runtime error stating the I need to have an int value for these two integers.

View Replies View Related

Can't Get Negative Values Working

Nov 11, 2014

when i input a positive integer it works but when i input a negative number it doesn't work

my pseudo code:

READ input
WHILE( NOT CORRECT INPUT)
READ INPUT AGAIN;
ENDWHILE
DECLARE array arr[input]
FOR(i=0 to input-1)
arr[i]= Random number from 0 to 100;
ENDFOR
DISPLAY ARRAY

error message when i input -5 : Exception in thread "main" java.lang.NegativeArraySizeException atPosNeg.main<PosNeg.java:36>
 
import java.util.*;
class PosNeg{
 public static void main(String args[]) {
  Random generator = new Random();
Scanner scan = new Scanner(System.in);

[code]....

View Replies View Related

Replace Negative Zero With Zero When Printing?

Mar 2, 2015

How do you replace negative zero value with a zero value when Printing results:

I want to remove the minus sign in -0.0000 and instead have 0.0000.

I am Printing coordinates and I do not want to have negative zero.

the coordinates are defined as double.

System.out.format(java.util.Locale.US," %.4f %.4f %.4f %.4f%n"xCur ,yCur,xNext,yNext);

0.0000 1.0000 -0.0000 0.0000

View Replies View Related

Negative Numbers In Binary

Mar 7, 2014

I need understanding why

1111 1101 = -3

View Replies View Related

Subtracting A Negative Fraction?

Mar 10, 2014

For some reason, I'm getting the correct result, but my negative sign is having issues. For example, if I do 1/4 - (-2/4), I get (-3/4).

Here is my minus method for subtracting fractions.

/**
Subtracts a fraction from another fraction.
@param toUse, the fraction to subtract.
@return minusFraction, the result after subtraction.
*/
public Fraction minus(Fraction toUse)

[Code] .....

Here is my reduce() method, just in case...

/**
Reduces the fraction, if possible, to it's simplest form.
Converts negative fractions to the form -x/y, or if -x/-y --> x/y
*/
private void reduce() {
int lowest = Math.abs(numerator);
int highest = Math.abs(denominator);

[code]...

I only switched an operator from my previous addition method, given here as well. I think only switching the + to a - may have caused my issue.

/**
Adds two fractions together.
@param toUse, the fraction to be added.
@return plusFraction, the sum of the two fractions.
*/
public Fraction plus(Fraction toUse) {

[Code] .....

View Replies View Related

Negative Character Literal?

Jun 3, 2014

char c=(char)-65;

This is legal but how ?? what is the value actually being stored in c ? The output is shown as ﾿.

View Replies View Related

Finding Binary Of Negative Numbers?

Mar 22, 2014

How do u find the binary of negative numbers? I already did it for positive numbers,?

View Replies View Related

How To Avoid Getting Negative Numbers Of Coins

Oct 18, 2014

how to avoid getting negative numbers of coins, use casting and mod to show how many quarters, dimes, nickels, and pennies there are?

import java.util.Scanner;

public class VM
{
public static void main(String[] args)
{
//money deposit
Scanner input = new Scanner(System.in);

[code]....

View Replies View Related

Byte Array Negative Values

Mar 30, 2015

I am new to Android. I have byte array of size 10. I am passing the Decimal values (131 - 140) to byte array. But while printing I get Negative (-) values with decreasing order .

How can I get same value as positive values?

Or How can I store positive value e.g. 131 as byte array element.

Please not my requirement is array must be ByteArray only

View Replies View Related

Getting Negative Number For Product Of Odd Integers

Sep 18, 2014

I am not sure what is happening with my code, but it is giving me a negative number. I am trying to write a program that calculates the product of the odd integers between 1 and 25. I messed with the program and as soon as you enter a number over 22, the end result is a negative number.

int total = 1;
for (int i = 1; i <= 25; i += 2){
total *= i;
}
System.out.println("Product:" + total);

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved