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.

105 lines
2.4 KiB

2 years ago
2 years ago
  1. package LernProgramm;
  2. import java.util.Random;
  3. import java.util.Scanner;
  4. public class FunktionenAusgelagert {
  5. public static void PrimBis100() {
  6. for (int i = 2; i <= 100; i++) {
  7. boolean istPrimZahl = true;
  8. for (int j = 2; j < i; j++) {
  9. if (i % j == 0) {
  10. istPrimZahl = false;
  11. break;
  12. }
  13. }
  14. if (istPrimZahl) {
  15. System.out.print(i + " ");
  16. }
  17. }
  18. }
  19. public static void Binaerrechner() {
  20. try (Scanner scannerBR = new Scanner(System.in)) {
  21. System.out.print("Gebe den ersten Binärcode ein: ");
  22. String binaerCode1 = scannerBR.nextLine();
  23. System.out.print("Gebe den zweiten Binärcode ein: ");
  24. String binaerCode2 = scannerBR.nextLine();
  25. System.out.print("Gebe die gewünschte Operation ein (+, -, *, /): ");
  26. char operation = scannerBR.next().charAt(0);
  27. int ergebnisBR = calculate(binaerCode1, binaerCode2, operation);
  28. System.out.println("Das Ergebnis ist: " + ergebnisBR);
  29. }
  30. }
  31. public static int calculate(String binaryCode1, String binaryCode2, char operation) {
  32. int decimal1 = binaryToDecimal(binaryCode1);
  33. int decimal2 = binaryToDecimal(binaryCode2);
  34. int result = 0;
  35. switch (operation) {
  36. case '+':
  37. result = decimal1 + decimal2;
  38. break;
  39. case '-':
  40. result = decimal1 - decimal2;
  41. break;
  42. case '*':
  43. result = decimal1 * decimal2;
  44. break;
  45. case '/':
  46. result = decimal1 / decimal2;
  47. break;
  48. default:
  49. System.out.println("Ungültige Operation! Bitte wähle +, -, * oder /.");
  50. return 0;
  51. }
  52. return decimalToBinary(result);
  53. }
  54. public static int binaryToDecimal(String binaryCode) {
  55. int decimal = 0;
  56. for (int i = binaryCode.length() - 1; i >= 0; i--) {
  57. char currentChar = binaryCode.charAt(i);
  58. if (currentChar == '1') {
  59. decimal += Math.pow(2, binaryCode.length() - i - 1);
  60. } else if (currentChar != '0') {
  61. System.out.println("Ungültiger Binärcode! Bitte gebe nur Nullen und Einsen ein.");
  62. return 0;
  63. }
  64. }
  65. return decimal;
  66. }
  67. public static int decimalToBinary(int decimal) {
  68. int binary = 0;
  69. int power = 0;
  70. while (decimal > 0) {
  71. binary += (decimal % 2) * (int) Math.pow(10, power);
  72. decimal /= 2;
  73. power++;
  74. }
  75. return binary;
  76. }
  77. public static void EasterEgg() {
  78. System.out.println(" _______");
  79. System.out.println(" / \\");
  80. System.out.println(" ( 0 0 )");
  81. System.out.println(" \\ --- /");
  82. System.out.println(" ------");
  83. }
  84. }