用户的Java UserInputs不包含任何字符串

时间:2014-01-20 07:22:43

标签: java arraylist user-input

我正在制作一个战舰计划,用户违反8x8网格中的计算机随机输入选择。 我遇到的问题是,如果我的用户输入一个字符串,例如“asdfklasdn”,“h”等,我不希望我的程序崩溃...如果它是一个整数,它不会崩溃,例如如1,5等有没有办法在不将行和列更改为字符串的情况下更改此设置?如果我使用try catch,它只会在userFire方法中的if-else语句中给出错误。 任何帮助都感激不尽。谢谢!

import java.util.*;
import java.util.Scanner;

public class Battleship
{
Scanner input = new Scanner(System.in);
public static final boolean DEBUG = false;

public static void breakln()
{
    System.out.println("─────────────");
}

public static void createBoard(String [][]board)
{
    for( int r = 0; r<board.length; r++)
    {
        for(int c= 0; c<board[0].length; c++)
        {
            board[r][c] = "-";
        }
    }
}

public static void showBoard(String[][] board)
{
    breakln();
    for(int r =0; r<board.length;r++)
    {
        if(DEBUG == true)
        {
            for(int c = 0; c<board[0].length;c++)
            {
                System.out.print(" " +board[r][c]);
            }
            System.out.println("");
        }
        else
        {
            for(int c = 0; c<board[0].length;c++)
            {
                if(board[r][c].equals("S"))
                {
                    System.out.print(" " + "-");
                }
                else
                {
                    System.out.print(" " + board[r][c]);
                }
            }
            System.out.println("");
        }
    }
    breakln();
}

public static void createShip(String[][] board, int size)
{
    if(Math.random()<0.5)
    {
        int col = (int)(Math.random()*5);
        int row = (int)(Math.random()*7);
        for(int i = 0; i<size; i++)
        {
            board[row][col+i]="S";
        }
    }
    else
    {
        int col = (int)(Math.random()*7);
        int row = (int)(Math.random()*5);
        for(int i = 0; i<size; i++)
        {
            board[row+i][col]="S";
        }
    }
}

public static int userFire(String[][] board, int hits, int torps)
{
    Scanner input = new Scanner(System.in);
    int row,col;
    System.out.println("You have: " + torps + " torpedos");
    System.out.println("Select row to fire in: ");
    row = input.nextInt(); 
    while(row>8||row<1)
    {
        System.out.println("Invalid. Enter a valid row (1-8)");
        row = input.nextInt();
    }
    System.out.println("Select column to fire in: ");
    col = input.nextInt();
    while(col>8 || col<1) 
    {
        System.out.println("Invalid. Enter a valid column (1-8)");
        col = input.nextInt();
    }

    if(board[row-1][col-1].equals("S"))
    {
        hits++;
        System.out.println("HIT ");
        board[row-1][col-1] = "×";
    }
    else
    {
        System.out.println("MISS");
        board[row-1][col-1] = "Ø";
    }
    return hits;
}

public static void endOfGame(int hits, int torps)
{
    if(hits<4)
        System.out.println(" LOSE ");
    if(torps<1)
        System.out.println("You have lost all your torpedos.");
    else
        if(hits>=4)
        {
            System.out.println("WINNER");
        }
    System.out.println("");
}

public static void main(String[] args)
{
    System.out.println(" BATTLESHIP ");
    System.out.println("");

    String[][] board = new String[8][8];
    createBoard(board);
    createShip(board,4);
    int torps = 25;
    int hits = 0;

    while(torps>0 && hits<4)
    {
        showBoard(board);
        hits = userFire(board,hits,torps);
        torps--;
    }
    endOfGame(hits, torps);
}

}


我已经尝试过每个人的答案,但我在此代码中收到了错误。

if(board[row-1][col-1].equals("S"))
    {
        hits++;
        System.out.println("╠══ HIT ══╣");
        board[row-1][col-1] = "×";
    }
    else
    {
        System.out.println("╠══ MISS ══╣");
        board[row-1][col-1] = "Ø";
    }
    return hits;

5 个答案:

答案 0 :(得分:0)

在row = input.nextInt()或接收输入的每个变量中添加try / catch块;

以下是示例代码

 try{
     row = input.nextInt(); 
}
catch(Exception)
{

}

答案 1 :(得分:0)

抓住例外,例如

try {
  row = input.nextInt();
} catch (InputMismatchException e) {
  System.err.println("Input is not an integer"); // or do some error handling
}

答案 2 :(得分:0)

试试这个:

    System.out.println("Invalid. Enter a valid row (1-8)");
    String userInput = input.next();
    try {
        row = Integer.parseInt(userInput);
    } catch (NumberFormatException exp) {
        // Failed : Invalid input. Take actions if required. 
        // May be prompt user for correct input
    }

答案 3 :(得分:0)

您可以使用while(input.hasNextInt())并打印一条消息,说明您只需要整数?

或者像BroSlow说的那样。

答案 4 :(得分:0)

try {
  xxx = input.nextInt();
} catch(NumberFormatException nfe) {
   doXXXLoop();
}

// ....

public void doXXXLoop() {
  System.out.println("Not a valid number. Enter another:");

  try {
    xxx = input.nextInt();
  } catch(NumberFormatException nfe) {
    doXXXLoop();
  }
}

与其他代码不同,这将很容易重复,直到输入有效的int。将XXX替换为Row或Col或任何您想要的内容。