Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.9k views
in Technique[技术] by (71.8m points)

java - How to display array line by line by pressing Enter

the scope of this problem is to have each emelent of the array displayed when I hit Enter. I came across System.in.read() method and it kind of works but if I type a bunch of random characters and then hit enter it will not only display the next line but displays several elements in a row... I have tried different ways of solving it but to no avail. Hopefully, someone can at least point me in the right direction. Below is my simplified code. Thanks

import java.io.IOException; import java.util.Scanner;

public class classClass { public static void main(String[] args) throws IOException {

    int[] array = new int[10];
    for (int i = 0; i < array.length; i++) {
        array[i] = i;
    }
    for (int i = 0; i < array.length; i++) {
        System.out.print(array[i]);
        System.in.read();
    }
}   

}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Seeing as you already imported java.util.Scanner, you could just use Scanner's .nextLine() method like so:

import java.io.IOException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws IOException {

        int[] array = new int[10];
        for (int i = 0; i < array.length; i++) {
            array[i] = i;
        }
        Scanner sc = new Scanner(System.in);
        for (int i = 0; i < array.length; i++) {
            sc.nextLine();
            System.out.print(array[i]);
        }
    }
}

You need to read the entire line. System.in.read() only reads the next character.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...