Mein Programm beendet sich ohne mein Zutun

Javafan21

Mitglied
Hallo!
Folgendes Programm beendet sich selbständig nach der Festlegung des zu erratenden Wortes! Wie kann ich das fixen?

Java:
import javax.swing.JOptionPane;
public class GalgenmännchenMP {
public static void main(String[] bla) {
System.out.println("Herzlich Willkommen zum lokalen Multiplayer des Galgenmännchen. Dieses Spiel wurde von Simon Wieser entwickelt. Wenden Sie Sich bitte im Falle auftretender Beschwerden an musterfrau@example.com. Ich wünsche Ihnen viel Spielspaß!");
String ZuErratendesWort = JOptionPane.showInputDialog (null, "Spieler 1, bitte geben Sie das von Spieler 2 zu erratende Wort ein", "Wahl des Wortes", JOptionPane.PLAIN_MESSAGE);
System.exit(0);
int versuche = 0;
System.out.println("Spieler 2, Sie haben jetzt 10 Versuche!");
while (true) {
System.out.println("Spieler 2, bitte erraten Sie das Wort");
String Rateversuch = new java.util.Scanner(System.in).nextLine();
if(versuche > 10) {
System.out.println("Ihre Versuche sind aufgebraucht");
return;
}
versuche++;
System.out.println("Sie haben bislang " + versuche + " Versuche benötigt");
if(Rateversuch == ZuErratendesWort) {
System.out.println("Bravo! Sie haben das Wort erraten!");
return;
} else {
System.out.println("Schade, das war nichts");
}
}
}
}
 
Zuletzt bearbeitet von einem Moderator:
Java:
public class GalgenmännchenMP {
  public static void main(String[] bla) {
    ...
    String ZuErratendesWort = JOptionPane.showInputDialog(null,
        "Spieler 1, bitte geben Sie das von Spieler 2 zu erratende Wort ein", "Wahl des Wortes",
        JOptionPane.PLAIN_MESSAGE);
    System.exit(0);  <========= GRUND!
    int versuche = 0;
    System.out.println("Spieler 2, Sie haben jetzt 10 Versuche!");
    ...
  }
}
 
Das Programm scheint noch andere Fehler zu haben, im lokalen Testlauf konnte man das zu erratende Wort zwar eingeben, aber für Spieler 2 hatte das keine Auswirkungen. Unter Eclipse gibt es in den Zeilen 11 ("String Rateversuch..."), 14 und 20 eine Warnmeldung: "Resource leak: <unasignable Clossable value> is never closed" oder "is not closed at this location" Ausserdem sollte es "if(versuche > 9)" heissen (Java-Indizes sind nullbasiert)
 
Strings werden auch nicht mit== sondern mit equals verglichen.

Und die Reihenfolge ist zumindest seltsam. Man gibt noch einen Rateversuch ein und bekommt dann erst angezeigt, dass die Versuche aufgebraucht würden? Oder habe ich das falsch gesehen?
 
@Javafan21 Tu Dir und uns einen Gefallen, und halte Dich auch an die Benenunngskonventionen von Java: Variablen, Parameter und Methoden werden in lowerCamelCase geschrieben, Namen von Typen wie Klassen in UpperCamelCase. Das Misch-Masch ist fürchterlich zu lesen. Außerdem vermeide für diese Dinge auch Umlaute.
 
Hallo!
Folgendes Programm beendet sich selbständig nach der Festlegung des zu erratenden Wortes! Wie kann ich das fixen?
Du solltest versuchen Dein Programm besser zu strukturieren. Hier ein Beispiel wie man Funktionen wiederverwenden kann.
Teste diese kleine Konsole Galgenmannversion, und versuche sie nachzuvollziehen.
Java:
mport java.util.Scanner;

public class Gallow {
    private static Scanner in = new Scanner(System.in);
    private static WordServer wordServer = WordServer.getInstance();
    public static final int MAX_MISTAKES = 8;

    public static void main(String[] args) {
        enterGameByNewWord();
        boolean playing = true;
        while (playing && doGame())
            playing = isYesAnswer("Wollen Sie noch einmal spielen");
        wordServer.printWords();
        in.close();
    }

    private static boolean doGame() {
        int mistakes = 0;
        String word = wordServer.getNotUsedRandomWord();
        if (word == null) {
            System.out.println("Alle Wörter sind schon benutzt worden!");
            return false;
        }

        char[] found = new char[word.length()];
        for (int i = 0; i < found.length; i++)
            found[i] = '.';
        do {
            printSeperator();
            char c = inputLetter(word, found, mistakes);

            int idx = word.indexOf(c);
            if (idx < 0) {
                mistakes++;
                if (mistakes == MAX_MISTAKES) {
                    System.out.println("Leider konntest Du das Wort '" + word + "' nicht erraten!\n");
                    return true;
                }
            } else {
                found[idx] = c;
                while ((idx + 1) < word.length() && (idx = word.indexOf(c, idx + 1)) >= 0)
                    found[idx] = c;
            }

        } while (!word.equals(new String(found)));
        System.out.println("\nBravo, Du hast das Wort '" + word + "' erraten!\n");
        return true;
    }

    public static void drawGallow(int mistakes, char[] found) {
        String[][] man = { { "   |" }, { "   O" }, { "  /", "|", "\\" }, { "  _", "|", "_" } };
        System.out.println("+---+\t" + new String(found));
        for (int i = 0; i < man.length; i++) {
            System.out.print("|");
            if (i < 2) {
                if (mistakes > i)
                    System.out.print(man[i][0]);
            } else {
                int offMistake = mistakes - 2 - 3 * (i - 2);
                if (offMistake > 3)
                    offMistake = 3;
                for (int ii = 0; ii < offMistake; ii++)
                    System.out.print(man[i][ii]);
            }
            System.out.println();
        }
        System.out.println("+");
    }

    private static void enterGameByNewWord() {
        printSeperator();
        System.out.println("Willkommen zum Galgenmann - Spiel:\n\n");
        String word = null;
        boolean ok = false;
        do {
            System.out.println("Um das Spiel zu beginnen geben Sie bitte ein neues korektes Suchwort ein!");
            word = inputNewWord();
            if (word == null)
                continue;
            if (wordServer.contains(word))
                System.out.println("Das Wort '" + word + "' existiert bereits!");
            else {
                wordServer.addWord(word);
                wordServer.setwordUsed(word);
                ok = true;
            }
        } while (!ok);
        wordServer.save();
        System.out.println();
    }

    public static char inputChar() {
        String input = in.nextLine();
        if (input == null || input.length() == 0)
            return '\n';
        return input.toUpperCase().charAt(0);
    }

    private static char inputLetter(String word, char[] found, int mistakes) {
        drawGallow(mistakes, found);
        System.out.print("Gebens Sie eine Buchstaben ein: ");
        return inputChar();
    }

    public static String inputNewWord() {
        System.out.println("Geben Sie ein neues Suchwort ein:");
        String word = in.nextLine();
        if (!isYesAnswer("Ist das Word " + word + " korrekt ?"))
            return null;
        return word;
    }

Java:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;

public class WordServer {
    public static final String wordFile = "./words.txt";
    private static final Random rnd = new Random(System.currentTimeMillis());
    private static ArrayList<String> words = new ArrayList<String>();
    private static ArrayList<String> usedWords = new ArrayList<String>();
    private static WordServer instance = null;

    private static boolean changed = false;

    private WordServer() {
        load();
    }

    public boolean addWord(String word) {
        word = formatWord(word);
        if (words.contains(word))
            return false;
        changed = true;
        return words.add(word);
    }

    public static String formatWord(String word) {
        return word.trim().toUpperCase();
    }

    public boolean contains(String word) {
        word = formatWord(word);
        return words.contains(word);
    }

    public static WordServer getInstance() {
        if (instance == null)
            instance = new WordServer();
        return instance;
    }

    public String getNotUsedRandomWord() {
        String word = getRandomWord();
        while (word != null && usedWords.contains(word))
            word = getRandomWord();
        usedWords.add(word);
        return word;
    }

    private String getRandomWord() {
        if (isEmpty() || usedWords.size() == words.size())
            return null;
        return words.get(rnd.nextInt(words.size()));
    }

    public boolean isEmpty() {
        return words.isEmpty();
    }

    private void load() {
        File file = new File(wordFile);
        if (!file.exists()) {
            addWord("haus");
            addWord("mauer");
            addWord("kuchen");
            save();
            return;
        }
        try {
            FileReader fR = new FileReader(file);
            BufferedReader bR = new BufferedReader(fR);
            String word = null;
            while ((word = bR.readLine()) != null)
                addWord(word);
            bR.close();
            fR.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void printWords() {
        Iterator<String> it = words.iterator();
        int i = 1;
        while (it.hasNext()) {
            System.out.print(it.next());
            if (i % 5 == 0)
                System.out.println();
            else if (it.hasNext())
                System.out.print(", ");
            i++;
        }
    }

    public boolean removeWord(String word) {
        boolean ok = words.remove(word);
        if (ok)
            changed = true;
        return ok;
    }

    public void resetUsedWords() {
        usedWords.clear();
    }

    public void setwordUsed(String word) {
        word = formatWord(word);
        if (words.contains(word))
            usedWords.add(word);
    }

    public void save() {
        if (!changed)
            return;
        try {
            FileWriter fW = new FileWriter(wordFile, false);
            PrintWriter pW = new PrintWriter(fW, true);
            Iterator<String> it = words.iterator();
            while (it.hasNext())
                pW.println(it.next());
            pW.close();
            fW.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
 
Das erste Programm lässt sich über die Änderung in der Zeile 18 in "if(Rateversuch.equals(ZuErratendesWort)) { " sogar zum Laufen bringen (ändert aber nichts an anderen Designfehlern und Warnmeldungen). Im zweiten Programmvorschlag sollte es wohl "Sep_a_rator" heissen (ist lt. Eclipse zusammen mit isYesAnswer aber undefiniert), trotzdem weist dieser Vorschlag solidere Praktiken auf.
 
"Sep_a_rator" heissen (ist lt. Eclipse zusammen mit isYesAnswer aber undefiniert),
Sorry da ging bei Copy Paste etwas daneben. Hier der vollständige Code.
Java:
import java.util.Scanner;

public class Gallow {
    private static Scanner in = new Scanner(System.in);
    private static WordServer wordServer = WordServer.getInstance();
    public static final int MAX_MISTAKES = 8;

    public static void main(String[] args) {
        enterGameByNewWord();
        boolean playing = true;
        while (playing && doGame())
            playing = isYesAnswer("Wollen Sie noch einmal spielen");
        wordServer.printWords();
        in.close();
    }

    private static boolean doGame() {
        int mistakes = 0;
        String word = wordServer.getNotUsedRandomWord();
        if (word == null) {
            System.out.println("Alle Wörter sind schon benutzt worden!");
            return false;
        }

        char[] found = new char[word.length()];
        for (int i = 0; i < found.length; i++)
            found[i] = '.';
        do {
            printSeperator();
            char c = inputLetter(word, found, mistakes);

            int idx = word.indexOf(c);
            if (idx < 0) {
                mistakes++;
                if (mistakes == MAX_MISTAKES) {
                    System.out.println("Leider konntest Du das Wort '" + word + "' nicht erraten!\n");
                    return true;
                }
            } else {
                found[idx] = c;
                while ((idx + 1) < word.length() && (idx = word.indexOf(c, idx + 1)) >= 0)
                    found[idx] = c;
            }

        } while (!word.equals(new String(found)));
        System.out.println("\nBravo, Du hast das Wort '" + word + "' erraten!\n");
        return true;
    }

    public static void drawGallow(int mistakes, char[] found) {
        String[][] man = { { "   |" }, { "   O" }, { "  /", "|", "\\" }, { "  _", "|", "_" } };
        System.out.println("+---+\t" + new String(found));
        for (int i = 0; i < man.length; i++) {
            System.out.print("|");
            if (i < 2) {
                if (mistakes > i)
                    System.out.print(man[i][0]);
            } else {
                int offMistake = mistakes - 2 - 3 * (i - 2);
                if (offMistake > 3)
                    offMistake = 3;
                for (int ii = 0; ii < offMistake; ii++)
                    System.out.print(man[i][ii]);
            }
            System.out.println();
        }
        System.out.println("+");
    }

    private static void enterGameByNewWord() {
        printSeperator();
        System.out.println("Willkommen zum Galgenmann - Spiel:\n\n");
        String word = null;
        boolean ok = false;
        do {
            System.out.println("Um das Spiel zu beginnen geben Sie bitte ein neues korektes Suchwort ein!");
            word = inputNewWord();
            if (word == null)
                continue;
            if (wordServer.contains(word))
                System.out.println("Das Wort '" + word + "' existiert bereits!");
            else {
                wordServer.addWord(word);
                wordServer.setwordUsed(word);
                ok = true;
            }
        } while (!ok);
        wordServer.save();
        System.out.println();
    }

    public static char inputChar() {
        String input = in.nextLine();
        if (input == null || input.length() == 0)
            return '\n';
        return input.toUpperCase().charAt(0);
    }

    private static char inputLetter(String word, char[] found, int mistakes) {
        drawGallow(mistakes, found);
        System.out.print("Gebens Sie eine Buchstaben ein: ");
        return inputChar();
    }

    public static String inputNewWord() {
        System.out.println("Geben Sie ein neues Suchwort ein:");
        String word = in.nextLine();
        if (!isYesAnswer("Ist das Word " + word + " korrekt ?"))
            return null;
        return word;
    }

    public static boolean isYesAnswer(String label) {
        System.out.print(label + "\t(J fuer ja) :");
        char c = inputChar();
        return c == 'J';
    }

    private static void printSeperator() {
        System.out.println("**********************************");

    }

}
Java:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;

public class WordServer {
    public static final String wordFile = "./words.txt";
    private static final Random rnd = new Random(System.currentTimeMillis());
    private static ArrayList<String> words = new ArrayList<String>();
    private static ArrayList<String> usedWords = new ArrayList<String>();
    private static WordServer instance = null;

    private static boolean changed = false;

    private WordServer() {
        load();
    }

    public boolean addWord(String word) {
        word = formatWord(word);
        if (words.contains(word))
            return false;
        changed = true;
        return words.add(word);
    }

    public static String formatWord(String word) {
        return word.trim().toUpperCase();
    }

    public boolean contains(String word) {
        word = formatWord(word);
        return words.contains(word);
    }

    public static WordServer getInstance() {
        if (instance == null)
            instance = new WordServer();
        return instance;
    }

    public String getNotUsedRandomWord() {
        String word = getRandomWord();
        while (word != null && usedWords.contains(word))
            word = getRandomWord();
        usedWords.add(word);
        return word;
    }

    private String getRandomWord() {
        if (isEmpty() || usedWords.size() == words.size())
            return null;
        return words.get(rnd.nextInt(words.size()));
    }

    public boolean isEmpty() {
        return words.isEmpty();
    }

    private void load() {
        File file = new File(wordFile);
        if (!file.exists()) {
            addWord("haus");
            addWord("mauer");
            addWord("kuchen");
            save();
            return;
        }
        try {
            FileReader fR = new FileReader(file);
            BufferedReader bR = new BufferedReader(fR);
            String word = null;
            while ((word = bR.readLine()) != null)
                addWord(word);
            bR.close();
            fR.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void printWords() {
        Iterator<String> it = words.iterator();
        int i = 1;
        while (it.hasNext()) {
            System.out.print(it.next());
            if (i % 5 == 0)
                System.out.println();
            else if (it.hasNext())
                System.out.print(", ");
            i++;
        }
    }

    public boolean removeWord(String word) {
        boolean ok = words.remove(word);
        if (ok)
            changed = true;
        return ok;
    }

    public void resetUsedWords() {
        usedWords.clear();
    }

    public void setwordUsed(String word) {
        word = formatWord(word);
        if (words.contains(word))
            usedWords.add(word);
    }

    public void save() {
        if (!changed)
            return;
        try {
            FileWriter fW = new FileWriter(wordFile, false);
            PrintWriter pW = new PrintWriter(fW, true);
            Iterator<String> it = words.iterator();
            while (it.hasNext())
                pW.println(it.next());
            pW.close();
            fW.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
 

Zurück
Oben