Question

could anyone help me with the following code :

import java.math.*;
import java.util.Scanner;

public class Pitagor {
public static void main (String[] args){
    System.out.println(pitagor(in1(),in2()));

}
public static int in1 (){
    Scanner input = new Scanner(System.in);
    System.out.println("Eingabe von a  ");
    int a = input.nextInt();

    return a;
}
public static int in2 (){
    Scanner input = new Scanner(System.in);
    System.out.println("Eingabe von b");
    int b = input.nextInt();

    return b;
}
public static double pitagor (int x , int y){
    double c = Math.sqrt((x*x)+(y*y));
    return c;
}
}

My goal here is to make the code simpler by using separate methods for input and calculation, but i can't seem to understand how to make only one input method instead of in1() and in2().

What i tried was :

public static void in (){
Scanner input = new Scanner(System.in);
System.out.println("Eingabe von a  ");
int a = input.nextInt();
Scanner input = new Scanner(System.in);
System.out.println("Eingabe von b");
int b = input.nextInt(); }

but i don't know how to get a and b from this method, so i can use them in

pitagor (int x , int y)

Thanks in advance.

Was it helpful?

Solution

One way to do it:

import java.math.*;
import java.util.Scanner;

public class Pitagor {
    public static void main (String[] args){
        System.out.println(pitagor(getIntInput("Eingabe von a  "),getIntInput("Eingabe von b")));

    }
    public static int getIntInput(String prompt){
        Scanner input = new Scanner(System.in);
        System.out.println(prompt);
        return input.nextInt();
    }
    public static double pitagor (int x , int y){
        double c = Math.sqrt((x*x)+(y*y));
        return c;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top