Java数组输入提示行号列号显示异常问题求助
解决Java数组索引转1-based行号列号时的字符串拼接问题
问题原因
问题出在字符串拼接的优先级上。Java中+运算符处理字符串和数字时,会从左到右依次执行:
- 执行
"Please enter the integer for row: " +i+1时,首先将字符串与整数i拼接成新字符串(比如i=0时,得到"Please enter the integer for row: 0"),随后再将这个字符串与1拼接,最终输出"Please enter the integer for row: 01",而非先计算i+1的数值。
修复方案
有两种简单的修复方式:
用括号强制优先计算算术运算
把出错的代码行修改为:System.out.println("Please enter the integer for row: " + (i+1) + " column: " + (j+1));括号会让
i+1和j+1先完成算术计算,得到正确的1-based数字后,再与字符串拼接。提前计算行号列号(可读性更优)
先将行号列号存入变量,再进行字符串拼接:int rowNum = i + 1; int colNum = j + 1; System.out.println("Please enter the integer for row: " + rowNum + " column: " + colNum);
修复后的完整代码
import java.util.Scanner; public class doubleArray{ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Hello! This program creates an array of numbers of your choosing and size!"); System.out.println("Please enter the number of rows for your array!"); int rows = scanner.nextInt(); System.out.println("Please enter the number of columns for your array!"); int columns = scanner.nextInt(); int storage[][] = new int[rows][columns]; for(int i=0; i<storage.length; i++) { System.out.println(); for (int j=0; j<storage[i].length; j++) { // 修复后的代码 System.out.println("Please enter the integer for row: " + (i+1) + " column: " + (j+1)); storage[i][j] = scanner.nextInt(); } } for(int i=0; i<storage.length; i++) { System.out.println(); for(int j=0; j<storage[i].length; j++) { System.out.print(storage[i][j]+ " "); } } scanner.close(); } }
内容的提问来源于stack exchange,提问作者jbjswim
相关产品推荐
相关产品推荐

