Input/Output Mehrere Befehle nacheinander ausführen

DanSc94

Mitglied
Hey,

ich sitze gerade an einer Übungsaufgabe für die Uni und habe folgendes Problem:
Ich soll 4 Gewinnt programmieren mit 3 Befehlen die man durch Input ausführen kann.
Die Methoden dazu habe ich schon geschrieben, nur weiß ich nicht wie ich durch das Auslesen von System.in eine Methode aufrufen kann. Zudem soll man danach wieder einen Befehl eingeben können, bis das Spiel zu Ende ist.
Folgende Befehle gibt es:
throwin value mit value = {0, 1, 2, 3, 4, 5, 6}.
print dadurch wird das aktuelle Spielfeld mit Terminal.printLine() ausgegeben.
field x,y dadurch wird der Zustand eines bestimmten Felds ausgegeben.
quit ist ja selbsterklärend.

Als Main Class habe ich folgendes:
Java:
public class Main {
    public static void main(String args[]) {
        while (Terminal.readLine() != "quit") {
            try {
                Terminal.readLine();
              
            } catch (ArrayIndexOutOfBoundsException e) {
                Terminal.printLine("Error index out of array range");
            }
        }
    }
}
Terminal.readLine() ersetzt System.in und Terminal.printLine() System.out.

Wie kann ich jetzt mit der Eingabe throwin 3 die Methode throwin(3) aufrufen?
 
Zuletzt bearbeitet:
Java:
if(Terminal.readLine().equals("throwin 3"))
    throwin(3);

Wenn ich dich richtig verstanden habe.

Man soll aber nicht nur 3 als value benutzen können, sondern von 0 - 6, ab 7 soll man nen Error ausgeben.
Die Frage war allgemein gestellt ^^
Edit: oder soll ich etwa eine switch case für jede mögliche Eingabe machen?
 
Dann wäre switch und case wahrscheinlich die einfachste Lösung.
Du könntest auch den ersten Teil des eingegeben String auf "throwin" prüfen und dann throwin(x) mit x als letzten char des Strings aufrufen. Würde zwar ein paar abfragen sparen ist aber bei so einer kleinen Aufgabe eher nicht nötig, denke ich. Außerdem wäre dann eine Exception möglich.
 
Dann wäre switch und case wahrscheinlich die einfachste Lösung.
Du könntest auch den ersten Teil des eingegeben String auf "throwin" prüfen und dann throwin(x) mit x als letzten char des Strings aufrufen. Würde zwar ein paar abfragen sparen ist aber bei so einer kleinen Aufgabe eher nicht nötig, denke ich. Außerdem wäre dann eine Exception möglich.

Es gibt ja nicht nur throwin X als verfügbaren Befehl, sondern noch print und field X,Y (wird genau so eingegeben, z.b. field 3,4 und es soll dann field(3,4) ausgeführt werden) und da kommen halt schon ne Menge cases zusammen..
 
Würde es so gehen?

Java:
public class Main {
    public static void main(String args[]) {
        Board board = new Board();
        while (Terminal.readLine() != "quit") {
            try {
                String[] inputSplit = Terminal.readLine().split(" ");
                if (inputSplit[0] == "throwin") {
                    board.throwin(Integer.parseInt(inputSplit[1]));
                }
                else if (inputSplit[0] == "print") {
                    board.print();
                }
                else if (inputSplit[0] == "field") {
                    String[] split2 = inputSplit[1].split(",");
                    board.field(Integer.parseInt(split2[0]),Integer.parseInt(split2[1]));
                }
                else {
                    Terminal.printLine("Error unvalid command");
                }
               
            } catch (ArrayIndexOutOfBoundsException e) {
                Terminal.printLine("Error index out of array range");
            }
        }
    }
}
 
Zuletzt bearbeitet:
Kannst du das denn nicht testen?
Bin mir da nicht so sicher.

Meine Idee wäre jetzt noch:

Java:
if(s.startsWith("throwin")){
          int x = Integer.valueOf(s.valueOf(s.charAt(s.length()-1)));
          throwin(x);
}


Dann halt die restlichen Abfragen angepasst drunter und natürlich Fehlerbehandlung, NumberFormatException.
Eigentlich auch keine schöne Lösung aber was besseres fällt mir gerade nicht ein.
 
Also anscheinend wird bei mir der String nicht gesplittet, es wird immer else aufgerufen.
Gehört split zu java.util? Wir dürfen java.util nämlich nicht benutzen..

Ich werd mal deinen Vorschlag ausprobieren.
 
Split gehört eigentlich nicht zu java.util.
Die Beobachtung, dass Split nicht so funktioniert habe ich auch gerade gemacht beim Testen.
Mit Split habe ich bisher nicht gearbeitet.
 
Also jetzt kann ich zumindest mal die Methoden aufrufen, aber ich spring sofort auf catch wenn ich den erhaltenen x Wert als Parameter angebe
 
Und welche Exception?
Die Exception die ich mit catch abfange, aber das liegt glaube ich an meinem Code in der Klasse Board.
Die Methoden print() und field(x,y) funktionieren ja.

Falls jemand Lust hat mit mir nach dem Fehler zu suchen 😀

Java:
public class Main {
    public static void main(String args[]) {
        Board board = new Board();
        String input = "";
        String[] inputSplit = new String[2];
        int x;
        int y;
        while (input != "quit") {
            try {
                input = Terminal.readLine();
              
                if (input.startsWith("throwin")) {
                    x = Integer.valueOf(input.valueOf(input.charAt(input.length()-1)));
                    board.throwin(x);
                }
                else if (input.startsWith("print")) {
                    board.print();
                }
                else if (input.startsWith("field")) {
                    x = Integer.valueOf(input.valueOf(input.charAt(input.length()-3)));
                    y = Integer.valueOf(input.valueOf(input.charAt(input.length()-1)));
                    board.field(x,y);
                }
                else if (input.startsWith("quit")) {
                    System.exit(0);
                }
                else {
                    Terminal.printLine("Error unvalid command");
                }
              
            } catch (ArrayIndexOutOfBoundsException e) {
                Terminal.printLine("Error index out of array range");
            }
        }
    }
}

Java:
public class Board {
    int board[][] = new int[7][7];
    int player = 0;
  
    public Board() {
        int n = 2;
        for (int i = 0; i < 7; i++) {
            for (int j = 0; j < 7; j++) {
                this.board[i][j] = n;
                n++;
            }
        }
    }
  
    public void print() {
        String buffer;
        for (int i = 0; i < 7; i++) {
            buffer = "";
            for (int j = 0; j < 7; j++) {
                if (this.board[i][j] > 1) {
                    buffer = buffer + "-";
                }
                else {
                    buffer = buffer + this.board[i][j];
                }
            }
            Terminal.printLine(buffer);
        }
    }
  
    public void throwin(int index) {
        if (this.board[0][index] < 2) {
            Terminal.printLine("Error column full");
        }
        else {
            for (int i = 6; i >= 0; i--) {
                if (this.board[i][index] > 1) {
                    this.board[i][index] = player;
                    break;
                }
            }
            if (checkBoard() == true) {
                Terminal.printLine("P" + player + " wins");
            }
            else {
                if (player == 0) {
                    player++;
                }
                else {
                    player--;
                }
                Terminal.printLine("succes");
            }
              
        }
    }
  
    public void field(int x, int y){
        String output = "";
        if (this.board[x][y] > 1) {
            output = "-";
        }
        else {
            output = Integer.toString(board[x][y]);
        }
        Terminal.printLine(output);
    }
  
    private boolean checkBoard() {
        if (checkRow() == true || checkColumn() == true || checkDiagonal() == true) {
            return true;
        }
        else {
            return false;
        }
    }

    private boolean checkRow() {
        int count = 0;
      
        for (int i = 0; i < 7; i++) {
            for (int j = 0; j < 6; j++) {
                if (this.board[i][j] == this.board[i][j+1]) {
                    count++;
                    if (count >= 4) {
                        break;
                    }
                }
                else {
                    count = 0;
                }
            }
        }
        if (count >= 4) {
            return true;
        }
        else {
            return false;
        }
    }

    private boolean checkColumn() {
        int count = 0;
      
        for (int j = 0; j < 7; j++) {
            for (int i = 0; i < 6; i++) {
                if (this.board[i][j] == this.board[i+1][j]) {
                    count++;
                    if (count >= 4) {
                        break;
                    }
                }
                else {
                    count = 0;
                }
            }
        }
        if (count >= 4) {
            return true;
        }
        else {
            return false;
        }
    }

    private boolean checkDiagonal() {
        int count = 0;
        for (int i = 0; i < 4; i++) {
            if (count >= 4) {
                break;
            }
            count = 0;
            for (int j = 0; j < 6; j++) {
                if (i + j >= 6) {
                    break;
                }
                if (this.board[i+j][j] == this.board[i+j+1][j+1]) {
                    count++;
                    if (count >= 4) {
                        break;
                    }
                }
                else {
                    count = 0;
                }
            }
        }
        if (count >= 4) {
            return true;
        }
        else {
            for (int i = 3; i < 7; i++) {
                if (count >= 4) {
                    break;
                }
                count = 0;
                for (int j = 0; j < 6; j++) {
                    if (i - j <= 0) {
                        break;
                    }
                    if (this.board[i-j][j] == this.board[i-j-1][j+1]) {
                        count++;
                        if (count >= 4) {
                            break;
                        }
                    }
                    else {
                        count = 0;
                    }
                }
            }
            if (count >= 4) {
                return true;
            }
            else {
                return false;
            }
        }
    }
}
Edit:
Terminal Klasse für Terminal.readLine() und Terminal.printLine().
Java:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
* This class provides some simple methods for input/output from and to a terminal.
*
* Never modify this class, never upload it to Praktomat. This is only for your local use. If an assignment tells you to
* use this class for input and output never use System.out or System.in in the same assignment.
*
* @author ITI, VeriAlg Group
* @author IPD, SDQ Group
* @version 4
*/
public final class Terminal {

    /**
     * BufferedReader for reading from standard input line-by-line.
     */
    private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    /**
     * Private constructor to avoid object generation.
     */
    private Terminal() {
    }

    /**
     * Print a String to the standard output.
     *
     * The String out must not be null.
     *
     * @param out
     *            The string to be printed.
     */
    public static void printLine(String out) {
        System.out.println(out);
    }

    /**
     * Reads a line from standard input.
     *
     * Returns null at the end of the standard input.
     *
     * Use Ctrl+D to indicate the end of the standard input.
     *
     * @return The next line from the standard input or null.
     */
    public static String readLine() {
        try {
            return in.readLine();
        } catch (IOException e) {
            /*
             * rethrow unchecked (!) exception to prevent students from being forced to use Exceptions before they have
             * been introduced in the lecture.
             */
            throw new RuntimeException(e);
        }
    }

}
 
Zuletzt bearbeitet:
Gern geschehen.
Lag es an deinen Schleifen?
Hätte dir sonst nämlich geraten checkColumns und checkRow jeweil auf 6 statt auf 7 in der ersten Schleife zu setzen.
 

Neue Themen


Zurück
Oben