Home > front end >  Give a random age number between 0-9 Java
Give a random age number between 0-9 Java

Time:04-04

So I'm currently a beginner programmer trying to slove some basic programming tasks. But I dont understand why My code is wrong. In eclipse everyting works. It's a coding problem from codewars.com

Introduction: You ask a small girl,"How old are you?" She always says, "x years old", where x is a random number between 0 and 9.

Write a program that returns the girl's age (0-9) as an integer.

Assume the test input string is always a valid string. For example, the test input may be "1 year old" or "5 years old". The first character in the string is always a number.

package headfirstjava;
import java.util.Random;



public class do_something5 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        {
        int min =1;
        int max =9;
        int age1 = (int)Math.round(Math.random() * (max - min)  min);
        int age2 = (int)Math.round(Math.random() * (max - min   1)  min);
        System.out.println("I'm "  age1  " Old");
    }
    
    }

}

CodePudding user response:

I think you didn't understand the problem asked. Here the input of the program is the string "x years old" and you have to return "x" as an integer :

return Integer.parseInt(input.substr(0,1))

CodePudding user response:

I am not sure what the problem is. Try this if the problem is with generating random number:

    // create random object
    Random ran = new Random();

    // Print next int value
    // Returns number between 0-9
    int nxt = ran.nextInt(10);

    // Printing the random number 
    // between 0 and 9
    System.out.println
    ("Random number between 0 and 9 is : "   nxt);

Also check out Random class in java! (Sry if this doesn't help)

CodePudding user response:

If you simply want to extract a number from a specific string format (means you know where the number you are looking for is) use the Character.getNumericValue(string.charAt(0)) method.

Scanner scanner = new Scanner(System.in)
System.out.println("How old are you?");
String s= scanner.nextLine();  
char c=s.charAt(0);
System.out.println("1st character is: "  Character.getNumericValue(c) );  

This is the simplest form that you can go. I suggest you go through w3schools.com for the basics.

  •  Tags:  
  • java
  • Related