Java picks any random number as the correct answer - java

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) + ".");

Related

Give a random age number between 0-9 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.

How to create a method that repeats a function?

Hello everyone I am new to the site and this is my first question from my Java programming class.
I have to create a program that asks a math question and tells the user if he is right or wrong, but the requirements also state that I need to create a method that generates a new question if the first question is correct, so when the computer asks what is 5 times 5 and the user inputs 25 the method should generate two new random numbers and ask the user for a result.
This is my code so far. I don't expect the answers as this is a school assignment but if anyone could give a direction it would be greatly appreciated it as this is my first java college course.
import java.security.SecureRandom; //program uses class SecureRandom
import java.util.Scanner; //program uses class Scanner
public class CAI
{
public static void main(String[] args)
{
System.out.println("Alex - Assignment 4\n");
//create Scanner for input from command window
Scanner input = new Scanner(System.in);
//randomNumbers object will produce secure random numbers
SecureRandom randomNumbers = new SecureRandom();
//generates two random numbers from 1 to 9 excluding 0
int random1 = 1+ randomNumbers.nextInt(9);
int random2 = 1+ randomNumbers.nextInt(9);
int answer; // declares answer from user
//calculates real result of first integer times second integer
int result = (random1 * random2);
//display generated integers
System.out.printf("What is %d times %d?\n",random1, random2);
do
{
answer = input.nextInt(); //keeps taking answer from user if wrong
if(answer == result) //if correct answer then print very good!
System.out.println("Very Good!");
else // if wrong answer then print no please try again
System.out.println("No. Please try again");
}
while (answer != result);
}
I think you have the basic way that your loop statements work mixed up. A do statement is going to execute its block of code once and wont inherently loop on its own. A while loop will repeat until you tell it to stop. So without telling you exactly how to structure your assignment ;) you should look at those two things. But your code does compile and does do one run through of what you want it to do. So this means that the problem you have is in the logic aspect of your code. This means that the computer doesn't understand based on the structure of your code when to execute the sections of your code.
So my advice is to try writing it out in plain English first (pseudocode) that way you can work out how the logic of your program should run and then translate it into code. Sometimes just saying "I want x to happen when y. But I only want this to happen if event z has happened." can help you understand logical how something has to work.
Best of luck
You could add a while loop before the generation of the random numbers that would repeat until answer== "exit". Something along those lines would work fine
You should put a break; statement in the bottom else loop and put everything from your public static void declaration in an "infinite" for loop. When the user inputs an incorrect answer, the program will go to the else loop and break. Otherwise, it will keep on repeating in the "infinite" for loop. Here is a sample code showing what you could do.
import java.security.SecureRandom; //program uses class SecureRandom
import java.util.Scanner; //program uses class Scanner
public class CAI
{
public static void main(String[] args)
{
boolean loopTest = false;
while (loopTest= true)
{
System.out.println("Alex - Assignment 4\n");
//create Scanner for input from command window
Scanner input = new Scanner(System.in);
//randomNumbers object will produce secure random numbers
SecureRandom randomNumbers = new SecureRandom();
//generates two random numbers from 1 to 9 excluding 0
int random1 = 1+ randomNumbers.nextInt(9);
int random2 = 1+ randomNumbers.nextInt(9);
int answer; // declares answer from the user
//calculates real result of first integer times second integer
int result = (random1 * random2);
//display generated integers
System.out.printf("What is %d times %d?\n",random1, random2);
do
{
answer = input.nextInt(); //keeps taking answer from user if wrong
if(answer == result) //if correct answer then print very good!
System.out.println("Very Good!");
else // if wrong answer then print no please try again
System.out.println("No. Please try again");
break;
}
while (answer != result);
}
}
}
*Note that the last } was not included in your program.

Guessing Game Help :)

Ok, so my computer teacher has asked us to make a simple game that asks the user to guess a radomly generated number, but I want to take it one step further and make it so that it display error messages when the user tries certain things. The problem here is that I am new to booleans and well, I am having a bit of trouble using java.util.Scanner and booleans. So, if anyone could take a quick look at this I would appreciate it.
import java.util.Scanner;
import java.util.Random;
public class MoreGuessing{
//Instantiation
Scanner reader = new Scanner(System.in);
Random number = new Random();
//Variables
int randomnumber = number.nextInt(10) + 1;
int cntr = 1;
static String decimalguessed;
String error1 = "Error001: Decimal found, please enter a whole number between 1-10." + "\n" + "Program terminated......";//Decimal portion error.
String error2 = "Please enter a positive number." + "\n" + "Program terminated......"; //Negative number error.
String error3 = "Unknown character entered." + "\n" + "Program terminated......"; //Unknown character error.
//Verifier
public static boolean verifyLetters() {
if (decimalguessed.matches("[a-zA-Z]+")){
return true;
}else{
return false;
}
}
public static void main(String [] args){
//Input and display
System.out.print("Please enter a whole number between 1-10: ");
decimalguessed = reader.nextLine();
//Process and Errors
while (decimalguessed != randomnumber) {
if (verifyLetters() != false){
System.out.println(error3);
System.exit(1);}
if (decimalguessed % 1 != 0) {
System.out.println(error1);
System.exit(1);}
if (decimalguessed < 0) {
System.out.println(error2);
System.exit(1);}
if (randomnumber != decimalguessed){
System.out.println("You've lost, please make another attempt.");}
System.out.print("Please enter a whole number between 1-10: ");
decimalguessed = reader.nextDouble();
cntr++;
}
if (cntr == 1) {System.out.println("Congratulations! You've guessed the number on your first attempt!");;
}
else {System.out.println("Congratulations! You've guessed the number, it took you " + cntr + " tries");}
}
}
You need to parse your input. decimalguessed is a string, and so you can't do comparisons like decimalguessed % 1.
You can convert it to an integer like this:
int guess = 0;
try {
guess = Integer.parseInt(decimalguessed);
} catch (NumberFormatException e) {
System.out.println("Your guess was not an integer: " + e.getMessage());
System.exit(1);
}
This will handle both cases where decimalguessed contains letters, and where it contains decimal points/fractions. decimalguessed is still a string, but guess now contains the integer version of it, so you can compare it to randomnumber properly. (Your loop would have never exited before, because a string is never == an integer)
Some other notes:
You should never have:
if (condition) {
return true;
} else {
return false;
}
This can always be simply replaced with
return condition;
It feels like you're very new to this. Welcome to programming!
So first, in Java generally you're not going to have all of that instantiation and variables stuff outside of your main function, unless you're going to make everything static. I would move all of that into your main function, un-static the decimalguessed variable and setup your verifyLetters function to take an argument of String decimalguessed. It may also be wise to check if the value is a number, rather than seeing if it is not a letter. There a lot of non-number, non-letter characters.
Once you've figured out that the guess is a number, you need to tell java it is one (cast it) to a decimal, then do you further comparisons against that decimal.
Darth Android also makes some good points, especially about booleans. You should never have the only result of an if/else be to return a boolean, just return the boolean. Also avoid comparisons to true/false, just do the if on the function/variable alone, or negate it with an '!' to check for false.
Good luck!

Comparing an array to two static values

So I am just doing something simple. I made a simple Java program where you enter your guess for what the roll will be which is stored in an array and then compared to two numbers generated randomly. So my question is how would I do the comparison of the array against the two number without referencing the exact index (i.e. not array[0]=number[1])? I am doing this mostly to figure out how array work. Also why is the else erroring?
public static void main (String [] args){
java.util.Scanner input = new java.util.Scanner(System.in);
int [] guess= new int [2];
System.out.print("Enter " + guess.length + " values: ");
for (int i=0; i<guess.length;i++)
guess[i] = input.nextInt();
method(guess);
}
public static String method(int [] that){
int number1 = (int)(Math.random() * 6);
int number2 = (int)(Math.random() * 6);
for (int i =0;i<that.length;i++){
if(that[i]==number1 and that[i]+1==number2)
{
return "You got it";
}
else
{
return "try again";
}//end else
} //end for
}//end method
You cannot write and like that , if you want to AND two conditions write &&. Also in your if condition I think you mean to increment your index that[i+1]==number2 , you were incrementing the random number itself. So your if condition would look like:-
if(that[i]==number1 && that[i+1]==number2)
{
return "You got it";
}
else{
..
}
Also want to add that you output You got it or try again will not be visible to user, since you are just calling the method method(guess); from main() which returns a String but does not do anything with returned String. You have to write it like this to make the ouput visible on console.
System.out.println(method(guess));
You can check whether the array contains the element or not like this
Arrays.asList(that).contains(number1)
It will return true if the array contains the element else as false
if you want comparison of the array against the two number without referencing the exact index then the first thing that you can do is use enhance for loop to avoid indexing of array like this
for(int number: that){
// do your comparison while iterating numbers in that(array) as "number"
}

Get user to input integers

I want to make a program which keeps prompting the user to input integers(from CUI) until it receives a 'X' or 'x' from the user.
The program then prints out the maximum number, minimum number and average value of the input numbers.
I did manage to get the user to input numbers until someone types 'X', but I can't seem to get it to stop if someone types 'x' and the second bit.
This is the code that I have managed to work out:
Scanner in = new Scanner(System.in);
System.out.println("Enter a number")
while(!in.hasNext("X") && !in.hasNext("x"))
s = in.next().charAt(0);
System.out.println("This is the end of the numbers");
Any hints on how I proceed further?
You will need to do something like this:
Scanner in = new Scanner(System.in);
System.out.println("Enter a number")
while(!(in.hasNext("X") || in.hasNext("x")))
s = in.next().charAt(0);
System.out.println("This is the end of the numbers");
Whenever you use while loop you have to use the {} in case the arguments in the while block are more than 1 line, but if they are just of a line then you can just go on without using the {}.
But the problem, you had I suppose is the use of && instead of ||. What the && (AND) operator does is execute if both the statements are true but a || (OR) Operator works if any of the conditions are true.
If you say while(!in.hasNext("X") && !in.hasNext("x")) it makes no sense as the user input is not both at the same time, but instead if you usewhile(!in.hasNext("X") || !in.hasNext("x"))` it makes sense. Understood?
And about sorry, im really new at this. but ive added the code No problem, you need not say sorry but there are a few things to keep in mind before asking a question. You must read this https://stackoverflow.com/help/how-to-ask and yeah one more thing, you should use proper English Grammar while framing your question.
Last of all, about how to calculate the average..., for that what you need to do is store all the input variables into an array and then take out the mean of that or alternatively you could think about it and code something up yourself. Like to take out mean, you could make a variable sum and then keep adding the integers the user enters and also keep a variable count which will keep the count of the number of integers entered and then at last you could divide both of them to have your answer
Update: For checking the minimum and the maximum, what you can do is make 2 new variables like int min=0, max=0; and when the user enters a new variable you can check
//Note you have to change the "userinput" to the actual user input
if(min>userinput){
min=userinput;
}
and
if(max<userinput){
max=userinput;
}
Note: At stackoverflow we are there to help you out with the problems you are facing BUT you cannot exploit this. You cannot just post your homework here. But if you are trying to code something up and are stuck at it and cannot find a answer at google/stackoverflow then you can ask a new question and in that you need to tell what all you have already tried. Welcome to SO! :D Hope you have a nice time here
This would fit your needs:
public void readNumbers() {
// The list of numbers that we read
List<Integer> numbers = new ArrayList<>();
// The scanner for the systems standard input stream
Scanner scanner = new Scanner(System.in);
// As long as there a tokens...
while (scanner.hasNext()) {
if (scanner.hasNextInt()) { // ...check if the next token is an integer
// Get the token converted to an integer and store it in the list
numbers.add(scanner.nextInt());
} else if (scanner.hasNext("X") || scanner.hasNext("x")) { // ...check if 'X' or 'x' has been entered
break; // Leave the loop
}
}
// Close the scanner to avoid resource leaks
scanner.close();
// If the list has no elements we can return
if (numbers.isEmpty()) {
System.out.println("No numbers were entered.");
return;
}
// The following is only executed if the list is not empty/
// Sort the list ascending
Collections.sort(numbers);
// Calculate the average
double average = 0;
for (int num : numbers) {
average += num;
}
average /= numbers.size();
// Print the first number
System.out.println("Minimum number: " + numbers.get(0));
// Print the last number
System.out.println("Maximum number: " + numbers.get(numbers.size() - 1));
// Print the average
System.out.println("Average: " + average);
}

Categories