写这样的循环会更惯用:for (currentRow = 0; currentRow < numRows; currentRow++) { currentColumnLetter = 'A'; for (currentColumn = 0; currentColumn < numColumns; currentColumn++) { System.out.print(currentRow + 1); System.out.print(currentColumnLetter + " "); currentColumnLetter++; }}I'm taking online classes, which makes it harder to get help, which is why I'm here. This week's lecture is on nested-loops. They are confusing the heck out of me. I am currently stuck on this problem. 1A 1B 1C 2A 2B 2C >I have tried many possible solutions which have yield many wrong results. This is my current solution int numRows; int numColumns; int currentRow; int currentColumn; char currentColumnLetter; numRows = scnr.nextInt(); numColumns = scnr.nextInt(); currentColumnLetter = 'A'; for (currentRow = 1; currentRow <= numRows; currentRow++) { for (currentColumn = 1; currentColumn < numColumns; currentColumn++) { System.out.print(currentRow); System.out.print(currentColumnLetter + " "); } if( currentColumn == numColumns) { currentColumnLetter++; } }The code yields this result 1A 1A 2B 2B The desired result is 1A 1B 2A 2BI've been going at it for two days and its making me seriously frustrated. Thanks in advance for any help. 解决方案 You're pretty close.However, you're not handling the column name correctly. As each row starts, you need to go back to A, and increment by one with each column:for (currentRow = 1; currentRow <= numRows; currentRow++) { currentColumnLetter = 'A'; //Starting a new row, reset the column to `A` for (currentColumn = 1; currentColumn < numColumns; currentColumn++){ System.out.print(currentRow); System.out.print(currentColumnLetter + " "); currentColumnLetter++; }}It's also pretty weird to be using 1-based indexing. Indexing in Java (as well as many other languages) should be started at 0. Your column loop doesn't perform enough iterations as a result - if you set numColumns to 2, you'll only print a single column.It would be more idiomatic to write the loops like this:for (currentRow = 0; currentRow < numRows; currentRow++) { currentColumnLetter = 'A'; for (currentColumn = 0; currentColumn < numColumns; currentColumn++) { System.out.print(currentRow + 1); System.out.print(currentColumnLetter + " "); currentColumnLetter++; }} 这篇关于需要修复循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-10 20:56