Rechner

Demenkay

Mitglied
Ich soll ein Programm schreiben, beidem jede Rechenart in einer eigenen Funktion steht! Ich hab es soweit fertig wie ich denke, allerdings hab ich nen Fehler drin, weiß aber nicht woran es liegt, oder ob ich es soweit schreiben kann??

Java:
import java.util.Scanner;

public class Funktionen2 {
	public static void main(String[] args) {
		int a = 0;
		int b = 0;
		int x;

		Scanner Eingabe = new Scanner(System.in);

		// Wert der Variablen über Tastatur eingeben
		System.out.println("Folgende Rechenarten sind möglich:");
		System.out.println("(1) Addition");
		System.out.println("(2) Subtraktion");
		System.out.println("(3) Multiplikation");
		System.out.println("(4) Division");
		System.out.println("(5) Modulo");
		System.out.println("Geben Sie die gewünschte Rechenart ein:");
		x = Eingabe.nextInt();
		System.out.println("1.Zahl: ");
		a = Eingabe.nextInt();
		System.out.println("2.Zahl: ");
		b = Eingabe.nextInt();

		if (x == 1) {
			int result = add(a, b);
		} else if (x == 2) {
			int result = sub(a, b);
		} else if (x == 3) {
			int result = mult(a, b);
		} else if (x == 4) {
			int result = div(a, b);
		} else if (x == 5) {
			int result = modulo(a, b);
		}

		System.out.println("Ergebnis von " + a + " und " + b + " ergibt: "+ result);
	}

	public static int add(int a, int b) {
		int result = a + b;
		return result;
	}

	public static int sub(int a, int b) {
		int r = a - b;
		return r;
	}

	public static int mult(int a, int b) {
		int r = a * b;
		return r;
	}

	public static int div(int a, int b) {
		int r = a / b;
		return r;
	}

	public static int modulo(int a, int b) {
		int r = a % b;
		return r;
	}
}

Der Fehler liegt bei der Ausgabe im Result (result cannot be resolved to a variable)
 

L-ectron-X

Gesperrter Benutzer
Mach das mal so:
[JAVA=25] int result = 0;

if (x == 1) {
result = add(a, b);
} else if (x == 2) {
result = sub(a, b);
} else if (x == 3) {
result = mult(a, b);
} else if (x == 4) {
result = div(a, b);
} else if (x == 5) {
result = modulo(a, b);
}[/code]
 

XHelp

Top Contributor
dein
Code:
result
exisiert ja auch nur in dem jeweiligem if-Zweig. Es sollte eher so aussehen:
Java:
int result;
if (x==1) {
  result = ...
} else if (...
Du kannst dir auch den
Code:
switch
-Operator mal anschauen.
 

Neue Themen


Oben