Utility Test Java - java

"public static int readInt(String s)" wat does this exactly do in a program?? Currently i need to use 4 of these but they all different and for the one i showed up here, i need to make a program where the user is prompted something and if the input is an int then it gets displayed and then goes to the second input for the user and if right then goes, but else if not an int; if its a double then print out "This is not valid..." and then will repeat the first one again and will also do the same thing for the second input if the second one prompted by the user is not an integer. There will be a total of two inputs for the user. What should i do to make a program for this? I am confused of how to use this "public static int readInt(String s)".
package rationalnumber;
import java.util.*;
public class Utility
{
public static int readInt(String s)
{
}
public static double readDouble(String s)
/**
* Generates a random integer between min and max, inclusive
* Precondition: min <= max
* #param min lower bound for the random integer
* #param max upper bound for the random integer
* #return A random integer
*/
public static int randomInt(int min, int max)
{
}
/**
* Computes the gcd between 2 nonnegative integers
* Precondition: num1 >= 0, num2 >= 0
* #param num1 The first integer
* #param num2 The second integer
* #return the gcd of num1 and num 2, gcd is 1 if both are 0,
* gcd is the non-zero number if only one is 0.
*/
public static int gcd(int num1, int num2)
{
}
this is like part of the code....i also need to add comments on here well so far those are the last two parts of my code but i couldnt start it without the first two parts.
package rationalnumber;
/**
* Test program for the Utility class
*/
public class UtilityTest
{
public static void main(String[] args)
{
String prompt1 = "Enter first integer: ";
String prompt2 = "Enter second integer: ";
int a = Utility.readInt(prompt1);
int b = Utility.readInt(prompt2);
int small = Math.min(a, b);
int large = Math.max(a, b);
System.out.println("A few random integers: ");
System.out.println(Utility.randomInt(small, large));
System.out.println(Utility.randomInt(small, large));
System.out.println(Utility.randomInt(small, large));
System.out.println(Utility.randomInt(small, large));
System.out.printf("The gcd of %d and %d is ", a, b);
System.out.println(Utility.gcd(Math.abs(a), Math.abs(b)));
}
}
in the end i use this which is in the same program but in another folder to run it.

Break it down:
Public -- Signifies this is a public method
int -- Signifies that the function will return an integer
readInt -- Name of the function
String s -- Signifies that the function takes a parameter of type String that will be referred to as s within the function.

Public --a public method
int -- return tpye integer
readInt -- Name of the function that will read a string and return it as an integer.in your program it will read prompt1 and prompt2 , like take input form the user , and store them int a and int b.
String s -- Signifies that the function takes a parameter of type String that will be referred to as s within the function.

Related

How can I use an instance variable with a static recursive method in java? (cumulative sum problem)

I'm writing some code to figure out the cumulative sum between two numbers recursively, but the method i wrote requires updating a would-be instance variable called "ans".
Since the problem I'm looking at requires the method header to be "public static int sumBetween(int a, int b)", I'm having issues using a non-static variable for this method.
Currently, I have the variable ans set to static but this can of course only run once, and if I call the method afterwards it starts with the variable ans being the last answer, not 0.
I'm new to recursion so I though I would start with some of these problems. Thank you!
Code:
/* EXERCISE 2: Cumulative sum
*
* public static int sumBetween(int a, int b)
* The goal is to find the sum of the values from 𝑎 to 𝑏. In math, we would write this problem as ∑𝑏𝑖=𝑎𝑖
*/
static int ans =0;
public static int sumBetween(int a, int b) {
// base case
if (a==b) {
ans = ans +b;
return ans;
}
// recursion
ans = ans + a + b;
return sumBetween(a+1, b-1);
}
Why use recursion, the goal can be achieved in O(1) complexity using maths
Sum of the number between a and b
- Step 1 find sum from 1 to a i.e. (a*(a+1))/2
- Step 2 find sum from 1 to b i.e. (b*(b+1))/2
- Step 3 Subtract out the result of step 2 by step 1 and add a
ans = (b*(b+1)/2) - (a*(a+1)/2) + a
Someone answer a second ago but deleted their answer - regardless, thank you stranger because it worked:
public static int sumBetween(int a, int b) {
return sumBetweenHelper(a, b, 0);
}
public static int sumBetweenHelper(int a, int b, int ans) {
// base case
if (a==b) {
ans = ans +b;
return ans;
}
// recursion
ans = ans + a + b;
return sumBetweenHelper(a+1, b-1, ans);
}

Im a really stumped on this Methods and Recursion

so I'm not really sure what to do what I've already done
/*
* a collection of methods to be completed
* complete each TODO body-code for the given methods
* use recursion for the first method and last method
*/
public class Methods
/*
* method to compute value of f(n) where:
* f(1) = 1
* f(n) = n + f(n-1) for n>1, n is even
* f(n) = n * f(n-1) for n>1, n is odd
*/
public static int f(int n) {
//TODO
return 0; //dummy line, replace this
}
/*
* method to compute the sum of the proper divisors of a given positive integer, n
* e.g., if n is 12, the sum of the proper divisors is:
* 1 + 2 + 3 + 4 + 6 = 16
* note: proper divisors are all divisors of an integer other than itself
*/
public static int sumOfDivisors(int n) {
//TODO
return 0; //dummy line, replace this
}
/*
* method that returns a String indicating whether a given positive integer, n, is:
* "abundant" - sum of proper divisors is greater than n
* "deficient" - sum of proper divisors is less than n
* "perfect" - sum of proper divisors is equal to n
*/
public static String numberType(int n) {
//TODO
return "foo"; //dummy line, replace this
}
/*
* method that returns the sum of the digits of the positive integer, n
* e.g., if n = 5403, the method will return:
* 5+4+0+3 = 12
* note: the right-most (1's) digit can be found using n%10
* the remaining digits (all but the 1's digit) can be found using n/10
*/
public static int sumOfDigits(int n) {
//TODO
return 0; //dummy line, replace this
}
//a dummy main method, not used
public static void main(String[] args) {
System.out.println("This program is not meant to be run on its own.");
System.out.println("This is just a dummy main method.");
}
} //end Methods
so yea any help would be great.
so I'm not really sure what to do what I've already done
You actually wrote only method declarations.
Your task is really well documented, you may try out to implement the utilities(like a public int[] divisors(int n) and so on) and eventually come back here and ask help about your concerns, posting either code or errors.
PS:This seems an academic assignment , have you checked some books, or notes?

Using int, double and long in calculation of powers

I'm having trouble figuring out when to use int, double and long.
I'm working on calculating the power of an integer and return the result as long as the power provided is not a negative number.
For the assignment, I'm required to use the following code to start:
public static long powerN(int number, int power) {
Here's what I came up with:
public class PowerCalculator
{
/**
* Calculate the non-negative power of an integer number. If a negative power is input, the method returns 1.
*
* #param number The number to take power.
* #param power The power factor to be taken to.
* #return The calculation result after taking power of the integer number.
*/
public static long powerN(int number, int power) {
if (power > 0)
{
double result = (Math.pow(number, power));
return result;
}
else
{
return 1;
}
}
}
I know I'm messing up the use of int, double or long but I don't know how to fix it.
Wait! If you're doing it yourself, use a faster algorithm like Exponentiation by squaring, something like this:
long powerN(long number, int power){
long res = 1;
long sq = number;
while(power > 0){
if(power % 2 == 1){
res *= sq;
}
sq = sq * sq;
power /= 2;
}
return res;
}
You could do it by yourself:
public static long powerN(
int number,
int power
) {
if(power == 0) return 1;
int result = number;
while(power > 1) {
result*=number;
power--;
}
return (long)result;
}
PS: This does not handle negative powers.
In case you'd like to use Math.pow:
public static long powerN(int number, int power) {
return (long) Math.pow(number, power);
}
Option 1: Cast result of Math.pow to long:
public class PowerCalculator{
/**
* Calculate the non-negative power of an integer number. If a negative power is input, the method returns 1.
*
* #param number The number to take power.
* #param power The power factor to be taken to.
* #return The calculation result after taking power of the integer number.
*/
public static long powerN(int number, int power) {
// write your code after this line
if (power < 0){
return 1;
} else{
return (long) Math.pow(number, power);
}
Option 2: without using Math.pow
public class PowerCalculator{
/**
* Calculate the non-negative power of an integer number. If a negative power is input, the method returns 1.
*
* #param number The number to take power.
* #param power The power factor to be taken to.
* #return The calculation result after taking power of the integer number.
*/
public static long powerN(int number, int power) {
// write your code after this line
long result = 1;
while (power > 0) {
result *= number;
power--;
}
return result;
}

Printing Result based on Input from JOptionPane

I am student, trying to finish a homework lab. Right now I am struggling to use the input from JOptionPane to display the results based on the input. There are two files to my lab, the CoinCounterTester.java and the CoinCounter.java. Both compile but it should print the total numbers of dollars and the total number of cents (teachers instructions) "Output should be in the console window, and should demonstrate the use of and escape sequences". I'm not sure if any part of the tester is correct but I think the JOptionPane methods are correct. I also think I'm supposed to parse them to get them into integer form , however I do not know how to print the designated number of dollars and number of cents left over based on user input. Can anyone explain?
Thanks
Edit:
Ok the answer seems like its correct but I'm confused about using the constructor call. What would you put for the parameters for the constructor call, I put
CoinCounter coinCounter = new CoinCounter(int quarters, int dimes, int nickels, int pennies);
but got seven errors
Edit 2:
I have now not included the variable type as well wisely suggested and input
CoinCounter coinCounter = new CoinCounter(quarters, dimes, nickels, pennies);
but I still get 4 errors (error cannot find symbol) :(. Can anyone suggest a correction please?
Edit 3: Added the println statements and moved the constructor call to the bottom but whenever I run the program I cannot get the file to print the number of dollars and the number of cents?!
import javax.swing.JOptionPane;
/**
* A class to test the CoinCounter class
*/
public class CoinCounterTester
{
/**
* Tests methods of the CoinCounter class
* #param args not used
*/
public static void main(String[] args)
{
String quarter = JOptionPane.showInputDialog("Enter the quantity of quarters");
int quarters = Integer.parseInt(quarter);
String dime = JOptionPane.showInputDialog("Enter the quantity of dimes");
int dimes = Integer.parseInt(dime);
String nickel = JOptionPane.showInputDialog("Enter the quantity of nickels");
int nickels = Integer.parseInt(nickel);
String penny = JOptionPane.showInputDialog("Enter the quantity of pennies");
int pennies = Integer.parseInt(penny);
CoinCounter coinCounter = new CoinCounter(quarters, dimes, nickels, pennies);
System.out.println(coinCounter.getDollars());
System.out.println(coinCounter.getCents());
System.exit(0);
}
}
/**
* A CoinCounter has a specific number of cents. It can provide the number of dollars and the
* number of cents that it contains
*/
public class CoinCounter
{
// constants
//*** These are class constants so they need public static
public static final int QUARTER_VALUE = 25;
public static final int DIME_VALUE = 10;
public static final int NICKEL_VALUE = 5;
public static final int PENNY_VALUE = 1;
public static final int PENNY_PER_DOLLAR_VALUE = 100;
// instance field (one - holds the total number of cents EX: 8,534)
private int total;
/**
* Constructs a CoinCounter object with a specified number of pennies,
* nickels, dimes and quarters
* #param quarterAmount the amount of quarters
* #param dimeAmount the amount of dimes
* #param nickelAmount the amount of nickels
* #param pennyAmount the amount of pennies
*/
public CoinCounter(int quarters, int dimes, int nickels, int pennies)
{
total = quarters * QUARTER_VALUE + nickels * NICKEL_VALUE + dimes * DIME_VALUE + pennies;
}
// add remaining methods as described
/**
* getDollars returns the number of dollars in the CoinCounter
* #return the number of dollars
*/
public int getDollars()
{
int dollars = (int) total / PENNY_PER_DOLLAR_VALUE;
return dollars;
}
/**
* getCents returns the number the numbers of cents left over after the dollars are removed
* #return the number of cents left over
*/
public int getCents()
{
int cents = total % PENNY_PER_DOLLAR_VALUE;
return cents;
}
}
What you're looking for is a constructor call. You have all the values. You just need to create a CoinCounter to count them for you. An example of doing that would look like:
CoinCounter coinCounter = new CoinCounter(1, 2, 3, 4);
After you have your CoinCounter, you can call methods on it, like coinCounter.getCents(). You print things out using System.out.println(<whatever you want to print>). Those should be the three things you need to finish up.
Edit: Close! Look carefully at how you called the constructor and how I did it. What you did is like this:
CoinCounter coinCounter = new CoinCounter(int 1, int 2, int 3, int 4);
Compare it to my example above.
You only put the variable type there when you define the constructor, not when you call it.

Project Euler problem 2: sum of even Fibonacci numbers

I am trying to solve Project Euler problem 2 in Java:
public class Euler2 {
public static long GenerateFibonacci(int term) {
long sum = 0;
long fib = 0;
long f1 = 0;
long f2 = 1;
if (term <=1) return term;
for (int i = 1; i <= term; i++) {
fib = f1 + f2;
f1 = f2;
f2 = fib;
if(fib %2 ==0)
sum += fib;
}
return sum;
}
/**
* #param args
*/
public static void main(String[] args) {
int n = 100;
long result = GenerateFibonacci(n);
System.out.println("The sum of the even Fibonacci numbers is: "+result);
}
}
When n is small I get the right answer but for bigger values I get the wrong result. What's the problem here?
int is limited to 32-bit accuracy, long to 64-bit.
When you exceed the limit by adding numbers whose result is larger then the bit limit, they "roll over" and you lose the most significant bits from the result of the addition - essentially, they are "rounded" to 32/64 bits.
Here's an example of rolling over:
int i = Integer.MAX_VALUE; // 2147483647
i++; // -2147483648
Roughly speaking, each fibonnacci number is double the previous one, so roughly speaking you can only handle in the order of 64 iterations using a long as the total.
The largest long value in Java is 9223372036854775807. Adding 1 to this value produces -9223372036854775807 because the integer values in most programming languages come from a finite set of values, and when you reach the highest value and add one the sequence "wraps around" to the beginning.
If you need to go outside this range, which you will to get the 100th Fibonacci number, use BigInteger.
The sum is greater than Long.MAX_VALUE. You're correct (in your comment to #Bohemian) that n is less than that limit, but it is rather surprising how quickly this simple series can grow. The 100th Fibonacci number, for example, is 354224848179261915075. The sum of the first 100 is a 20 digit number, just to give you a feeling for the scale you're dealing with.
You need to use BigInteger, you can also use the fact that every third Fibonacci number is even.
public static BigInteger sumOfEvenFibonacci(int term) {
BigInteger sum = BigInteger.ZERO;
BigInteger f1 = BigInteger.ONE;
BigInteger f2 = BigInteger.ONE;
for (int i = 1; i <= term; i+=3) {
BigInteger fib = f1.add(f2);
sum = sum.add(fib);
f1 = f2.add(fib);
f2 = fib.add(f1);
}
return sum;
}
System.out.println(sumOfEvenFibonacci(100));
prints
1213946614199987541226
You can improve efficiency of 'GenerateFibonacci' with following code. This should be a comment but I can not format the code in comment, I am doing this in answer,
public class FibUtil {
//Constants used in equation to calculate nth fib term
private static final double fibA=1/Math.sqrt(5);
private static final double fibB=(1+Math.sqrt(5))/2;
private static final double fibC=(1-Math.sqrt(5))/2;
public static double getNthFibTerm(long n){
return fibA*(Math.pow(fibB, n)-Math.pow(fibC, n));
}
}
Further, based on euler 2 problem statement, you can just add only nth terms which are multiples of 3. I leave 'why' to you.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package evenfibonaccisum;
import java.math.BigInteger;
/**
*
* #author blades of Aragon
*/
public class EvenFibonacciSum {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
long a=0;
long b=1;
long fib=1;
int i=10;
long sum=0;
while(fib<=4000000){
fib=a+b;
a=b;
b=fib;
if(fib>=4000000){
break ;
}
else{
if(fib%2==0){
sum=sum+fib;
}
}
}
System.out.println("sum of even Fibonacci "+sum);
}
}

Categories