-2

I'm really new to Java programming, so this is a simple question I guess.

I need to write a program that gets as an input the height and weight of a person as one string in which the height and weight separated by white space, for example: 1.68 70

and it calculates and prints the BMI (calculation by the formula weight/height^2).

I read on the internet that getting input from the user can be done by the Scanner class, and that's what I used. Now I want to save the height and weight in different variables so I can convert them from string to Double, but I don't know how to do it as the whole input is one string . I'm used to Python and slicing :( .. Please help? Thanks a lot.

CnR
  • 351
  • 1
  • 6
  • 15

2 Answers2

2

Based on your comments in the other answer, it looks like you're using a Scanner already. Try something like this.

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter stuff");
    double height = scanner.nextDouble();
    double weight = scanner.nextDouble();

    // do your stuff
}
Ian McLaird
  • 5,507
  • 2
  • 22
  • 31
1

Here you go.

How to split a String by space

This splits the string into an array on any number of white space. Returns an array of your values. The first value in your string will be in your array at position [0] while the second value at [1].

So to relate that to your example...

String value = "1.68 70";
String[] splitValues = value.split("\\s+");

Double height = Double.parseDouble(splitValues[0]);
Double weight = Double.parseDouble(splitValues[1]);
Community
  • 1
  • 1
zarry
  • 70
  • 5
  • What is the other problem you are hitting? – zarry Feb 18 '14 at 20:38
  • Thanks a lot, I have one more problem - with the input. I imported java.util.Scanner; asked from the user to type the data by System.out.println, and then typed Scanner str = new Scanner(System.in); How can I use your code not on a specific input but on the Scanner ? – CnR Feb 18 '14 at 20:40
  • @CnR, the scanner can read straight into the doubles for you, without needing this code at all. See http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextDouble() – Ian McLaird Feb 18 '14 at 20:40
  • @IanMcLaird But I need to separate them first into 2 numbers.. – CnR Feb 18 '14 at 20:42
  • @CnR, if they're on `System.in` separated by a space, call `nextDouble` *twice*. – Ian McLaird Feb 18 '14 at 20:43