簡體   English   中英

代碼錯誤,對於要求輸入二維數組的索引並輸出該索引處的值的程序

[英]Error in code, for program that asks input of index for 2d array and outputs the value at that index

我有一項任務需要執行以下操作:

編寫一個程序,允許用戶輸入 integer 值並查詢大小為 9x9 的二維數組。 然后,您的程序應向用戶詢問一對坐標 (x, y),以空格分隔並返回給定坐標指定的 position 處的值。 例如,0 3 應該返回值 7(第一行第四列的值——記住數組索引從零開始)。 假設每個 integer 都是從 1 到 9 的單個數字。輸入 -1 作為任一坐標以結束程序。

我不斷收到此錯誤:

基數為 10 的 int() 的無效文字:''

這是代碼:

print("Enter an array:")
array_9x9 = [input() for i in range(9)]    

while True:
    # Read a line of coordinates, split into two elements, convert to integers
    x, y = map(int, input("Enter coordinates: ").split(' ', 2))
               
    # Stop if sentinel in either coordinate
    if -1 in (x, y):
        print("DONE")
        break
    # print the element at the specified coordinates
    print('Value = ' [array_9x9[x][y]])

這是 output:

Sample I/O:
Enter an array:
359716482
867345912
413928675
398574126
546281739
172639548
984163257
621857394
735492861
Enter coordinates:
0 3
Value = 7
Enter coordinates:
5 5
Value = 9
Enter coordinates:
8 8
Value = 1
Enter coordinates:
-1 -1
DONE

您沒有處理用戶輸入無效值時發生的錯誤。 當提示用戶是否只是不輸入任何內容並點擊時,您會看到您描述的錯誤。 同樣,如果用戶輸入非數字或意外值,您將收到類似的錯誤。

while True:
    try:
        x, y = map(int, input("Enter coordinates: ").split(' ', 2))
    except ValueError:
        continue
               
    if -1 in (x, y):
        print("DONE")
        break

    print('Value = ', array_9x9[x][y])  # fixed this line

如果用戶輸入的有效數字是無效索引(例如 12 或 -2),您還可以考慮額外的錯誤處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM