|
@ -21,6 +21,72 @@ public class FunktionenAusgelagert { |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public static void Binaerrechner() { |
|
|
|
|
|
|
|
|
|
|
|
try (Scanner scannerBR = new Scanner(System.in)) { |
|
|
|
|
|
System.out.print("Gebe den ersten Binärcode ein: "); |
|
|
|
|
|
String binaerCode1 = scannerBR.nextLine(); |
|
|
|
|
|
System.out.print("Gebe den zweiten Binärcode ein: "); |
|
|
|
|
|
String binaerCode2 = scannerBR.nextLine(); |
|
|
|
|
|
System.out.print("Gebe die gewünschte Operation ein (+, -, *, /): "); |
|
|
|
|
|
char operation = scannerBR.next().charAt(0); |
|
|
|
|
|
|
|
|
|
|
|
int ergebnisBR = calculate(binaerCode1, binaerCode2, operation); |
|
|
|
|
|
System.out.println("Das Ergebnis ist: " + ergebnisBR); |
|
|
|
|
|
} |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
public static int calculate(String binaryCode1, String binaryCode2, char operation) { |
|
|
|
|
|
|
|
|
|
|
|
int decimal1 = binaryToDecimal(binaryCode1); |
|
|
|
|
|
int decimal2 = binaryToDecimal(binaryCode2); |
|
|
|
|
|
|
|
|
|
|
|
int result = 0; |
|
|
|
|
|
switch (operation) { |
|
|
|
|
|
case '+': |
|
|
|
|
|
result = decimal1 + decimal2; |
|
|
|
|
|
break; |
|
|
|
|
|
case '-': |
|
|
|
|
|
result = decimal1 - decimal2; |
|
|
|
|
|
break; |
|
|
|
|
|
case '*': |
|
|
|
|
|
result = decimal1 * decimal2; |
|
|
|
|
|
break; |
|
|
|
|
|
case '/': |
|
|
|
|
|
result = decimal1 / decimal2; |
|
|
|
|
|
break; |
|
|
|
|
|
default: |
|
|
|
|
|
System.out.println("Ungültige Operation! Bitte wähle +, -, * oder /."); |
|
|
|
|
|
return 0; |
|
|
|
|
|
} |
|
|
|
|
|
return decimalToBinary(result); |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
public static int binaryToDecimal(String binaryCode) { |
|
|
|
|
|
|
|
|
|
|
|
int decimal = 0; |
|
|
|
|
|
for (int i = binaryCode.length() - 1; i >= 0; i--) { |
|
|
|
|
|
char currentChar = binaryCode.charAt(i); |
|
|
|
|
|
if (currentChar == '1') { |
|
|
|
|
|
decimal += Math.pow(2, binaryCode.length() - i - 1); |
|
|
|
|
|
} else if (currentChar != '0') { |
|
|
|
|
|
System.out.println("Ungültiger Binärcode! Bitte gebe nur Nullen und Einsen ein."); |
|
|
|
|
|
return 0; |
|
|
|
|
|
} |
|
|
|
|
|
} |
|
|
|
|
|
return decimal; |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
public static int decimalToBinary(int decimal) { |
|
|
|
|
|
int binary = 0; |
|
|
|
|
|
int power = 0; |
|
|
|
|
|
while (decimal > 0) { |
|
|
|
|
|
binary += (decimal % 2) * (int) Math.pow(10, power); |
|
|
|
|
|
decimal /= 2; |
|
|
|
|
|
power++; |
|
|
|
|
|
} |
|
|
|
|
|
return binary; |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
} |
|
|
} |