Give a random age number between 0-9 Java - java

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

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))

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)

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.

Related

Java picks any random number as the correct answer

I want to develop a "periodic table tester" which asks you the atomic number of any random element. If you answer wrong, it will tell you the correct answer.Here's my code:
import java.util.Scanner;
import java.util.Random;
import java.util.Arrays;
class element {
public static void main(String[] args) {
// create an object of Scanner class
Scanner input = new Scanner(System.in);
// creating an array of elements (only first thirty for now)
String[] elements = {"hydrogen", "helium", "lithium", "berylium", "boron", "carbon", "nitrogen", "oxygen", "flourine", "neon", "sodium", "magnesium", "aluminium", "silicon", "phosphorus", "sulphur", "chlorine", "argon", "potassium", "calcium", "scandium", "titanium", "vandium", "chromium", "manganese", "iron", "cobalt", "nickel", "copper", "zinc"};
// pick a random element
Random random = new Random();
int pickRandom = random.nextInt(elements.length);
String randomElement = elements[pickRandom];
// ask the question
System.out.println("What is the atomic number of "+ randomElement + "?");
System.out.print("Your answer: ");
// ask for input
int yourAnswer = input.nextInt();
// check the answer
int result = Arrays.binarySearch(elements, randomElement);
int recievedInput = yourAnswer - 1;
int correctAnswer = result + 1;
if (recievedInput == result) {
System.out.println("Correct Answer!");
} else {
System.out.println("Sorry, but you need some more practice. The correct answer is " + correctAnswer + ".");
}
// close the object with Scanner class
input.close();
}
}
Its output should be like
$ java element
What is the atomic number of nitrogen?
Your answer: 7
Correct Answer!
$ java element
What is the atomic number of helium?
Your answer: 5
Sorry, but you need some more practice. The correct answer is 2.
But, it's like:
$ java element
What is the atomic number of oxygen?
Your answer: 8
Sorry, but you need some more practice. The correct answer is -10.
$ java element
What is the atomic number of chromium?
Your answer: 0
Correct Answer!
$ java element
What is the atomic number of lithium?
Your answer: 3
Correct Answer!
How should I solve the problem?
You're using Arrays.binarySearch() on the wrong type of data set. It needs to take a sorted input to work properly.
try this
//Make it List<> so you have access to the method indexof
List<String> list = Arrays.AsList(elements);
int CurrectAnswer = list.indexof(randomElement);
if (yourAnswer==CurrectAnwser){
System.out.println("You found it");
}
else {
System.out.println("The Currect Answer was"+CurrectAnswer);
}
// close the object with Scanner class
input.close();
You don't need to perform a Binary Search to find the correct answer and also it will fetch incorrect results most of the times as the elements array is not sorted.
So, as we already know the index of the random element selected at the beginning which in nothing but elements[pickRandom]. So we can verify the result by checking if the elements in the index yourAnswer-1 (yourAnswer-1 as you have started your periodic table from index 0) are the same or not.
int correctAnswer = pickRandom;
if (elements[recievedInput].equals(elements[yourAnswer-1]))
System.out.println("Correct Answer!");
else
System.out.println("Sorry, but you need some more practice. The correct answer is " + (correctAnswer+1) + ".");

Using the Scanner class in Java to get specific digits of an integer [duplicate]

This question already has answers here:
How to get the separate digits of an int number?
(32 answers)
Closed 6 years ago.
I just started learning Java (two months and counting), and I still have lots of questions and a whole lot to learn. Right now I want to use the Scanner class to "divide" an integer into its digits. I'll explain myself better with an example:
I request the user to type a four-digit integer, say 8919. What I want to do is to use the Scanner class to divide that integer and to assign each one of its digits to a variable; i.e. a = 8, b = 9, c = 1 and d = 9.
I positively know that it can be done and that the Scanner class is the way to go. I just don't know how to properly use it. Can a noob in need get some help here? Thanks!
EDIT:The suggestion that has been made does not match my specific question. In that thread the class Scanner is not used to separate the integer into digits. I specified i wanted to use the Scannerclass because many different methods used there are still way beyond my level. Anyway, there are lots of interesting ideas in that thread that i hope i will be able to use later, so thanks anyway.
You can use a delimiter with the scanner. You can use an empty string as delimiter for this case.
String input = "8919";
Scanner s = new Scanner(input).useDelimiter("");
a = s.nextInt();
b = s.nextInt();
c = s.nextInt();
d = s.nextInt();
s.close();
you should read the integer as whole number and store it in a variable. after you stored it you can split it up. other way is so store it as string and then split the string. what you should choose depends on what youwant to do with it afterwards
Try this:
import java.util.Scanner;
public class ScannerToTest {
public static void main(String[] args) {
int a,b,c,d;
System.out.print("Please enter a 4 digit number : ");
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
String numberToString = String.valueOf(number);
if(numberToString.length() == 4) {
String numberArray [] = numberToString.split("");
a = Integer.parseInt(numberArray[1]);
b = Integer.parseInt(numberArray[2]);
c = Integer.parseInt(numberArray[3]);
d = Integer.parseInt(numberArray[4]);
System.out.println("Value of a is : " + a);
System.out.println("Value of b is : " + b);
System.out.println("Value of c is : " + c);
System.out.println("Value of d is : " + d);
}else {
System.out.println("Numbers beyond 4 digits are disallowed!");
}
}
}

How to convert JOptionPane.showInputDialog to int to use in programme?

So basically have an Array and am using the Joption input system so the user has to input a int between 1 and 3. Basically how do I use this int I to divide the number of objects in my array? Also not necessary but it would help if you could advise me how do I stop people inputting a number less than 1 and greater than 5.
Rain[] drops = new Rain [3000]; // WANT TO DIVIDE INT INTO ARRAY
import javax.swing.*;
void setup() {
noCursor();
JOptionPane.showInputDialog( "Please enter a number between one and three","2");
}
So can I use the output from this to adjust the number of objects created by my array ?
Java cannot convert between strings and number by itself, you have to use specific functions, just use:
int ans = Integer.parseInt(JOptionPane.showInputDialog(...))
For your other question you may wanna do something like the following:
boolean inputAccepted = false;
while(!inputAccepted) {
try {
int answer = Integer.parseInt(JOption....
// do some other validation checks
if (answer < 1 || answer > 3) {
// tell them it's still a bad number
} else {
// a good value
inputAccepted = true;
}
} catch(NumberFormatException e) {
// input is bad. popup something
// some communication
// saying what you expect the user to enter.
}
... do stuff with good input value
Since you tagged this with processing, I'll assume you're using the Processing language.
Processing has an int() function that converts from a String to an int.
float f = 65.0;
int i = int(f);
println(f + " : " + i); // Prints "65.0 : 65"
char c = 'E';
i = int(c);
println(c + " : " + i); // Prints "E : 69"
More info on this and related functions can be found in the Processing reference.
You could try this
String ans_s = JOptionPane.showInputDialog( "Please enter a number between one and three","2");
int ans = Integer.parseInt(ans_s);
Please wrap this in try{ }catch(NumberFormatException nfe){}

How to multiply a set number and a user input number in Java?

I want to make a calculator that greets the user by name then multiplies one number that the user enters and one number that I set. For instance, if the user enters the number 10, I want my code to take the 10 and multiply it by 6.
Here's what I have so far:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args){
Scanner userInputScanner = new Scanner(System.in);
System.out.println ("Hello, my name is Bob. What is your name?");
String userName = userInputScanner.nextLine();
System.out.println ("Hello" + userName + "how many steps do you take in a ten second interval?");
}
}
This part is working, but I can't figure out what to do next.
If you take a look at the Javadoc for Scanner, there is a nextInt() method, which will do the same thing as nextLine() but return an integer. You can set that to an integer variable.
To multiply two variables, it's as simple as
int z = x * y;
Then print out the result, or to simplify it, you could just print out the calculation without setting it equal to a variable
System.out.println("The awnser is: " + (scanner.nextInt() * 6));
Keep in mind, this are integers, you could also use doubles or floats, or even longs. See the scanner documentation for all the methods you can use to get input.
Use nextInt() (or nextDouble() or ...) method to read the number the user will input.
int userNumber = (userInputScanner.hasNext()) ? userInputScanner.nextInt() : 0;
System.out.println("6 * " + userNumber + " = " + (6 * userNumber));

How to use charat(index) to count the number of specified characters when comparing strings

Hi I am still new when it comes to programming so I was wondering how to use the charat(index) method to compare characters in two strings each are 4 characters long.
I am essentially making a random number guessing game where the user has 5 chances to guess the 4 digit number, and each time I am supposed to return a hint in the form "nAkB". "nA" is supposed to be the number of matching characters in the right index and "kB" is the number matching characters in essentially the wrong index like "2A1B". Here is an example of what the output should look like.
You have 5 chances. Input your guess:1234
Hint:2A1B
You have 4 chances. Input your guess:2136
Hint:0A4B
You have 3 chances. Input your guess:1263
You win!
This is what I get
Enter your guess you have 5 chances left 1289
1234
hint 213A 196B hint 425A 396B hint 637A 600B hint 849A 808B
Enter your guess you have 4 chances left 1289
1289
hint 213A 196B hint 425A 396B hint 637A 600B hint 849A 808B hint 213A 196B hint 425A 396B hint 637A 600B hint 849A 808B
Enter your guess you have 3 chances left 1289
also for some reason the condition I set for winning the game is only accepted during the first iteration
The problem with the hints is in the getHint() method the problem with my win condition is in the loop in the runGame() method I really really appreciate any help thank you for your time.
below is my code
runGame()
public static String generateRandomNumber()
{
//Creates a string array of numbers that will be used to generate random numbers
String random[]={"0","1","2","3","4","5","6","7","8","9"};
//This takes the array and shuffles it around in order to make a random number
Collections.shuffle(Arrays.asList(random));
//This concatenates the fiers fouri ndex's of the array and reuturns them as a single string
return random[0]+random[1]+random[2]+random[3];
}
public static String getHint(String answer,String guess)
{
//This is the inititialization of the hint string no kidding??
String hint="";
int i, j;
//This nested for loop takes the guess by the user and the answer and compares the postions and numbers
int G=0;
int A=0;
for(i=0;i<4;i++){
for(j=0;j<4;j++){
//This looks at the index's of the players guess
G+=guess.charAt(i);
//This looks at the index's of the answer
A+=answer.charAt(j);
//If G=A and i=j then they should increment the value of A and tell the player the number of numbers in the right spot
if (G==A &&i==j) {
A++;
}
//Though if only G=A then it should increment the G which will the player the number of right numbers in the wrong postions
else if (G==A ) {G++;}
// System.out.println("inner loop hint>" + hint + "<");
} // end inner j loop
hint+=String.valueOf("hint "+A+"A "+G+"B "); // += ????
//System.out.println("outer loop hint>" + hint + "<");
} // end outer i loop
return hint;
}
public static void runGame()
{
Scanner k=new Scanner(System.in);
boolean control=true;
String answer=generateRandomNumber();
String guess="";
int i;
System.out.println("In this game you will have 5 chances to guess the the 4 digit number "+
"You will recieve a hint based on the numbers you have entered nA n meaning number of right digits in the right place "+
"and kB k meaning number of digits that are right but placed wrong good luck.");
String hint="";
//System.out.println("Enter your answer you have 5 chances"+answer);
//String hint = getHint(answer,guess);
for(i=5;i>0&&control;i--) {
System.out.println("Enter your guess you have "+(i)+" chances left "+answer);
guess+=k.nextLine();
hint+=getHint(answer,guess);
if(answer.equals(guess))
control=false;
if(control==false) {
System.out.println("You Win!");
}
else if(answer!=guess)
control=true;
if(control==true&&i>1) {
System.out.println(hint);
}
} // end loop
if (control==true) {
System.out.println("Sorry you lose the answer was "+answer);
}
} // end runGame()
} // end class

Categories