[英]Printing Array Backwards - Not printing the last Entry! - java
我正在嘗試創建一個String Revert程序,我在其中輸入String並將它們存儲在數組中-數組完成后,它將向后打印內容-如果用戶輸入Quit ,程序將停止並向后打印而不將退出存儲在數組中
但是我的代碼無法顯示最后一個條目。我不確定為什么嗎?
import java.util.*;
import java.io.*;
class StringRevert {
public static void main(String[] args) {
String buffer[];
Scanner scan = new Scanner(System.in);
System.out.println("Enter Size: ");
int num = scan.nextInt();
buffer = new String[num];
String read = scan.nextLine();
for(int i=0; i<buffer.length; i++) {
if(read.equals("quit")) {
break;
} else {
buffer[i] = read;
}
read = scan.nextLine();
}
for(int k=buffer.length -1; k>=0; k--) {
System.out.println(buffer[k]);
}
}
}
用以下代碼替換您的for循環:
String read = null;
for(int i=0; i<buffer.length; i++) {
read = scan.nextLine();
if(read.equals("quit")) {
break;
} else {
buffer[i] = read;
}
}
您想在循環的開頭而不是結尾處讀取新行。
我在代碼中發現的唯一問題是跳過nextInt()
之后的行nextInt()
方法不會占用整行,它只會將輸入的下一個標記作為int占用,因此您位於同一行(讀取int),則必須跳過該行。通過執行scan.nextLine();
在scan.nextInt();
String buffer[];
Scanner scan = new Scanner(System. in );
System.out.println("Enter Size: ");
int num = scan.nextInt();
buffer = new String[num];
scan.nextLine(); // skipping the line
String read = scan.nextLine();
for (int i = 0; i < buffer.length; i++) {
if (read.equals("quit")) {
break;
} else {
buffer[i] = read;
}
read = scan.nextLine();
}
for (int k = buffer.length - 1; k >= 0; k--) {
System.out.println(buffer[k]);
}
演示 (向后打印陣列)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.