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

Categories

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();
    }
}   

}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.6k views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...