Jump to content

Keyboard input to double

- - - - -

  • Please log in to reply
4 replies to this topic

#1
Lavaderman

Lavaderman

    Newbie

  • Members
  • Pip
  • 3 posts
Hi Guys!

Since I'm a newbie in Java I would probably ask dumb question. :c-smile:

I want to read a string from keyboard(array of string perhaps) e.g.
Enter some numbers:1.2 3.2 4 71.3
and convert it to Double array so I can easily calculate average later in some other method!

I planned to read it like:
BufferedReader line = new BufferedReader(

new InputStreamReader(System.in) ) ;

String array = line.readLine();


And I was wonder how to convert this string into an array of double.

Thank you!

:)

#2
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
String to double:
Double.parseDouble(array);
You could also use the Scanner class as input, it has predefined methods like nextInt, nextDouble, ...

Scanner input = new Scanner(System.in);

Double number = input.nextDouble();


I'm not sure what you want with the array. Does the user give in a bunch of doubles on 1 line or so?

#3
Lavaderman

Lavaderman

    Newbie

  • Members
  • Pip
  • 3 posts
Thank you on your answer, i will explain it to you :c-smile: . I want from user to enter in one line array of (it would be perfect if it were double) and my question is how to implement it in Java.
e.g
Enter an array:

1.2 3.4 5.1 34.2 6.7

Example of double array:
|1.2|3.4|5.1|34.2|6.7|
From there I need to calculate arithmetic middle and geometric middle in separated methods(not a problem). I know how to write method to turn String[] into double[], but I don't know how to read String[].

#4
Lavaderman

Lavaderman

    Newbie

  • Members
  • Pip
  • 3 posts
double post. sorry :cool:

#5
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
Then you would just read the line like you did:

String doubleLine = line.readLine();

Then you split the String on space:

String[] doubles = doubleLine.split(" ");

Then all you need to do is loop trough the array and parse to doubles.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users