I am writing a function and I want it two return two integers as results. However, I cannot get it to do this. Could someone help me? Here is my best shot
public static int calc (int s, int b, int c, int d, int g)
{
if (s==g)
return s;
else if (s+b==g)
return s && b;
else if (s + c==g)
return s && c;
else if (s+d==g)
return s && d;
else
System.out.println("No Answer");
}
You could have the method return an array of int:
public static int[] calc (int s, int b, int c, int d, int g)
Make a "pair" class and return it.
public class Pair<T,Y>
{
public T first;
public Y second;
public Pair(T f, Y s)
{
first = f;
second = s;
}
}
Make a small inner class that has two integers.
private static class TwoNumbers {
private Integer a;
private Integer b;
private TwoNumbers(Integer a, Integer b) {
this.a = a;
this.b = b;
}
}
You create a instance of the class and return that instead.
For this specific problem, since the answer always returns s:
....
return s;
....
return s && b;
....
return s && c;
....
return s && d;
....
you could just return the 2nd value. I use 0 to indicate "just s" since the first case (if (s==g)) could be thought of as if (s+0==g). Use a different sentinel value than 0 for this, if necessary.
public static int calc (int s, int b, int c, int d, int g)
{
if (s==g)
return 0;
else if (s+b==g)
return b;
else if (s+c==g)
return c;
else if (s+d==g)
return d;
else {
// System.out.println("No Answer");
// Probably better to throw or return a sentinel value of
// some type rather than print to screen. Which way
// probably depends on whether "no answer" is a normal
// possible condition.
throw new IndexOutOfBoundsException("No Answer");
}
}
If no exception is thrown, then s is always the first result:
try {
int result1 = s;
int result2 = calc(s, b, c, d, g);
} catch (IndexOutOfBoundsException ex) {
System.out.println("No Answer");
}
package calcultor;
import java.util.*;
import java.util.Scanner;
public class Calcultor{
public static void main(String args[]){
input();
}
public static void input(){
Scanner FirstNum = new Scanner(System.in);
System.out.print("Enter the First number: ");
int num01 = FirstNum.nextInt();
Scanner secondNum = new Scanner(System.in);
System.out.print("Enter the second number: ");
int num02 = secondNum.nextInt();
output(num01, num02);
}
public static void output(int x ,int y){
int sum = x + y;
System.out.println("Sum of Two Number: "+sum);
//return sum;
}
}
why do you want to do this? and if you have some need like this can't you change your return type to string, because in case of string you can have separator between two values which will help you in extracting values.... say 10&30 ,
I agree this is a wrong way of solving...i assumed that there is limitation of sticking to primitive datatype
Related
i have one class which have 4 int fields . i want to sort objects array by some mathematical operation on fields .I tried below code but sorting is not happening.
class Cust1 implements Comparable<Cust1>{
int a;
int o;
int s;
int p;
#Override
public int compareTo(Cust1 b) {
if(this.a + this.s <= b.a + b.s)
{
return 1;
}
else {
return 0;
}
}
}
public class Test5 {
public static void main (String args[]) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
Cust1[] cust = new Cust1[n];
for(int i=0;i<n ;i++)
{
Cust1 a = new Cust1();
String[] str = br.readLine().split(" ");
a.a = Integer.parseInt(str[0]);
a.o = Integer.parseInt(str[1]);
a.s = Integer.parseInt(str[2]);
a.p = Integer.parseInt(str[3]);
cust[i] =a;
}
Arrays.sort(cust, new Comparator<Cust1>() {
#Override
public int compare(Cust1 o1, Cust1 o2) {
return o1.compareTo(o2);
}
});
}
}
Based on your code snippet: you don't need to provide Comparator, since Cust1 already implements Comparable. So, this should be enough:
Arrays.sort(cust);
Also, Cust1 implementation of Comparable doesn't really tell, when one object is less then other. Probably, you meant something like this:
#Override
public int compareTo(Cust1 b) {
if(this.a + this.s < b.a + b.s) {
return 1;
} else if (this.a + this.s > b.a + b.s) {
return -1;
} else {
return 0;
}
}
But it's hard to tell, what exact implementation of Comparable should be without more details (for instance, for some reason fields o and p are not involved in comparison at all).
You comparator work wrong. It should return:
>0 - current object is greater than another one
0 - current object is equal to another one
<0 - current object is less than another one
class Cust1 implements Comparable {
int a;
int o;
int s;
int p;
#Override
public int compareTo(Cust1 b) {
return Integer.compare(a + s, b.a + b.s);
}
}
And you do not have to provide additional comparator to Arrays.sort() since Cust1 already implements Comparable.
I am making a calculator to test what I can do and I have a small problem. I am trying to take an input parameter on my "input" method and just have them enter their numbers as a string and parse for the doubles on either side of the symbol. However, I am not sure how to do this. I was thinking of using an if statement, something like if (symbol) run method. The code is as follows:
public class Calculation_Controls extends JPanel implements ActionListener, KeyListener{
public double A, B;
public String input(String nums){
String[] split = nums.split("[-.+,/,*,^]");
int left = Integer.parseInt(split[0]);
int right = Integer.parseInt(split[1]);
}
//What I am trying to invoke for the "if (symbol)"
public double add(double a, double b){
this.a = A;
this.b = B;
return (a + b);
}
public double subtract(double a, double b){
this.a = A;
this.b = B;
return a - b;
}
public double multiply(double a, double b){
this.a = A;
this.b = B;
return a * b;
}
public double divide(double a, double b){
this.a = A;
this.b = B;
return a / b;
}
public double pwr(double a, double b){
this.A = a;
this.B = b;
return (Math.pow(a, b));
}
Assuming the input format you expect is a string of the general for of "5*6" :
public class Calculation_Controls {
private String[] operators = new String[] {"-","+","/","*","^"};
public void input(String nums){
//add: check input is valid
String operator = findSymbol(nums);
if(operator == null ) {
System.out.println("Invalid input");
return;
}
String[] split = nums.split(operator);
int left = Integer.parseInt(split[0]);
int right = Integer.parseInt(split[1]);
double result = 0;
switch (operator) {
case "-":
result = subtract(left, right);
break;
case "+":
result = add(left, right);
break;
case "/":
result = divide(left, right);
case "*":
result = multiply(left, right);
break;
case "^":
result = pwr(left, right);
break;
default: System.out.println("Invalid operator");
}
}
private String findSymbol(String nums) {
for( String operator : operators) {
if(nums.contains(operator))
return operator;
}
return null;
}
public double add(double a, double b){
return (a + b);
}
public double subtract(double a, double b){
return a - b;
}
public double multiply(double a, double b){
return a * b;
}
public double divide(double a, double b){
return a / b;
}
public double pwr(double a, double b){
return (Math.pow(a, b));
}
}
Note: I did not test it.
You can use switch case OR if ,
OR by using the interfaces like below .
interface Operation {
public double resultFor(double left, double right);
}
class Calculation_Controls extends JPanel implements ActionListener, KeyListener{
public double a, b;
Map<Character, Operation> operations = new HashMap<Character, Operation>();
public Calculation_Controls() {
operations.put('*', new multiply());
operations.put('-', new subtract());
operations.put('+', new Add());
operations.put('/', new divide());
operations.put('^', new pwr());
}
public String input(String nums) {
String[] split = nums.split("[-.+,/,*,^]");
for (int i = 0; i < split.length; i++) {
System.out.println("" + split[i].length());
}
char operation = nums.charAt(split[0].length());
int left = Integer.parseInt(split[0]);
int right = Integer.parseInt(split[1]);
double result = 0;
Operation op = operations.get(Character.valueOf(operation));
if (op != null) {
result = op.resultFor(left, right);
System.out.println("Result :" + result);
} else {
System.out.println("Error: Unknown operator");
}
return String.valueOf(result);
}
class Add implements Operation {
#Override
public double resultFor(double left, double right) {
return (left + right);
}
}
class subtract implements Operation {
#Override
public double resultFor(double left, double right) {
return left - right;
}
}
class divide implements Operation {
#Override
public double resultFor(double left, double right) {
return left / right;
}
}
class multiply implements Operation {
#Override
public double resultFor(double left, double right) {
return left * right;
}
}
class pwr implements Operation {
#Override
public double resultFor(double left, double right) {
return (Math.pow(left, right));
}
}
}
To use it :
Calculation_Controls inst = new Calculation_Controls();
inst.input("2^4");
I've made a main method in one class and a lot of other small methods in another class. When I call on them in my main method using their location and making sure that they would outprint if I called on them, they still don't outprint. Only the print two methods show any output. I'm not sure how to go about fixing it so I haven't tried many things yet. Could you look at my code and check why they aren't working?
Update: I've managed to get all the line in the main method except for 28 working with the help I received. Now all that's left is that one output. I've changed the code so it works a bit better and will shut down if it doesn't output, but the output is still missing.package rational;
My Main Method
package rational;
/**
*
* #author Dominique
*/
public class Rational {
public static String number() {
rational1 number= new rational1(27, 3);
String r3= number.printRational(number);
return r3;
}
public static void main(String[] args) {
rational1 number= new rational1(27,3);
System.out.println(number());
String r3=number();
System.out.println(rational1.toDouble(27,3 ));
rational1.add(number);
rational1.invert(r3, number);
rational1.negate(r3, number);
rational1.toDouble(27, 3);
}
}
My Other Method Class
package rational;
/**
*
* #author Dominique
*/
public class rational1 {
public int top;
public int bottom;
public rational1 () {
this.top = 0;
this.bottom = 0;
}
public rational1(int top, int bottom){
this.top=top;
this.bottom=bottom;
}
public String printRational(rational1 r1){
String r3=("Your fraction is "+String.format(r1.top+" / "+r1.bottom));
return r3;
}
public static void invert(String r2, rational1 r1) {
int index = r2.indexOf('s');
if (index != -1) {
System.out.print(r2.substring(0, index+1));//works
System.out.println(" "+r1.bottom + "/" + r1.top);
index++;
}
else {
System.exit(0);
}
}
public static void negate(String r2, rational1 r1){
int index = r2.indexOf('-');
if (index != -1) {
String stringValueOf = String.valueOf(r1.top);
System.out.println(r2.substring(0, 17));//works
System.out.println(r1.bottom+"/"+stringValueOf.substring(1));
index++;
}
}
public static double toDouble(int one, int two){
int three= one/two;
return three;
}
public static double gcd( double a, double b)
{
double r = a % b;
if (r != 0)
{
return gcd(b, r );
}
else
{
return b;
}
}
public static double reduce(double t, double b){
double numberone=gcd(t, b);
double pick=numberone*(b/t);
return pick;
}
public static double add(rational1 r1){
double pickone=(r1.top);
double choice= pickone+pickone;
double choice2=reduce(choice, r1.bottom);
return choice2;
}
}
So the problem is in invert method:
public static void invert(String r2, rational1 r1){
int index = 0;
while (index < 1) {
if (r2.charAt(index) == '/') {
System.out.print(r2.substring(0, 17));
System.out.print(r1.bottom+"/"+r1.top);
index++;
}else{
System.exit(0);
}
`}
}
This method immediate checks the character at r2.charAt(index) == '/'), but this is never the case. Because the character at index = 0 is 'Y' from the printRational method. Because that's not the case then System.exit(0) gets called which immediately ends the program without running the rest of the program.
I believe that this code will work.
public static void invert(String r2, rational1 r1) {
int index = r2.indexOf('/');
if (index != -1) {
index++;
}
else {
System.out.print(r2.substring(0, index));//works
System.out.print(r1.bottom + "/" + r1.top);
}
}
The print method does not necessarily flush the buffer to the screen. Try replacing the print method with the println method.
Once this is in rational package., try to change the system.out.print to system.out.println .Basically all your codes are okay. Try look at this link.
Click [here] (http://introcs.cs.princeton.edu/java/92symbolic/Rational.java.html)!
I'm trying to write a program that takes three sides of a triangle in any order, re arranges them in ascending order (a,b,c) and then tells the user what type of triangle it is and the area. However I can't figure out what is wrong with my code that it keeps getting the wrong true/false value for my isValid method. Even if the sides don't make up a triangle it still proceeds as if the isValid method had returned true. Any suggestions? Thanks.
package javaapplication1;
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter three numbers:");
double a = input.nextDouble();
double b = input.nextDouble();
double c = input.nextDouble();
if (a > b)
{
double temp = a;
a = b;
b = temp;
}
if (b > c)
{
double temp = b;
b = c;
c = temp;
}
if (a > b)
{
double temp = a;
a = b;
b = temp;
}
double area = area(a, b, c);
boolean isValid = isValid(a, b, c);
String type = type(a, b, c);
if (isValid = true)
{
System.out.println("This triangle is " + type);
System.out.printf("The area is %.2f", area, "\n\n");
}
else
{
System.out.print("Invalid triangle");
}
}
public static boolean isValid(double a, double b, double c)
{
if (a + b > c)
{
return true;
}
else
{
return false;
}
}
public static double area(double a, double b, double c)
{
double s = (a + b + c)/2.0;
double area = Math.sqrt(s * (s - a) * (s - b) * (s - c));
return area;
}
public static String type(double a, double b, double c)
{
String type;
if (a == c)
{
type = "equilateral";
} else if (a == b || b == c)
{
type = "isosceles";
} else
{
type = "scalene";
}
return type;
}
}
The issue appears to be here (unless it was a typo):
if (isValid = true)
You're assigning true to isValid, so the condition in the if statement is always true.
The proper way to do comparison of primitive values is by using two equals signs:
if (isValid == true)
However, for booleans, this is redundant. The best way to test if a boolean value is true/false is simply to use the boolean variable itself:
if (isValid)
I am trying to learn programming and I am on the phase of learning recursion. Before this, I have successfully solve the problem but using loops. Right now, since recursion is quite interesting to me, I was wondering if I could convert the loop into a recursive method. I have done my attempts but I've been getting a sort of infinite computation whatsoever.
Can somebody give me a hand with this? Thanks.
This is my code.
public class RecursiveProduct {
public static void main (String[] args) {
Scanner myInput = new Scanner(System.in);
System.out.print("Enter num1: ");
int num1 = myInput.nextInt();
System.out.print("Enter num2: ");
int num2 = myInput.nextInt();
int product = recursiveProduct(num1, num2);
System.out.print(num1 +" * " +num2 +" = " +product);
}
public static int recursiveProduct(int a, int b)
{
int result = 0;
if(b == 0)
return result;
else
{
result += a;
return result += recursiveProduct(a, b--);
}
}
}
First, this is C++ code, but I will explain Java code later:
int function(int a, int b, int &counter,int &result){
if(b==0 || a==0)
return 0;
if(counter==b)
return 1;
else{
result+=a;
counter++;
function(a,b,counter,result);
}
}
Function takes two references int &counter and int result. Unfortunately, you can't pass primitive types by reference in Java, so you should declare Wrapper class, and then call your method, something like this:
class MyInt{
public int value=0;
}
Here you will bi 100% sure that object of MyInt will be passed by value, but itself is reference so you get what you want. Reimplement our function:
void function(int a, int b, MyInt counter,MyInt result){
if(b==0 || a==0)
return 0;
if(counter==b)
return 1;
else{
result.value+=a;
counter.value++;
function(a,b,counter,result);
}
}
Call your method like this bellow, and everything should work:
int a=2,b=5;
MyInt counter=new MyInt();
MyInt result=new MyInt();
function(a,b,counter,result);
Try this:
public static int recursiveProduct(int a, int b) {
if (b == 0) {
return 0;
} else {
return a + recursiveProduct(a,--b);
}
}
You are almost there: just add result += recursiveProduct(a, b--); instead of just calling the function.
EDIT: call it with b- 1 not with b--
I suggest you simplify your code.
Something like
return b == 0 ? 0 : a + fn(a, b-1);