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);
}
}
}
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;
}
}
How can I create a java program using only if / else to order 3 numbers in descending order. I can not use for processes or array. Numbers are entered by the user.
Here's what i have so far. What should i do, is the user enters two integers that are the same? The code can only display one output.
import java.util.Scanner;
public class DescendingOrder
{
public static void main(String [] args)
{
//variable dec.
int a;
int b;
int c;
Scanner kbd = new Scanner(System.in);
//user prompt
System.out.println("Please enter three integers");
a=kbd.nextInt();
b=kbd.nextInt();
c=kbd.nextInt();
//program output
if (a>=b && b>=c && a>=c)
{
System.out.println("a b c");
}
if (a>=c && c>=b && a>=b )
{
System.out.println("a c b");
}
if (b>=a && a>=c && b>=c)
{
System.out.println("b a c");
}
if (b>=c && c>=a && b>=c)
{
System.out.println("b c a");
}
if(c>=a && a>=b && c>=b)
{
System.out.println("c a b");
}
if (c>= b && b>=a && c>=a)
{
System.out.println("c b a");
}
}
}
A simpler way you can do it is
if (a < b)
{
int temp = a;
a = b;
b = temp;
}
if (b < c)
{
int temp = b;
b = c;
c = temp;
}
if (a < b)
{
int temp = a;
a = b;
b = temp;
}
System.out.println(a + " " + b + " " + c);
If two numbers are the same it doesn't really matter, as 90 45 45 is the same as 90 45 45. (In the case of your code as written, however, you are correct in noticing that it does matter. You could fix this by changing all your if statements except the first one into else-if)
This question seems to be a thought exercise so consider this answer an alternative to the other correct answers for your consideration. Here my enterprise-y solution.
Step 0, refactor your code to make it testable and stub out the method that will do the actual work:
import static java.lang.System.in;
import static java.lang.System.out;
import java.util.Scanner;
public class DescendingOrder {
public static final void main(final String... args) { // unavoidable use of an array, please don't dock points
try (final Scanner kbd = new Scanner(in)) { // always close your Closeables
final int a = kbd.nextInt();
final int b = kbd.nextInt();
final int c = kbd.nextInt();
final DescendingOrder calculator = new DescendingOrder();
out.println(calculator.order(a, b, c));
}
}
public String order(final int a, final int b, final int c) {
return null;
}
}
Step 1, write a unit test:
import static java.lang.Integer.MAX_VALUE;
import static java.lang.Integer.MIN_VALUE;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
public class DescendingOrderTest {
private DescendingOrder orderer;
#Before
public void setUp() throws Exception {
orderer = new DescendingOrder();
}
#Test
public final void testOrderABC() {
final String result = orderer.order(MAX_VALUE, 0, MIN_VALUE); // don't forget the edge cases
assertEquals(MAX_VALUE + " " + 0 + " " + MIN_VALUE, result);
}
#Test
public final void testOrderACB() {
final String result = orderer.order(13, 5, 8);
assertEquals("13 8 5", result);
}
#Test
public final void testOrderBAC() {
final String result = orderer.order(4, 8, 2);
assertEquals("8 4 2", result);
}
#Test
public final void testOrderBCA() {
final String result = orderer.order(-8, -2, -4); // don't forget negative numbers
assertEquals("-2 -4 -8", result);
}
#Test
public final void testOrderCAB() {
final String result = orderer.order(1, -5, 5);
assertEquals("5 1 -5", result);
}
#Test
public final void testOrderCBA() {
final String result = orderer.order(MAX_VALUE, 0, MIN_VALUE);
assertEquals(MAX_VALUE + " " + 0 + " " + MIN_VALUE, result);
}
#Test
public final void testAllSame() {
final String result = orderer.order(53, 53, 53);
assertEquals("53 53 53", result);
}
}
Step 2, iteratively implement order until your tests pass:
public String order(final int a, final int b, final int c) {
if (a > b && a > c) {
return a + " " + order(b, c);
} else if (b > a && b > c) {
return b + " " + order(a, c);
}
return c + " " + order(a, b);
}
protected String order(final int x, final int y) {
if (x > y) {
return x + " " + y;
}
return y + " " + x;
}
It might not be the most computationally efficient, but I kept the method sizes small so it is clear what the code is meant to accomplish. I also do not need to scan through six scenarios to see that it is correct. If I assume that order( int, int ) is correct, then I only need to work through three scenarios to see that order( int, int, int ) is correct.
Obviously, this is overkill. But those constraints would never really exist.
I think your code was fine you were just printing wrong. You have to understand that a,b,c are variable of type int. when you use the + operator with two ints it performs an addition. If you use the + operator with an int and with a string it produces a concatenation. The int 'calls' to string turning the int into a string which produces String + String = concatenation.
Anyways, I think this is what you wanted. Let me know if this is what you wanted.
import java.util.Scanner;
public class Stackoverflow
{
public static void main(String [] args)
{
//variable dec.
int a;
int b;
int c;
Scanner kbd = new Scanner(System.in);
//user prompt
System.out.println("Please enter three integers");
a=kbd.nextInt();
b=kbd.nextInt();
c=kbd.nextInt();
//program output
if (a>=b && b>=c && a>=c)
{
System.out.println(a+" "+b+" "+c);
}
if (a>=c && c>=b && a>=b )
{
System.out.println(a+" "+c+" "+b);
}
if (b>=a && a>=c && b>=c)
{
System.out.println(b+" "+a+" "+c);
}
if (b>=c && c>=a && b>=c)
{
System.out.println(b+" "+c+" "+a);
}
if(c>=a && a>=b && c>=b)
{
System.out.println(c+" "+a+" "+b);
}
if (c>= b && b>=a && c>=a)
{
System.out.println(c+" "+b+" "+a);
}
}
}
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();
}
everyone so I'm writting a program that solves quadratics (one doubled root and two doubled roots this seems to work but somehow I can't get it to solve complex roots? any help.
import javax.swing.JOptionPane;
public class QuadMethods {
static double a=0;
static double b=0;
static double c=0;
public static void main(String[] args) {
getUserInput(); // gets values into a, b, and c
double disc = getTheDiscriminant(a,b,c);
if (disc ==0) {
displayDoubledRealRoot(a,b,c);
//} else if (disc < 0) {
//displayComplexConjugates();
} else if (disc > 0) {
displayUnequalRealRoots(a,b,c);
//} else {
//System.out.println("Help! Arithmetic has failed!");
//
}
}
public static void displayUnequalRealRoots(double a, double b, double c) {
double disc = getTheDiscriminant(a,b,c);
double r1 = (-b+Math.sqrt(disc)/ (2*a));
double r2 = (-b-Math.sqrt(disc)/ (2*a));
String s = "two roots " + r1 + " and " + r2;
JOptionPane.showMessageDialog(null, s);
}
public static void displayDoubledRealRoot(double a, double b, double c) {
String s = "One doubled root = " + (-b/(2*a));
JOptionPane.showMessageDialog(null, s);
}
public static double getTheDiscriminant(double a, double b, double c) {
return b*b - 4*a*c;
}
public static void getUserInput() {
JOptionPane.showMessageDialog(null, "Getting coeffecients for ax^2+bx+c=0");
a = getANumber("a");
b = getANumber("b");
c = getANumber("c");
}
public static double getANumber(String p) {
boolean iDontHaveANumberYet = true;
double r = 0;
do {
try {
String aStr = JOptionPane.showInputDialog("Enter \"" + p + "\"");
r = Double.parseDouble(aStr);
iDontHaveANumberYet = false;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Hey, I can't deal with that. Must enter legal number.");
}
} while (iDontHaveANumberYet);
return r;
}
}
The solution:
import javax.swing.JOptionPane;
public class QuadMethods {
static double a=0;
static double b=0;
static double c=0;
public static void main(String[] args) {
getUserInput(); // gets values into a, b, and c
double disc = getTheDiscriminant(a,b,c);
if (disc ==0) {
displayDoubledRealRoot(a,b,c);
} else if (disc > 0) {
displayUnequalRealRoots(a,b,c);
} else {
// New method
displayComplexRoots(a,b,c);
}
}
public static void displayUnequalRealRoots(double a, double b, double c) {
double disc = getTheDiscriminant(a,b,c);
double r1 = (-b+Math.sqrt(disc)/ (2*a));
double r2 = (-b-Math.sqrt(disc)/ (2*a));
String s = "two roots " + r1 + " and " + r2;
JOptionPane.showMessageDialog(null, s);
}
public static void displayDoubledRealRoot(double a, double b, double c) {
String s = "One doubled root = " + (-b/(2*a));
JOptionPane.showMessageDialog(null, s);
}
public static double getTheDiscriminant(double a, double b, double c) {
return b*b - 4*a*c;
}
// New method
public static void displayComplexRoots(double a, double b, double c) {
double disc = 4 * a * c - b * b;
double dobleA = 2 * a;
String s = "two roots (" + (-b/dobleA) + "+" + (Math.sqrt(disc)/dobleA) + "i) and ("+ (-b/dobleA) + "" + (-Math.sqrt(disc)/dobleA) + "i)";
JOptionPane.showMessageDialog(null, s);
}
public static void getUserInput() {
JOptionPane.showMessageDialog(null, "Getting coeffecients for ax^2+bx+c=0");
a = getANumber("a");
b = getANumber("b");
c = getANumber("c");
}
public static double getANumber(String p) {
boolean iDontHaveANumberYet = true;
double r = 0;
do {
try {
String aStr = JOptionPane.showInputDialog("Enter \"" + p + "\"");
r = Double.parseDouble(aStr);
iDontHaveANumberYet = false;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Hey, I can't deal with that. Must enter legal number.");
}
} while (iDontHaveANumberYet);
return r;
}
}
General solution with complex numbers:
public class Complex {
double r;
double i = 0;
public Complex(double real, double imaginary) {
this.r = real;
this.i = imaginary;
}
public Complex(double real) {
this.r = real;
}
public Complex add(Complex c){
return new Complex(r+c.r, i+c.i);
}
public Complex cross(Complex c){
return new Complex(r*c.r - i*c.i, i*c.r + r*c.i);
}
public double getR() {
return r;
}
public double getI() {
return i;
}
#Override
public String toString() {
String result = Double.toString(r);
if (i < 0) {
result += " - " + ((i != -1)?Double.toString(-i):"") + "i";
} else if (i > 0) {
result += " + " + ((i != 1)?Double.toString(i):"") + "i";
}
return result;
}
public Complex[] squareRoot(){
double r2 = r * r;
double i2 = i * i;
double rR = Math.sqrt((r+Math.sqrt(r2+i2))/2);
double rI = Math.sqrt((-r+Math.sqrt(r2+i2))/2);
return new Complex[]{new Complex(rR, rI),new Complex(-rR, rI)};
}
public static Complex[] quadraticsRoot(double a, double b, double c) {
Complex[] result = new Complex(b*b - 4*a*c).squareRoot();
Complex bNegative = new Complex(-b);
Complex divisor = new Complex(1.0d / (2 * a));
for (int j = 0; j < result.length; j++) {
result[j] = bNegative.add(result[j]).cross(divisor);
}
return result;
}
public static void main(String[] args) {
Complex[] sol = quadraticsRoot(1,-10,34);
System.out.println(sol[0]);
System.out.println(sol[1]);
}
}
Here is my code:
package AbstractClassesTwo;
class X {
private int n;
public X(int n){
this.n = n;
}
public String toString(){
return "[" + n + " ]";
}
public boolean equals (Object obj){
boolean b = false;
if(obj instanceof X){
X x = (X)obj;
b = this.n == x.n;
}
return b;
}
public int hashCode(){
return n;
}
}
And the driver class:
package AbstractClassesTwo;
import java.util.HashMap;
public class UseX {
public static void main (String[] args){
X x1 = new X(1);
X x2 = new X(2);
String s1 = "1 ett one";
String s2 = "2 två two";
HashMap<X, String> t = new HashMap<X, String>();
t.put(x1, s1);
t.put(x1, s2);
int i = (int) (2 * Math.random() + 1);
X n = new X(i);
String s = (String)t.get(n);
System.out.println(n + ": " + s);
}
}
The value s returns both null values and the string values(" 2 två two") when executed several times?
t.put(x1, s1);
t.put(x1, s2);
^^
shouldn't that have been x2? Whenever you look for a new X(2), you get null.