为何无法将含空格、逗号的用户输入字符串存入ArrayList?
Hey there! Let's break down why your address input is getting truncated. The root issue is how Scanner.next() behaves—it stops reading input as soon as it hits any whitespace character (spaces, tabs, newlines, etc.). That's why when you type "1, 2nd Street road", only "1" gets stored: the space right after the comma tells next() to stop processing that input.
Fix 1: Use nextLine() with a buffer cleanup
If you want to keep using next() for the location (though it's not strictly necessary), you need to handle the leftover newline character in the input buffer first. Here's the adjusted code:
import java.util.*; class Main{ public static void main(String args[]){ Scanner sc = new Scanner(System.in); ArrayList<String> list = new ArrayList<String>(); System.out.println("Enter Location"); list.add(sc.next()); // Consume the remaining newline character left by next() sc.nextLine(); System.out.println("Enter the Address"); list.add(sc.nextLine()); System.out.println(list); } }
Fix 2: Use nextLine() for all inputs
A simpler approach is to use nextLine() for both inputs. This method reads an entire line of text (including spaces and commas) until the user presses enter, which is exactly what you need for addresses. Here's how that looks:
import java.util.*; class Main{ public static void main(String args[]){ Scanner sc = new Scanner(System.in); ArrayList<String> list = new ArrayList<String>(); System.out.println("Enter Location"); list.add(sc.nextLine()); System.out.println("Enter the Address"); list.add(sc.nextLine()); System.out.println(list); } }
Quick note on the buffer issue
When you use next(), it only reads up to the first whitespace, leaving the rest of the line (including the newline from pressing enter) in the input buffer. If you call nextLine() immediately after, it'll read that leftover newline as an empty string instead of your actual address. That's why Fix 1 adds an extra sc.nextLine() to clear that buffer before reading the address.
内容的提问来源于stack exchange,提问作者SMR

