Make a util class with three methods. First method's name is add, that returns the result by adding two numbers.
Second method's name is multiply, that returns the result by multiplying two numbers.
Third's method name is division that returns a result by dividing first parameter by second parameter.
Then call a method from this class called main and print the results 6 times for each method call? I'm having trouble with this part.
This is what I've got so far:
public class Util {
public static int add(int a, int b) {
int result = a + b;
System.out.println("result = " + result);
return result;
}
public static int multiply(int a, int b) {
int result = a * b;
System.out.println("result = " + result);
return result;
}
public static int divide(int a, int b) {
int result = a / b;
System.out.println("result = " + result);
return result;
}
public static void main(String[] args) {
int res = multiply(5, 2);
System.out.println("res = " + res);
res = add(5, 2);
System.out.println("res = " + res);
res = divide(5, 2);
System.out.println("res = " + res);
}
}
How would I do this: call a method from this class called main and print the results 6 times for each method call?
just use a for loop like that:
public static void main(String[] args) {
for (int i = 0; i <= 6; i++) {
System.out.println(multiply(5, 2));
System.out.println(add(5, 2));
System.out.println(divide(5, 2));
}
}
or from another class:
public class Main()
{
private Util myUtil;
public void calculate()
{
for (int i = 0; i <= 6; i++) {
System.out.println(myUtil.multiply(5, 2));
System.out.println(myUtil.add(5, 2));
System.out.println(myUtil.divide(5, 2));
}
}
public static void main(String[] args) {
Main myMain = new Main();
myMain.calculate();
}
Related
I would like to send multiple values from my getMultiples method to my main method using a return statement and no print or println statements.
public class StaticMethods {
public static void main (String[] args) {
int a = 6;
int b = 9;
int result = getMultiple(a,b);
System.out.println(result + "\n")
System.out.println("The first " + a + " multiples of " + b + " are: ");
int p = getMultiples(a,b);
}
public static int getMultiple(int a,int b) {
return (int) (a * b);
}
public static int getMultiples(int a, int b) {
int p = 0;
for (int i = 1; i <= a; i++) {
p = getMultiple(a,i);
}
return (p);
}
}
I have tried putting the return statement in the for loop but it does not work.
In Java as soon as return is encountered in the code, method is removed from execution stack and flow is returned back to calling method. So you can not return multiple values from a method. Rather you should create a list/array and return that as below(array example):
public class StaticMethods {
public static void main (String[] args) {
int a = 6;
int b = 9;
int result = getMultiple(a,b);
System.out.println(result + "\n");
System.out.println("The first " + a + " multiples of " + b + " are: ");
int p[] = getMultiples(a,b);
}
public static int getMultiple(int a,int b) {
return (int) (a * b);
}
public static int[] getMultiples(int a, int b) {
int[] p = new int[a];
for (int i = 1; i <= a; i++) {
p[i-1] = getMultiple(a,i);
}
return p;
}
}
I am writing code in Java which has multiple methods and these methods have multiple variables. I want the other methods to access the variables of another method using actual and formal parameters. How can I do it?
I am pasting an example of the problem I'm facing.
Error : variable is not defined.
Code
public class example {
public void addition() {
int a = 0;
int b = 10;
int c = a + b;
}
public void result() {
System.out.println("The result for the above addition is" + c);
}
}
IM GETTING AN ERROR SAYING VARIABLE IS NOT DEFINED
You should declare c as global variable
public class Example {
int c;
public void addition() {
int a = 0;
int b = 10;
c = a + b;
}
public void result() {
System.out.println("The result for the above addition is " + c);
}
public static void main(String[] args) {
Example e = new Example();
e.addition();
e.result();
}
}
well, your java syntax is quite wrong... if you need to do an addition, you can do as follows:
public class Addition {
public static int addition(int a, int b)
{
int c= a + b;
return c;
}
public static void main(String[] args) {
int a = 1;
int b = 10;
int c = addition(a,b);
System.out.println("The result for the above addition is " + c);
}
}
where addition function does add a + b and return the result to your main method.
I want to time how long my code takes to perform on average over many test runs. In each test run, doWork() performs the work that I want to time. But I also want to checkWork() in each test run without it counting towards the time. I'm going to have many similar Exercise# classes, so I'd like to abstract the testing via a TestInterface. Is my current way a reasonable approach? Or is there a better design pattern / standard approach? Thanks in advance.
#FunctionalInterface
public interface TestInterface {
void test(final int NUM_TESTS);
}
public class TimeTests {
public static void test(TestInterface ti, final int NUM_TESTS, String testName) {
DecimalFormat df = new DecimalFormat("#.####");
long start = System.nanoTime();
ti.test(NUM_TESTS);
System.out.println("DEBUG: " + testName + " took "
+ df.format((System.nanoTime() - start) * 1.0 / NUM_TESTS)
+ " nanoseconds on average for " + NUM_TESTS + " tests");
}
}
public class Exercise1 {
private static final int NUM_TESTS = (int) Math.pow(10, 6);
private static void mainWork(List<Integer> A) {
// do stuff and time it
}
private static void checkWork(List<Integer> A) {
// do stuff but don't count it towards the time
}
public static void main(String[] args) {
TimeTests.test((NUM_TESTS_LOCAL) -> {
for (int i = 0; i < NUM_TESTS_LOCAL; ++i) {
List<Integer> A = new ArrayList<>();
// add random elements to A
mainWork(A);
checkWork(A);
}
}, NUM_TESTS, "Exercise1");
}
}
Okay, I think I managed to put together a decent framework (is this the right word?) for this task. If anybody could chime in to let me know if my approach is any good, I'd really appreciate it.
While my code seems to work fine for my use cases so far, I have a few questions:
In the interface definition of public interface CloneableTestInput<T extends CloneableTestInput<T>>, how is the type template <T extends CloneableTestInput<T> not a circular definition? I'm not sure I fully understand what that type template is saying.
Is there a way to make a generic CloneableList class that implements CloneableTestInput<List>? Currently, I need to make a separate implementation for each Collection type (e.g. ArrayList, LinkedList, ...). Similarly, is it possible to make a generic CloneableSet class that implements CloneableTestInput<Set>?
Thanks in advance :)
Testing Framework
Part I - An interface for test inputs
This allows TimeTests.java to work for generic input types.
public interface CloneableTestInput<T extends CloneableTestInput<T>> extends Cloneable {
T clone();
}
public class CloneableString implements CloneableTestInput<CloneableString> {
public String data;
public CloneableString() {}
public CloneableString(String input) { data = input; }
public CloneableString clone() { return new CloneableString(String.valueOf(data)); }
}
public class CloneableArrayList extends ArrayList implements CloneableTestInput<CloneableArrayList> {
public CloneableArrayList(ArrayList input) {
this.addAll(input);
}
#Override
public CloneableArrayList clone() {
return new CloneableArrayList(this);
}
}
Part II - An interface for timing tests
#FunctionalInterface
public interface TimeTestsInterface<outputType> {
void test(Callable<CloneableTestInput> formInput
, Function<CloneableTestInput, outputType> runAlgorithm
, Function<CloneableTestInput, outputType> getKnownOutput
, BiFunction<outputType, outputType, Boolean> checkResults
, final int NUM_TESTS, String testName);
}
public class TimeTests<outputType> implements TimeTestsInterface<outputType> {
public void test(Callable<CloneableTestInput> formInput
, Function<CloneableTestInput, outputType> runAlgorithm
, Function<CloneableTestInput, outputType> getKnownOutput
, BiFunction<outputType, outputType, Boolean> checkResults
, final int NUM_TESTS, String testName) {
try {
DecimalFormat df = new DecimalFormat("#.####");
long total = 0, start;
for (int i=0; i < NUM_TESTS; ++i) {
CloneableTestInput input = formInput.call();
CloneableTestInput orig_input = input.clone();
start = System.nanoTime();
outputType algorithmResult = runAlgorithm.apply(input);
total += System.nanoTime() - start;
outputType expectedResult = getKnownOutput.apply(orig_input);
assert(checkResults.apply(algorithmResult, expectedResult));
}
System.out.println("DEBUG: " + testName + " took "
+ df.format(total * 1.0 / NUM_TESTS)
+ " nanoseconds on average for " + NUM_TESTS + " tests");
} catch (Exception|AssertionError e) {
System.out.println(e.toString() + " - " + e.getMessage() + " - ");
e.printStackTrace();
}
}
}
Example Usages
Increment a BigInteger (uses CloneableArrayList)
/**
* Problem 6.2 from EPI
* Given an array A of digits encodiing a decimal number D,
* with MSD at A[0]. Update A to hold D + 1.
*/
public class PlusOne {
private static final int NUM_TESTS = (int) Math.pow(10, 5);
private static final int ARR_LENGTH = (int) Math.pow(10, 2);
private static ArrayList<Integer> plusOne(ArrayList<Integer> A) {
int n = A.size() - 1;
A.set(n, A.get(n) + 1);
for (int i = n; i > 0 && A.get(i) == 10; --i) {
A.set(i, 0);
A.set(i-1, A.get(i-1) + 1);
}
if (A.get(0) == 10) {
// Need additional digit up front as MSD
A.set(0,0);
A.add(0,1);
}
return A;
}
private static ArrayList<Integer> randArray(int len) {
ArrayList<Integer> A = new ArrayList<>();
if (len == 0) return A;
Random rgen = new Random();
A.add(rgen.nextInt(9) + 1);
--len;
while (len != 0) {
A.add(rgen.nextInt(10));
--len;
}
return A;
}
public static void main(String[] args) {
Callable<CloneableTestInput> formInput = () -> new CloneableArrayList(randArray(ARR_LENGTH));
Function<CloneableTestInput, ArrayList<Integer>> runAlgorithm =
(input) -> plusOne((ArrayList<Integer>) input);
Function<CloneableTestInput, ArrayList<Integer>> getKnownOutput =
(orig_input) -> {
BigInteger B = new BigInteger(Joiner.on("").join((ArrayList<Integer>) orig_input));
B = B.add(BigInteger.valueOf(1));
ArrayList<Integer> expectedOutput = new ArrayList<>();
while (B.compareTo(BigInteger.valueOf(0)) > 0) {
expectedOutput.add(0, B.mod(BigInteger.valueOf(10)).intValue());
B = B.divide(BigInteger.valueOf(10));
}
return expectedOutput;
};
BiFunction<ArrayList<Integer>, ArrayList<Integer>, Boolean> checkResults = List::equals;
TimeTests<ArrayList<Integer>> algTimer = new TimeTests<>();
algTimer.test(formInput, runAlgorithm, getKnownOutput, checkResults, NUM_TESTS, "PlusOne");
}
}
Can String be rearranged as a palindrome? (uses CloneableString)
public class CanStringBePalindrome {
private static final int INPUT_STRING_LENGTH = (int) Math.pow(10, 2);
private static final int NUM_TESTS = (int) Math.pow(10, 6);
private static boolean canFormPalindromeHash(final String s) {
Map<Character, Integer> charFreqs = new HashMap<>();
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (!charFreqs.containsKey(c))
charFreqs.put(c, 1);
else
charFreqs.put(c, charFreqs.get(c) + 1);
}
int oddFreqCount = 0;
for (Map.Entry<Character, Integer> entry : charFreqs.entrySet()) {
if ((entry.getValue() % 2) != 0 && (++oddFreqCount > 1))
return false;
}
return true;
}
private static boolean canFormPalindromeSorting(final String s) {
// TODO : find faster/simpler way of getting frequency counts
char[] a = s.toCharArray();
Arrays.sort(a);
int oddFreqCount = 0;
int numCurrChar =1;
for (int i = 1; i < a.length && oddFreqCount <= 1; ++i) {
if(a[i] != a[i-1]) {
if ((numCurrChar & 1) != 0)
++oddFreqCount;
numCurrChar = 1;
} else
++numCurrChar;
}
if ((numCurrChar & 1) != 0)
++oddFreqCount;
return oddFreqCount <= 1;
}
private static String randString(int len) {
StringBuilder sb = new StringBuilder();
Random rgen = new Random();
while (len-- > 0)
sb.append((char)(rgen.nextInt(26) + 'A'));
return sb.toString();
}
public static void main(String[] args) {
Callable<CloneableTestInput> formInput = () -> new CloneableString(randString(INPUT_STRING_LENGTH));
Function<CloneableTestInput, Boolean > runAlgorithm =
(input) -> canFormPalindromeHash(((CloneableString)input).data);
Function<CloneableTestInput, Boolean> getKnownOutput =
(orig_input) -> canFormPalindromeSorting(((CloneableString)orig_input).data);
BiFunction<Boolean, Boolean, Boolean> checkResults = Boolean::equals;
TimeTests<Boolean> algTimer = new TimeTests<>();
algTimer.test(formInput, runAlgorithm, getKnownOutput, checkResults
, NUM_TESTS, "CanStringBePalindrome");
}
}
I already posted this question but I gave it a try I'm not sure if I'm on the right track:
Make a util class with three methods. First method's name is add, that returns the result by adding two numbers.
Second method's name is multiply, that returns the result by multiplying two numbers.
Third's method name is division that returns a result by dividing first parameter by second parameter. How would I do this part?
This is what I've got so far:
public class Util {
public static int add(int a, int b) {
int result = a + b;
System.out.println("result = " + result);
return result;
}
public static void main(String[] args) {
int res = add(5, 2);
System.out.println("res = " + res);
}
public static int multiply(int a, int b) {
int result = a * b;
System.out.println("result = " + result);
return result;
}
public static void main(String[] args) {
int res = multiply(5, 2);
System.out.println("res = " + res);
}
}
I think what you are confusing is the multiple main methods. You should only have 1 entry point (main) in your code, the rest of your util class is correct.
public class Util {
public static int add(int a, int b){
int result = a + b;
System.out.println("result = " + result);
return result;
}
public static int multiply(int a, int b){
int result = a * b;
System.out.println("result = " + result);
return result;
}
public static int divide(int a, int b){
int result = a / b;
System.out.println("result = " + result);
return result;
}
public static void main(String[] args) {
int[] aValues = {1,2,3,4};
int[] bValyes = {4,3,2,1};
for (int i = 0; i < aValues.length; i++) {
int a = aValues[i];
int b = bBalues[i];
int res = multiply(a, b);
System.out.println("res = " + res);
res = add(a, b);
System.out.println("res = " + res);
res = divide(a, b);
System.out.println("res = " + res);
}
}
}
public class For {
public static void main(String[] args){
for(int i=2; i<=1024; i *= 2){
System.out.println("Count is: " + i);
}
}
public class While {
public static void main(String[] args){
int i = 1;
while (i < 1024) {
i *= 2;
System.out.println("Count is: " + i);
}
}
public class DoWhile {
public static void main(String[] args){
int i = 1;
if (i < 1024) {
do { i*=2;
System.out.println("Count is: " + i);
} while (i < 1024);
}
}
How would one convert the for loop/while loop so it does the same thing, but using a recursive function?
Like so:
public class Recursive {
public void r(int i) {
if (i < 1024) {
i *= 2;
System.out.println("Count is: " + i);
r(i);
}
}
public static void main(String[] args) {
Recursive r = new Recursive();
r.r(1);
}
}
Take the loop of main and put it in its own function with an argument int i. In that function, rewrite the loop to
If the loop condition is false (i >= 1024), then return
Else, recursive call with argument i*2.
Call the function with argument 1 or 2, depending on which of your programs you're rewriting (they don't entirely match).
Recurrent loop can look like this:
class Main
{
public static void main(String[] args){
RecWhile(1);
}
public static void RecWhile(int i) {
if (i < 1024) {
i = i*2;
System.out.println("Count is: " + i);
RecWhile(i);
}
}
}
public class Test1 {
public static void main(String[] args) {
Test1 mainFunc = new Test1();
int[] arr = {1,2,4,3,5,6};
int start=0;
int end=arr.length;
mainFunc.callRecursiveFun(start, end, arr);
}
public int callRecursiveFun(int start, int end, int[] arr) {
int arrLen = end;
if(arrLen == 0) {
return 0;
} else {
System.out.println("Loop Index at "+start +": "+arr[start]);
}
return callRecursiveFun(start+1, end-1, arr);
}
}