How to Directly Output Arrays, Traverse Strings, and Read Keyboard Input in Java
This article demonstrates how to print an int array using Arrays.toString, presents two methods for iterating over a string—via toCharArray and charAt—and explains proper usage of Scanner methods to read tokens, lines, and integers from the console, including handling of newline characters.
1. Directly Output an Array
int[] arr = {1, 2, 432, 32, 54, 32, 3, 7, 657};
System.out.println(Arrays.toString(arr));
// Output: [1, 2, 432, 32, 54, 32, 3, 7, 657]2. Two Approaches to Traverse a String
(a) Convert the string to a char array and iterate
Use toCharArray to obtain a character array, then use an enhanced for‑loop to print each character.
String str = "fje你kw我FDQFj你feAF他Eajf他eo2FA我FEjfew";
char[] str2 = str.toCharArray();
for (char c : str2) {
System.out.println(c);
}(b) Access characters directly with charAt()
Iterate over the string indices and call charAt(i) to get each character.
String str = "fje你kw我FDQFj你feAF他Eajf他eo2FA我FEjfew";
for (int i = 0; i < str.length(); i++) {
System.out.println(str.charAt(i));
}3. Reading Input from the Keyboard
Scanner sc = new Scanner(System.in);
String s = sc.next(); // reads a token separated by whitespace
String line = sc.nextLine(); // reads the rest of the line
int num = sc.nextInt(); // reads an integerNote: Methods like next() and nextInt() do not consume the line‑break character, while nextLine() does. After calling next() or nextInt(), a subsequent nextLine() may return an empty line. Call an extra nextLine() to consume the leftover newline before reading the intended line.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
