Java Queries Here..

nbaztec

Master KOD3R
Guys having trouble providing keyboard input as arguments to a function especially when passing more than 1 argument. Written a java code i procedural style ( without any use of objects) to show if a triangle can be formed when we provide three integer inputs.

The code works flawlessly when manually providing arguments to the method isTriangle.

But when using providing inputs through keyboard , it throws error. Providing the code below:


Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class triangleFormation {
public static boolean isTriangle (int a, int b, int c){
	if (c>a+b || a>b+c || b>a+c ){
		return true;
	} else{
		return false;
	}
}

public static void main (String [] args)throws IOException {
	
   BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(System.in));
	String s = bufferedreader.readLine();
	String r = bufferedreader.readLine();
	String t = bufferedreader.readLine();
	
    int m = Integer.parseInt(s);
    int n = Integer.parseInt(r);
    int o = Integer.parseInt(t);
	
	
	
	System.out.println("the triangle is " + isTriangle (m,n,o));
}
}

I don't know if the process of providing keyboard input is correct or not. Only thing i found that its a hassle i java or i don't know some basic concepts. Providing inputs was so easy in c++.

Please throw some light into it guys. :)
The code is valid although logic is flawed. You should be returning `false` if `c>a+b || a>b+c || b>a+c`.

How exactly are you providing input? You should input on separate lines.
And catch the exception within main itself. Ignoring it and letting the runtime deal with it (or rather not) is a bad practice.
 

vickybat

I am the night...I am...
The code is valid although logic is flawed. You should be returning `false` if `c>a+b || a>b+c || b>a+c`.

How exactly are you providing input? You should input on separate lines.
And catch the exception within main itself. Ignoring it and letting the runtime deal with it (or rather not) is a bad practice.



If any of the above conditions are satisfied, true should be returned and if not, then false. Code is tested and is working correctly now. Just asking how to enter input values manually through console i.e keyboard input. :neutral:

I didn't get the bold part . Can you plz be a bit clear on that part mate? Besides i'm not much into handling exceptions yet in java. Just want to know how to successfully input through keyboard when passing more than one argument.
 
Last edited:

nbaztec

Master KOD3R
Nope mate the logic isn't flawed. See a,b and c are three sides of a triangle and atleast one side should be greater than the sum of the other two sides for a triangle to form.

If any of the above conditions are satisfied, true should be returned and if not, then false. Code is tested and is working correctly. Just asking how to enter input values manually through console i.e keyboard input. :neutral:

I didn't get the bold part . Can you plz be a bit clear on that part mate?

You got it wrong. For a Triangle, the sum of 2 sides is always greater or equal to the 3rd side,
A + B >= C
1,1,10 is not a triangle. Your code says it is.

You just have to input the value on 3 separate lines:
Code:
1 
1
10

and not:
Code:
1 1 10
 

vickybat

I am the night...I am...
^^ Oh got it and fixed the code. Ya i messed up the logic a bit.

But still how to provide the keyboard input. Actually i mean how to directly pass values through keyboard as arguments to the method isTriangle??

Lets say i want to pass 4,6 9. How do i pass that through keyboard to that method?

The above process works for a single argument but not more than that. Am i missing something here? Can you plz show it mate?
 

nbaztec

Master KOD3R
^^ Oh got it and fixed the code. Ya i messed up the logic a bit.

But still how to provide the keyboard input. Actually i mean how to directly pass values through keyboard as arguments to the method isTriangle??

Lets say i want to pass 4,6 9. How do i pass that through keyboard to that method?

The above process works for a single argument but not more than that. Am i missing something here? Can you plz show it mate?
Just a bit? Lol :p


As for the input, the code is fine. You just have to run the darn thing and:
input [Enter]
input [Enter]
input [Enter]
[Output]


P.S. On a side note it's a practice to name Classes as a capitalized string.
 

vickybat

I am the night...I am...
Just a bit? Lol :p

My head was screwed up a bit. :grin: Thanks for pointing that out man or i would have been a joke for all elementary school students. :p



As for the input, the code is fine. You just have to run the darn thing and:
input [Enter]
input [Enter]
input [Enter]
[Output]


P.S. On a side note it's a practice to name Classes as a capitalized string.

Buddy this is what i don't understand. In java i guess we can't input like that or atleast i think i don't know how to.

See when you input a single value , java takes only strings and invokes a readline method through a bufferreader object. Then that string has to be converted into an integer and those integers are passed as arguments for a respective method.

It works for a single argument but not for 3 in this case. I'm totally confused.
Can you please show me with proper java syntax?
 

nbaztec

Master KOD3R
My head was screwed up a bit. :grin: Thanks for pointing that out man or i would have been a joke for all elementary school students. :p





Buddy this is what i don't understand. In java i guess we can't input like that or atleast i think i don't know how to.

See when you input a single value , java takes only strings and invokes a readline method through a bufferreader object. Then that string has to be converted into an integer and those integers are passed as arguments for a respective method.

It works for a single argument but not for 3 in this case. I'm totally confused.
Can you please show me with proper java syntax?
How are you running the program?
 

vickybat

I am the night...I am...
^^ Hey got it man. I guess you meant to provide one input per line in the console of the ide. Yeah did that and its working. I misunderstood your post a bit.

Thanks a lot mate. I'm using eclipse.

*i.imgur.com/mpZeA.png

I will rename the classes with capitalized strings in my codes.

Following thinkingapjava by Allen B. downy and finding his approach amazing in terms of building codes. Its a free ebook. Heard of him?
 
Last edited:

nbaztec

Master KOD3R
^^ Hey got it man. I guess you meant to provide one input per line in the console of the ide. Yeah did that and its working. I misunderstood your post a bit.

Thanks a lot mate. I'm using eclipse.

*i.imgur.com/mpZeA.png

I will rename the classes with capitalized strings in my codes.

Following thinkinginjava by Allen B. downy and finding his approach amazing in terms of building codes. Its a free ebook. Heard of him?

I've never followed any book on anything. So nope.
 

vickybat

I am the night...I am...
Is this method efficient??

Question-Write a recursive method called power that takes a double x
and an integer n and that returns x^n.
Hint: a recursive denition of this operation is x^n = x*x^n-1. Also, remember
that anything raised to the zeroeth power is 1.

Optional challenge: you can make this method more efficient, when n is even,
using x^n = (x^n/2)^2.

My code:

Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Power {
public static double power(double x ,int n){
	if (n==0){
		return 1;
	} if (n%2==0){
		double b =Math.pow(n, x);
		return b;
	}else{
		
	 double recurse = power(x,n-1);
	
	return x*recurse;
	}
	}


public static void main (String [] args) throws IOException{
	BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(System.in));
	String s = bufferedreader.readLine();
	String r = bufferedreader.readLine();
	
	double m = Double.parseDouble(s);
	int p = Integer.parseInt(r);
	
	System.out.println (power (m,p));
}
}

Writing recursive code to compute x^n is easy. But the optional challenge is confusing. Is it okay to provide math methods in the conditional statement or it can be done recursively?

In the above code, if n is even, it invokes the Math.pow method and if odd, invokes power method recursively to get the result. Code is working but is it efficient.

Please provide some comments guys.
 
Last edited:

nbaztec

Master KOD3R
Code:
public double power(double x, int n)
{
  if(n == 0)
     return 1;
  else if(n%2 == 0)
    return power(x, n/2)*power(x, n/2);
  else
    return x*power(x,n-1);
}

System.out.println(power(5,6));
 

vickybat

I am the night...I am...
Code:
public double power(double x, int n)
{
  if(n == 0)
     return 1;
  else if(n%2 == 0)
    [B][SIZE="4"]return power(x, n/2)*power(x, n/2);[/SIZE][/B]
  else
    return x*power(x,n-1);
}

System.out.println(power(5,6));

^^ Thanks a lot for your help mate. Yeah that's the recursive logic that i missed out.
Its working now without using any library methods. :)

Analyzed it with stack diagrams. Your input will invoke the first else i.e the power*power method and it will be like power (5,3)*power( 5,3).

Now since n is 3, it skips to the last conditional and recursively computes x*power(x,n-1) and returns 625 for each power (5,3) and finally gives the result. Again thanks a lot mate.



Solved another recursive algorithm and this time its Euclid's recursive algorithm.

Question: The process is based on the observation that, if r is the remainder when a
is divided by b, then the common divisors of a and b are the same as the
common divisors of b and r. Thus we can use the equation
gcd(a, b) = gcd(b, r)
to successively reduce the problem of computing a GCD to the problem of
computing the GCD of smaller and smaller pairs of integers. For example,
gcd(36,20) = gcd(20, 16) = gcd(16, 4) = gcd(4, 0) = 4
implies that the GCD of 36 and 20 is 4. It can be shown that for any two
starting numbers, this repeated reduction eventually produces a pair where the
second number is 0. Then the GCD is the other number in the pair.
Write a method called gcd that takes two integer parameters and that uses
Euclid's algorithm to compute and return the greatest common divisor of the
two numbers.

Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Euclid {
public static int gcd (int a, int b){
	
	
			
				int r = a % b;
				if (r == 0){
					
					return b;
				} else {
			      
				int recurse = gcd (b,r);
				
				return recurse;
                  }
			
			
		}


	public static void main (String [] args) throws IOException{
	BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(System.in));
	String s = bufferedreader.readLine();
	String r = bufferedreader.readLine();
	
	int p = Integer.parseInt(s);
	int q = Integer.parseInt(r);
	System.out.println (gcd(p,q));
	
}
}

Guys is the code efficient or there are better ways?

@nbaztec - Waiting for your reply buddy.:)
 
Last edited:

nbaztec

Master KOD3R
Divide and conquer is already pretty optimal (at least in this regard). One thing though, you don't need the value of `recurse` anywhere except returning it, so why not simply return the value from function.

One a side note, If you are trying to learn Java there are better things to do than to solve Euclidean problems. I usually prefer optimized recursions in C/C++ where one can have pointer control to mess around.
 

vickybat

I am the night...I am...
Divide and conquer is already pretty optimal (at least in this regard). One thing though, you don't need the value of `recurse` anywhere except returning it, so why not simply return the value from function.

One a side note, If you are trying to learn Java there are better things to do than to solve Euclidean problems. I usually prefer optimized recursions in C/C++ where one can have pointer control to mess around.

True, but the material i'm following suggests to practice returning variables to better assist in debugging complex codes. So keeping the practice. The above one is a simple one and recurse variable can be omitted
and function returned directly.

Besides i was going through the recursion chapter and thus solved this. Will be moving on to newer problems. :)
 

nbaztec

Master KOD3R
True, but the material i'm following suggests to practice returning variables to better assist in debugging complex codes.
You interpreted it wrongly mate.

What the author meant was to `return` values from functions as a means of determining whether the function failed or executed successfully. Take the following pseudo functions:
Code:
void foo(a,b){
    file.open(a);
    file.write(b);
}

int bar(a,b){
    if(file.open(a)){
        if(file.write(b))
             return 0;
        else
             return 1;
    }    
    return 2;
}

You see the difference between the 2 functions? While `foo` has effectively the same function calls within to perform the same task, `bar` makes use of a paradigm called error codes (albeit in a simpler form). So using `bar` you can better debug complex tasks by noting the return value of the it and take suitable action if it's other than a 0 (or any other success value).

While using a modular approach it is best suited to always return status codes from functions, unless it's trivial.

What I meant was to use:
Code:
    /* int recurse = gcd(a,b);
     * return recurse;
     */
    return gcd(a,b);
 

Piyush

Lanaya
first time using Scanner class
getting error
need help
...

Code:
mport java.util.Scanner.*;

public class Calc
{	
	public static void main (String args[]) 
	{	int result,a,b,c;
		Scanner scan=new Scanner(System.in);
		System.out.println("Enter the operation to perform: 1-->+ 2-->- 3-->/ 4-->* ");
		c=scan.nextInt();
		System.out.println("Enter the two numbers: a and b");
		a=scan.nextInt();
		b=scan.nextInt();
		switch(c)
		{	case '1':
			{	result=a+b;
				System.out.println("Result is "+result);
				break;
			}
		
			case '2':
			{	result=a-b;
				System.out.println("Result is "+result);
				break;
			}
			
			case '3':
			{	result=a*b;
				System.out.println("Result is "+result);
				break;
			}
			
			case '4':
			{	result=a/b;
				System.out.println("Result is "+result);
				break;
			}
			
			default:
			{	System.out.println("Wrong operator choice!!!");
				break;
			}
		}
		
	}
}

error
Code:
Calc.java:29: error: cannot find symbol
		Scanner scan=new Scanner(System.in);
		^
  symbol:   class Scanner
  location: class Calc
Calc.java:29: error: cannot find symbol
		Scanner scan=new Scanner(System.in);
		                 ^
  symbol:   class Scanner
  location: class Calc
2 errors
 
Top Bottom