Java 2d数组TicTacToe NumberFormat错误 [英] Java 2d array TicTacToe NumberFormat error

查看:94
本文介绍了Java 2d数组TicTacToe NumberFormat错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的方法entreeIncorrecte在这里检查用户输入.如果lignecolonne的值不是"0","1","2"或"3"以外的其他值,我想打印出用户不正确并重新启动entreeIncorrecte的循环.如果我在行和列中分别输入"e"和"3",则编译器将显示以下信息:

My method entreeIncorrecte is there to check for user input. If the value for ligne and colonne are anything other than "0", "1", "2" or "3", I want to print out that the user was incorrect and restart the loop for entreeIncorrecte. If I enter "e" and "3" for the row and column, the compiler gives me:

线程主"中的异常java.lang.NumberFormatException:用于输入 字符串:"e"在 java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) 在java.base/java.lang.Integer.parseInt(Integer.java:652)在 java.base/java.lang.Integer.parseInt(Integer.java:770)在 td.Main.verifierEntree(Main.java:200)在 td.Main.jouerUnePartie(Main.java:152)在 td.Main.main(Main.java:32)处的td.Main.plusieursParties(Main.java:103)

Exception in thread "main" java.lang.NumberFormatException: For input string: "e" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.base/java.lang.Integer.parseInt(Integer.java:652) at java.base/java.lang.Integer.parseInt(Integer.java:770) at td.Main.verifierEntree(Main.java:200) at td.Main.jouerUnePartie(Main.java:152) at td.Main.plusieursParties(Main.java:103) at td.Main.main(Main.java:32)

这有什么关系吗?

N.B .:由于居住地的原因,按照惯例,必须用法语为我的变量,方法等编写代码,对于任何混乱,请提前抱歉.这是我的代码:

N.B.: The code has to be written in French for my variables, methods, etc. by convention because of where I live, so sorry in advance for any confusion. Here is my code:

package td;

import java.util.Random;
import java.util.Scanner;

public class Main {


// Initialisation des variables
public static String ligne, colonne;
public static Scanner scan;
public static char[][] tableau = new char[4][4];
public static char tourJoueur = 'O';
public static Random rand;
public static int scoreJ1;
public static int scoreJ2;
public static String nomJoueur1;
public static String nomJoueur2;

public static void main(String[] args) {
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 4; j++) {
            tableau[i][j] = ' ';
            // Introduction avant les jeux
            menuIntroduction();

            // Toutes les parties
            plusieursParties();

            // Message final
            menuFin();
        }
    }
}

private static void menuIntroduction() {
    printIntro();

    scoreJ1 = 0;
    scoreJ2 = 0;

    // Initialisation du Scanner
    scan = new Scanner(System.in);

    // Recuperation des noms des joueurs
    System.out.println("Joueur 1 rentrez votre nom");
    nomJoueur1 = scan.nextLine();

    System.out.println("Joueur 2 rentrez votre nom");
    nomJoueur2 = scan.nextLine();

    // Choix du premier joueur au hasard
    Random rand = new Random();
    if (rand.nextInt() % 2 == 0) {
        tourJoueur = 'O';
    } else {
        tourJoueur = 'X';

    }
}

private static void printIntro() {
    System.out.println("BIENVENU AU TIC TAC TOE!\n");
    System.out.println("Chaque joueur se fera assigner 'X' ou 'O'\n");
    System.out.println("Chaque joueur selectionnera une case dans le Tic Tac Toe.\n");
    System.out.println(
            "Il faudra selectionner une ligne (de 0-3) et peser sur ENTER. Il faudra ensuite selectionner une colonne et peser sur ENTER\n");
    System.out.println("Chaque joueur se fera assigner 'X' ou 'O', débutant par le joueur 1\n");
    System.out.println(
            "Pour gagner, il faudra compléter une ligne du tableau avec 'X' ou 'O', soit verticalement, soit horizontalement, soit diagonalement\n");
    System.out.println("Si le tableau est plein et qu'aucun joueur n'a fait de ligne, la partie sera nulle\n");
    System.out.println("Chaque partie gagnée donnera un point au joueur vainqueur\n");
    System.out.println("Bonne partie!");
    System.out.println();
    System.out.println("========================================================\n\n\n");

}

private static void menuFin() {
    System.out.println("=========================FIN DU JEU=========================\n\n\n");
    System.out.println("merci à " + nomJoueur1 + " et " + nomJoueur2 + " d'avoir joué ! ");

    // message de fin different selon le joueur gagnant ou s'il y a égalité
    if (scoreJ1 > scoreJ2) {
        System.out.println(nomJoueur1 + " l'emporte à " + scoreJ1 + " contre " + scoreJ2);
    } else if (scoreJ2 > scoreJ1) {
        System.out.println(nomJoueur2 + " l'emporte à " + scoreJ2 + " contre " + scoreJ1);

    } else {
        System.out.println("Égalité! " + scoreJ1 + " point(s) au total!");
    }
    System.out.println("\n\n\n\nÀ bientôt!");

}

private static void plusieursParties() {
    do {

        jouerUnePartie(tourJoueur);

    } while (onContinue());
}

private static boolean onContinue() {
    boolean inputContinue = false;
    boolean entreeIncorrecte = true;

    // tant que l'utilisateur ecrit n'importe quoi on lui redemande de faire un
    // choix
    do {
        System.out.println("les scores sont : ");
        System.out.println(nomJoueur1 + " : " + scoreJ1 + "  |||  " + nomJoueur2 + " : " + scoreJ2);
        System.out.println("voulez - vous continuer ? [Oui/Non]");

        String reponseUser = scan.nextLine();

        // cas un et deux reponse valide et transmise, cas trois le user dit n'importe
        // quoi
        if (reponseUser.equals("Oui")) {
            inputContinue = true;
            entreeIncorrecte = false;
        } else if (reponseUser.equals("Non")) {
            inputContinue = false;
            entreeIncorrecte = false;
        } else {
            System.out.println("Erreur, entrez 'Oui' ou 'Non'");
            entreeIncorrecte = true;
        }

    } while (entreeIncorrecte);

    // on renvoie la reponse de l'utilisateur lorsqu'elle est valide
    return inputContinue;
}

private static void jouerUnePartie(char tourJoueur1) {
    System.out.println("C'est au tour de " + nomJoueur1 + "!" + "Tu joues " + tourJoueur + "!\n");
    System.out.println("Entre une ligne et pèse sur ENTER");
    System.out.println("Entre une colonne et pèse sur ENTER");

    // Verifie si l'utilisateur utilise un chiffre et non quelque chose d'autre pour
    // ligne et pour colonne
    boolean jouant = true;
    do {
        afficherTableau();
        verifierEntree();

    } while (jouant);
    {
        int colonne2 = Integer.parseInt(colonne);
        int ligne2 = Integer.parseInt(ligne);

        tableau[ligne2][colonne2] = tourJoueur;
        if (victoire(scoreJ1, scoreJ1) && !tableauPlein()) {
            System.out.println("Felicitations! Le joueur " + tourJoueur + " gagne!");
            jouant = false;
        }


        if (!victoire(ligne2, colonne2) && tableauPlein()) {
            System.out.println("Partie nulle!");
            jouant = false;
        } else {
            jouant = true;
        }
        if (tourJoueur == 'O') {
            tourJoueur = 'X';
        } else {
            tourJoueur = 'O';
        }

    }
}

private static void verifierEntree() {

    boolean entreeIncorrecte = true;
    while (entreeIncorrecte) {

        ligne = scan.nextLine();
        colonne = scan.nextLine();

        if (ligne.contentEquals("0")) {
        }
        if (ligne.equals("0") || ligne.equals("1") || ligne.equals("2") || ligne.equals("3")) {
            entreeIncorrecte = false;
        } else if (colonne.equals("0") || colonne.equals("1") || colonne.equals("2") || colonne.equals("3")) {
            entreeIncorrecte = false;
        } else {
            System.out.println("Mauvaise entree! Recommence! ");
            entreeIncorrecte = true;
        }
        if (!entreeIncorrecte) {
            // Comment colonne2 et ligne2 ne sont pas utilisés?
            int colonne2 = Integer.parseInt(colonne);
            int ligne2 = Integer.parseInt(ligne);
        } else {

        }
    }
}

private static boolean victoire(int ligne2, int colonne2) {

    // Verifie horizontalement la victoire

    if (tableau[0][colonne2] == tableau[1][colonne2] && tableau[0][colonne2] == tableau[2][colonne2]
            && tableau[0][colonne2] == tableau[3][colonne2])
        return true;

    // Verifie verticalement la victoire

    if (tableau[ligne2][0] == tableau[ligne2][1] && tableau[ligne2][0] == tableau[ligne2][2]
            && tableau[ligne2][0] == tableau[ligne2][3])
        return true;

    // Verifie diagonalement vers la droite la victoire

    if (tableau[0][0] == tableau[1][1] && tableau[0][0] == tableau[2][2] && tableau[0][0] == tableau[3][3]
            && tableau[1][1] != ' ')
        return true;

    // Verifie diagonalement vers la gauche la victoire

    if (tableau[0][3] == tableau[1][2] && tableau[0][3] == tableau[2][1] && tableau[0][3] == tableau[3][0]
            && tableau[1][2] != ' ')
        return true;
    if (tableauPlein())
        return true;
    return false;
}

private static boolean tableauPlein() {
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 4; j++) {
            if (tableau[i][j] == ' ') {
                // Un tour peut etre fait, tableau non vide
                return false;
            }
        }
    }
    return true;

}

private static void afficherTableau() {
    for (int i = 0; i < 4; i++) {
        System.out.println();
        for (int j = 0; j < 4; j++) {
            if (j == 0) {
                System.out.print(" |");
            }
            System.out.print(tableau[i][j] + " |");
        }
    }
    System.out.println();
}
}

推荐答案

法语很好,但不幸的是我的法语知识非常有限.因此,我只是猜测"entreeIncorrecte"表示错误的用户输入.否则,至少可能是语法上的帮助:

French is fine but unfortunately my french knowledge is very limited. So I am just guessing "entreeIncorrecte" signals a wrong userinput. Otherwise it might at least be a syntactical help:

int colonne2 = 0;
int ligne2 = 0;
try{
   colonne2 = Integer.parseInt(colonne);
   ligne2 = Integer.parseInt(ligne);
} catch (NumberFormatException ignored){
    entreeIncorrecte = true;
}

如果您输入字母(例如"e")并将变量entreeIncorrecte设置为true,这会将变量设置为0.

This would set the variables to 0 if you entered a letter like "e" and set the variable entreeIncorrecte to true.

可能是您整个方法的替代品(里程数各不相同):

And this might be a replacment of your whole method(milage my vary):

private static void verifierEntree() {
    int intcolonne2 = 0;
    int intligne2 = 0; 
    boolean entreeIncorrecte = true;
    while (entreeIncorrecte) {

        ligne = scan.nextLine();
        colonne = scan.nextLine();

        if (ligne.contentEquals("0")) {
        }
        if (ligne.equals("0") || ligne.equals("1") || ligne.equals("2") || ligne.equals("3")) {
            entreeIncorrecte = false;
        } else if (colonne.equals("0") || colonne.equals("1") || colonne.equals("2") || colonne.equals("3")) {
            entreeIncorrecte = false;
        } else {
            System.out.println("Mauvaise entree! Recommence! ");
            entreeIncorrecte = true;
        }
        if (!entreeIncorrecte) {
        // Comment colonne2 et ligne2 ne sont pas utilisés?
            //int colonne2 = Integer.parseInt(colonne);
            //int ligne2 = Integer.parseInt(ligne);
            try{
                intcolonne2 = Integer.parseInt(colonne);
                intligne2 = Integer.parseInt(ligne);
            } catch (NumberFormatException ignored){
                intcolonne2 = 0;
                intligne2 = 0; 
                entreeIncorrecte = true;
            }
        } //else {

        if(entreeIncorrecte){

        }
     }
 }

或者类似这样的东西:

private static void verifierEntree() {
    int intcolone;
    int intligne;
    boolean entreeIncorrecte = true;
    while (entreeIncorrecte) {

        ligne = scan.nextLine();
        colonne = scan.nextLine();
        switch(ligne){
        case "0": 
        case "1":
        case "2":
        case "3":
            entreeIncorrecte = false;
            intligne = ligne.charAt(0)-'0';
            break;
        default: entreeIncorrecte = true;
        } 

        switch(colonne){
         case "0":
         case "1":
         case "2":
         case "3":
            intcolone = colonne.charAt(0)-'0';
            break;
         default: entreeIncorrecte = true;

         } 
         if(entreeIncorrecte) {
            System.out.println("Mauvaise entree! Recommence!");
         }
     }
 }

这篇关于Java 2d数组TicTacToe NumberFormat错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆