You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
92 lines
2.2 KiB
92 lines
2.2 KiB
package LernProgramm;
|
|
|
|
import java.util.Random;
|
|
import java.util.Scanner;
|
|
|
|
public class FunktionenAusgelagert {
|
|
|
|
public static void PrimBis100() {
|
|
for (int i = 2; i <= 100; i++) {
|
|
boolean istPrimZahl = true;
|
|
for (int j = 2; j < i; j++) {
|
|
if (i % j == 0) {
|
|
istPrimZahl = false;
|
|
break;
|
|
}
|
|
}
|
|
if (istPrimZahl) {
|
|
System.out.print(i + " ");
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
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;
|
|
}
|
|
|
|
|
|
}
|