首页 > 解决方案 > 当我输入 10 时,我的代码不会读取第 10 行,当我输入负数时如何退出程序?

问题描述

当我输入 10 时,我的代码不会读取第 10 行,当我输入负数时如何退出程序?

这是错误。

Enter row and column number to reserve separated by space  (Enter a negative number to exit): -1
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
    at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:47)
    at java.base/java.lang.String.charAt(String.java:693)
    at SeatReservation.main(SeatReservation.java:33)

这是我的代码:我使用字符串而不是 int。我认为没关系,但现在我不能在我的 if 上使用代码 (seatNumber < 0)。我想使用它,所以当我输入负字符串数字时,程序将退出。同样,当我在行上输入 10 时,它无法读取它。我不能使用子字符串,因为它是字符串而不是 int。帮助我,我对此感到困惑和陌生。

import java.util.Scanner;

 public class SeatReservation {
     
     static int filled = 0 ;

    public static void main(String[] args)
    {

        char[][] seats = new char [10][4] ;
        for (int i = 0; i < 10; i++)
        {
            seats[i][0] = '*' ;
            seats[i][1] = '*' ;
            seats[i][2] = '*' ;
            seats[i][3] = '*' ;
        }

        String seatNumber = " " ; 
        String q = " " ;
        System.out.println("Bus Seat Reservation:") ;
        printSeats(seats) ;
        Scanner keyboard = new Scanner(System.in) ;
        seatNumber = keyboard.nextLine() ;
        if (seatNumber.equals("q"))
                {
                    System.out.println("Program exit!") ;
                    System.exit(0) ;
                } 
        while((filled < 40) && (seatNumber.length() > 0))
        {
            int row = seatNumber.charAt(0) - '1';
            int col = seatNumber.charAt(2) - '1';
            if (row < 0 || row > 10 || col < 0 || col > 4)
            {
                System.out.print("Input error. Enter row and column number to reserve separated by space  (Enter a negative number to exit): ");
                seatNumber = keyboard.nextLine() ;
                if (seatNumber.equals("q"))
                {
                    System.out.println("Program exit!") ;
                    System.exit(0) ;
                } 
            }
            else
            {
                if (seats[row][col] != 'X')
                {
                    seats[row][col] = 'X' ;
                    filled++ ; 
                    printSeats(seats) ;
                }
                if (filled < 40)
                {
                    seatNumber = keyboard.nextLine();
                    if (seatNumber.equals("q"))
                    {
                        System.out.println("Program exit!") ;
                        System.exit(0) ;
                    } 
                }
            }
        } 
        printSeats(seats); 
    }

    private static void printSeats(char[][] seats)
    {
        System.out.println("         Col 1   Col 2   Col 3   Col 4") ;
        for (int i = 0; i < seats.length; ++i)
        {
            System.out.println(("Row "+ (i + 1)) + "\t" +
                " |"+seats[i][0] + "      " + seats[i][1] + "       " + seats[i][2] + "        " + seats[i][3]) ;
        }
        System.out.print("Enter row and column number to reserve separated by space  (Enter a negative number to exit):");
        System.out.print(" ");
    }
}

请帮我解决一下这个。太感谢了!

标签: java

解决方案


好的,所以基本问题是,您想反复要求用户输入一个值,直到他们输入"q"一个负数。

于是这顿时惨叫了起来do-while loop。你需要至少做一个循环来获取输入,此时你可以决定如何处理它

boolean shouldEnd = false;
Scanner keyboard = new Scanner(System.in);
do {
    String seatNumber = " ";
    System.out.println("Bus Seat Reservation:");
    printSeats(seats);
    seatNumber = keyboard.nextLine();
    if (seatNumber.equals("q") || isNegativeNumber(seatNumber)) {
        shouldEnd = true;
    } else {
        // All the processing which needs to be done   
    }
    System.out.println("");
} while (!shouldEnd);

负值的测试涉及更多一点,因为String需要int先将其转换为值,并且您需要愿意处理输入不是数值的情况。为此,一个小助手方法开始发挥作用。

private static boolean isNegativeNumber(String input) {
    try {
        return Integer.parseInt(input) < 0;
    } catch (NumberFormatException exp) {
        return false;
    }
}

现在,进入处理输入。 String操作可能很棘手,您需要愿意处理输入格式符合您期望的所有可能情况。

我假设输入是row[space]col格式。为此,我们可以简单地在空间上拆分输入并检查我们是否有两个值,例如....

String[] parts = seatNumber.split(" ");
if (parts.length == 2) {
    // More processing   
} else {
    System.out.println("Invalid input, please use [row] [col]");
}

处理输入然后归结为简单地将您拥有的输入值转换为int值,验证输入是否在范围内并应用它们......

try {
    int row = Integer.parseInt(parts[0]) - 1;
    int col = Integer.parseInt(parts[1]) - 1;
    // Remember, you've zero index'ed your values, so it's 0 to 9 and 0 to 3
    // not 0 to 10 and 0 to 4
    if (row < 0 || row > 9 || col < 0 || col > 3) {
        System.out.println("Input error. Enter row and column number to reserve separated by space");
    } else {
        if (seats[row][col] != 'X') {
            seats[row][col] = 'X';
            filled++;
        }
    }
} catch (NumberFormatException exp) {
    System.out.println("Row/col input should be numeric value");
}

您会注意到,我只使用一个输入请求,并且在整个工作流程中只打印一次座位。每次循环再次运行时,都会打印座位并请求输入。这简化了工作流程并使其更易于管理

我没有检查filled状态,我会让你去做。

以上所有内容放在一起,可能看起来像......

import java.util.Scanner;

public class SeatReservation {

    static int filled = 0;

    public static void main(String[] args) {

        char[][] seats = new char[10][4];
        for (int i = 0; i < 10; i++) {
            seats[i][0] = '*';
            seats[i][1] = '*';
            seats[i][2] = '*';
            seats[i][3] = '*';
        }

        boolean shouldEnd = false;
        Scanner keyboard = new Scanner(System.in);
        do {
            String seatNumber = " ";
            System.out.println("Bus Seat Reservation:");
            printSeats(seats);
            seatNumber = keyboard.nextLine();
            if (seatNumber.equals("q") || isNegativeNumber(seatNumber)) {
                shouldEnd = true;
            } else {

                String[] parts = seatNumber.split(" ");
                if (parts.length == 2) {
                    try {
                        int row = Integer.parseInt(parts[0]) - 1;
                        int col = Integer.parseInt(parts[1]) - 1;
                        // Remember, you've zero index'ed your values, so it's 0 to 9 and 0 to 3
                        // not 0 to 10 and 0 to 4
                        if (row < 0 || row > 9 || col < 0 || col > 3) {
                            System.out.println("Input error. Enter row and column number to reserve separated by space");
                        } else {
                            if (seats[row][col] != 'X') {
                                seats[row][col] = 'X';
                                filled++;
                            }
                        }
                    } catch (NumberFormatException exp) {
                        System.out.println("Row/col input should be numeric value");
                    }
                } else {
                    System.out.println("Invalid input, please use [row] [col]");
                }
            }
            System.out.println("");
        } while (!shouldEnd);
    }

    private static boolean isNegativeNumber(String input) {
        try {
            return Integer.parseInt(input) < 0;
        } catch (NumberFormatException exp) {
            return false;
        }
    }

    private static void printSeats(char[][] seats) {
        System.out.println("         Col 1   Col 2   Col 3   Col 4");
        for (int i = 0; i < seats.length; ++i) {
            System.out.println(("Row " + (i + 1)) + "\t"
                    + " |" + seats[i][0] + "      " + seats[i][1] + "       " + seats[i][2] + "        " + seats[i][3]);
        }
        System.out.print("Enter row and column number to reserve separated by space  (Enter a negative number to exit):");
        System.out.print(" ");
    }
}

推荐阅读