dirtyblankets
dirtyblankets

Reputation: 71

Eliminating the new line when using BufferedReader method to get user input using Java

In this first assignment I have to have the user input some number (ex: 312) then add each number and output something like: "The numbers are 3 1 2 with the sum of 6." Here are the codes:

public static void main(String[] args) {
    int Max_Size = 30;
    char[] myArray = new char [Max_Size];
    String temp = " ";
    char parse;
    int sum = 0;
    int counter = 0;
    System.out.print("Please enter a non-negative integer: ");

    try{
        BufferedReader dataIn = new BufferedReader(
                new InputStreamReader(System.in));
        temp = dataIn.readLine();
    } catch (IOException e) {
        System.out.println("Error!");
    }

   System.out.print("The numbers are ");
   //put each character of the string into a char array
   for (int i = 0; i < temp.length(); i++){
     myArray[i] = temp.charAt(i);
       System.out.print(myArray[i] + " ");
    }
   //take sum of each character as an integer
    while (counter != temp.length()){
        sum = sum + (myArray[counter] - '0');
        counter++;
    }
    System.out.println("with the sum of " + sum);
}

Here is a sample run:

Please enter a non-negative integer: 
312
The numbers are 3 1 2 with the sum of 6
BUILD SUCCESSFUL (total time: 7 seconds)

HOW DO I HAVE IT SO A NEW LINE ISN'T PLACED FOR THE INPUT: 312 ? Meaning I want it so it is like "Please enter a non-negative integer: 312", with the 312 in the same line. Also, is there a better way to parse the input into integers and put it into an integer array?

Upvotes: 1

Views: 1510

Answers (2)

Jack Leow
Jack Leow

Reputation: 22477

I suspect this may be due to the NetBeans console, or perhaps the fact that you appear to be executing this via Ant/Maven (perhaps a NetBeans thing).

(I'm assuming Ant/Maven due to the "BUILD SUCCESSFUL (total time: 7 seconds)" at the end).

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500155

I don't know why you're seeing that - I've just tried it and obtained this output:

Please enter a non-negative integer: 312
The numbers are 3 1 2 with the sum of 6

What platform are you running on?

I would say that your use of a char array is somewhat pointless when you can just use charAt(), and if you really do want to convert the input into a char array, I'd use String.toCharArray() instead.

Also, if you're using Java 1.6, I'd recommend:

String temp = System.console().readLine();

as a simpler way of reading a line of text from the user.

Upvotes: 3

Related Questions