I have a program that will help the user to learn a multiplication table and then show results of right/wrong answers. The first step is to simply ask the user for which multiplication table it want to work on (1-9). And then the user will get a random sequence of number multiplied by the chosen multiplication table. If the user answers correctly then that number won't be shown again, but if incorrectly then it will be shown until the correct answer is made.
One scenario could be that the user chooses "3", and it will then be displayed in a random sequence such as (3x7 =, 3x1 =, 3x9 =...). And the user will answer after each "=". Right now, I can only print it all in ascending order, should I use Random multiplied with the chosen table in a while loop instead?.
My second issue, is how I can ask the incorrectly answered numbers again, until correctly answered? Am I right to think that a for loop isn't the best choice in this case?
Here is my code so far:
public class Multiplication {
public static void main (String[] args) {
Scanner inread = new Scanner (System.in);
int answer;
System.out.println("Choose multiplication table (1-9)");
int num1= inread.nextInt();
for (int i=1; i<11; i++) {
System.out.println("Write answer after = ");
System.out.println(num1 + " x " + (i) + " = ");
answer=inread.nextInt();
if (answer == (num1 * i) ) {
System.out.println("Correct answer");
// Do not show that number again
}
else {
System.err.println("Wrong answer");
//Show this number again.
}
}
}
}
New code after int num1 = inread.nextInt();
unanswered.add(1);
unanswered.add(2);
unanswered.add(3);
unanswered.add(4);
unanswered.add(5);
unanswered.add(6);
unanswered.add(7);
unanswered.add(8);
unanswered.add(9);
unanswered.add(10);
Collections.shuffle(unanswered);
while (!unanswered.isEmpty()) {
System.out.println(num1 + "*" + "unanswered" + " = "); //?
answer = inread.nextInt();
if (answer == (num1 * unanswered)) { //?
unanswered.remove(unanswered); //?
}
}
So, I think this is almost the way you suggested? However I'm sure I could add the numbers in a more beautiful way. I am used to looping through lists with a for loop in order to then use the counter to display the list. So where I putted a "?" is because I am not sure how to specify where in the list I am trying, for example to remove a number.
Or should I have the while loop, inside the for loop that I originally had? So that I could use the (i) in the for loop to specify where in the list I will display and perhaps remove?
A good question and a good start on the coding.
One way of asking for input until all the multiplication questions have been solved would be a while loop.
As #Easton pointed out an ArrayList to store the numbers and Collections.shuffle will help with the setup. By creating the ArrayList ahead of time then using a while loop until it is empty to prompt the user to keep answering.
EDIT
Heading in the right direction. To simplify the creation of unanswered numbers make use of the for loop, Something like: for(i=1, i<=10,i++) then add(i) to unanswered.
In the while loop, grab the first index: unanswered[0] and set that to num1 then if the answer is correct, remove it (as you have now). If not use Collections.rotate on unanswered by 1. Which will move the unanswered question to the end of the array for another attempt later.
Bellow you can find a solution for your problem with Hash Tables, you can do modifications to it so that the user can not type a number larger than 9 or smaller than 0 but this should work for your purpose:
import java.util.Random;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Multiplication {
public static void main (String[] args) {
Map<Integer, Integer> list = new HashMap<Integer, Integer>();
Scanner inread = new Scanner (System.in);
int answer;
System.out.println("Choose multiplication table (1-9)");
int num1= inread.nextInt();
for (int i = 1; i<10; i++) {
list.put(i, num1*i);
}
System.out.println(list);
while (!list.isEmpty()) {
System.out.println("Write answer after = ");
Random generator = new Random();
Object[] keys = list.keySet().toArray();
Object randomValue = keys[generator.nextInt(keys.length)];
int next = (Integer) randomValue;
System.out.println(num1 + " x " + (next) + " = ");
answer=inread.nextInt();
if (answer == (num1 * next)) {
System.out.println("Correct answer");
list.remove(next);
} else {
System.err.println("Wrong answer");
}
}
System.out.println("Congrats!!!");
}
}
Related
I'm trying to learn (self-taught) Java by reading Big Java, Late Objects from by Cay Horstmann. I'm using repl.it to write my code (if you may want to look it up, it's public)
A selfcheck question of Chapter 4 Loops is:
How can you overcome the problem of when the user doesn't provide any input in the algorithm of section 4.7.5 (titled Maximum and Minimum) and the WHILE loop just terminates the program for this reason ?
They basically ask to rewrite the code so it solves this problem.
The information of section 4.7.5 you need to solve this problem: To compute the largest value in a sequence, keep a variable that stores the largest element that you have encountered, and update it when you find a larger one.
(This algorithm requires that there is at least one input.)
double largest = in.nextDouble();
while (in.hasNextDouble())
{
double input = in.nextDouble();
if (input > largest)
{
largest = input;
}
}
This is what the book suggests as the answer to this problem (but I disagree):
One solution is to do all input in the loop and introduce a Boolean variable that checks whether the loop is entered for the first time.
double input = 0;
boolean first = true;
while (in.hasNextDouble())
{
double previous = input;
input = in.nextDouble();
if (first) { first = false; }
else if (input == previous) { System.out.println("Duplicate input"); }
}
I don't fully understand the first sentence. And I disagree this as a solution for the problem because (as far as I can tell) it tests whether the input has been entered before, instead of testing if any sort of user input has been provided..
I tried to merge those two sections of code together but I can't seem to make it work. Or more specific: figure out how to build it. What variables / loops do I need? In which order do I write this?
I've made a flowchart in Visio of the first section of code but have no clue how to continue.
This is what I've written so far:
import java.util.Scanner;
class Main {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the number: ");
double largest = 0;
while (input.hasNextDouble())
{
double value = input.nextDouble();
if (value > largest)
{
largest = value;
System.out.println("The largest input till now is: " + largest);
}
}
Can someone:
Ask me questions which help me to solve this question? I.e. Tell me what tools I need (WHILE, FOR etc.)
Provide a solution in text which I can hopefully transform in code
Or write the code for me (I haven't learned arrays yet, so please solve it without)
Thanks in advance,
So I worked on this for a bit and I think I have something close to what you're looking for using a do while loop.
This code accepts user input first, then checks it's value in comparison to the last input and return either "Input a higher value", "Duplicate number found", or it sets the last number entered to the current number.
I hope this helps you get your code to where you'd like it to be! I'm still new, so I apologize if this is not entirely optimized.
Also, I have not added a way to exit the loop, so you may want to add a check on each iteration to see if the user would like to continue.
public static void main(String[] args) {
double userInput = 0;
double prevNum = 0;
boolean hasValue = false;
boolean exitCode = false;
do {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number: ");
userInput = sc.nextDouble();
do {
if (userInput<prevNum) {
System.out.println("Please enter a number higher than " + prevNum);
hasValue=true;
}
else if (userInput==prevNum) {
System.out.println("Duplicate input detected.");
hasValue=true;
}
else {
prevNum = userInput;
hasValue = true;
}
}
while(hasValue==false);
System.out.println(prevNum);
System.out.println(userInput);
}
while(exitCode==false);
}
If you want compute if the number entered is the largest entered from the beginning but declare it at the largest if it's the first iteration then do this :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean flag = true;
double largest = 0;
System.out.println("Enter the number: ");
while (input.hasNextDouble()){
double value = input.nextDouble();
if (flag) {
flag = false;
largest = value;
}
else if (value > largest) largest = value;
System.out.println("The largest input till now is: " + largest);
System.out.println("Enter a new number: ");
}
}
Write a program that will help an elementary school student learn multiplication. Use a SecureRandom object to produce two positive one-digit integers (you will need to look up how to do this). The program should then prompt the user with a question, such as
How much is 6 times 7? The student then inputs the answer. Next, the program checks the student’s answer. If it’s correct, display the message "Very good!" and ask another multiplication question. If the answer is wrong, display the message "No. Please try again.>again." and let the student try the same question repeatedly until the student finally gets it right.
A separate method should be used to generate each new question. This method should be called once when the application begins execution and each time the user answers the question correctly.
My question is do you have to make an if else statement == my public static mathQuestion and then have it output? I am lost on what to do after making the SecureRandom. I'm still new to Java.
I've tried doing an if-else statements after missing the question more than once but it has be done in a method.
import java.security.SecureRandom;
import java.util.;
public class h_p1 {
static SecureRandom rand = new SecureRandom();
static Scanner sc = new Scanner (System.in);
public static int mathQuestion() {
int n1 = rand.nextint(9) + 1;
int n2 = rand.nextint(9) + 1;
System.out.print("What is" + n1 + "x" + n2"?");
return r1 * r2;
}
}
}
You need to do the following:
Prompt for the answer
Check the answer by using an if statement.
If the answer is incorrect, prompt again.
If it correct, generate another question.
You will need to use loops in this situation. It could take on
different designs but you would need one for the reprompting and one for
the new question.
Imo, the best way to do the reprompting is to use a while statement with a settable boolean value. If they get the answer correct, set the boolean to false
otherwise, keep prompting while true. You could also use a for loop if you want to limit the number of guesses.
public class Quiz {
public static void main(String[] args) {
generateRandomNumbers();
}
public static void generateRandomNumbers() {
SecureRandom rand = new SecureRandom();
Scanner sc = new Scanner (System.in);
int n1 = rand.nextInt(9) + 1;
int n2 = rand.nextInt(9) + 1;
generateQuestion(n1,n2);
}
public static void generateQuestion(int n1, int n2) {
Scanner sc = new Scanner (System.in);
System.out.print("What is " + n1 + " x " + n2+ " ?");
int typedAnswer = sc.nextInt();
if(typedAnswer == (n1*n2)) {
System.out.println("Correct Answer");
generateRandomNumbers();
}else {
System.out.println("Wrong Answer");
generateQuestion(n1,n2);
}
}
}
The simplest answer to this question that I could have thought for:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
do {
SecureRandom secureRandom = new SecureRandom();
int numbOne = secureRandom.nextInt(9) + 1;
int numbTwo = secureRandom.nextInt(9) + 1;
int prod = numbOne * numbTwo;
int response;
do {
System.out.println(MessageFormat.format("What is the product of {0} and {1}", numbOne, numbTwo));
response = scanner.nextInt();
if (response != prod) {
System.out.println("Incorrect answer! Try again");
}
} while (response != prod);
System.out.println("Correct answer");
System.out.println("Do you want to practice with another question (Y/N)?");
} while (scanner.next().equalsIgnoreCase("Y"));
}
It uses 2 do-while loops. The outer loop controls the number of times a question should be asked depending on user's choice and the inner loop checks the correctness of the answer given by the user.
I have code that is supposed to guess the user's number and it will narrow its search based on user input. The only issue is that within the while loop, the conditionals are not working with .equals. Instead, it skips to the else even when I type "less than". This is my code below, I am new to java so I might have made a mistake.
package reversedHiLo;
//Import utility
import java.util.*;
public class ReversedHiLo
{
public static void main(String[] args)
{
//create scanner class
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to reverse number guessing game, pick a number between 1 and 100 and type it below:");
int answer = sc.nextInt();
//Create the first guess
int guess = 1 + (int)(100*Math.random());
//Create an array that stores the range of the player's number
int[] range = new int[] {1,100};
//While loop that guesses the number
while(guess != answer)
{
System.out.println("Is your number greater than or less than " + guess + "?" + Arrays.toString(range));
String response = sc.next();
sc.nextLine();
//Conditionals to set the range of the guess
if(response.equals("less than"))
{
range[1] = guess;
}
else
{
range[0] = guess;
}
//Guess a new number based on the range
guess = range[0] + (int)((range[1] - range[0]) * Math.random());
}
//Final print
System.out.println("Your number was " + answer + ".\nThe computer's guess was: " + guess);
//Close scanner
sc.close();
}
}
There are two places where there is a problem:
The first one sc.nextInt() method - which only reads the int
value by keeps current reading buffer on the same line. So to
ignore/skip everything what is after int on the input line (which is
probably \n or \r\n if you only enter the number) you have to
use sc.nextLine().
The second one is sc.next() method - which
only reads first token(or simply word) from your line. That is
probably why you only get "less" value assigned to response
and that will never be .equals to "less than". So you will
have to replace sc.next() one with sc.nextLine() and remove
unnecessary sc.nextLine() from the next line.
Hope this should be clear now and you have a better understanding of what happens when you call these function. If not then I strongly advise you to have a look into Scanner class, read JavaDocs on write multiple tests around it to get a better understanding of what is going on.
If my explanation is still not clear have a look at the code I have modified for you below:
public static void main(String[] args)
{
//create scanner class
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to reverse number guessing game, pick a number between 1 and 100 and type it below:");
int answer = sc.nextInt();
sc.nextLine(); // This one is necessary to ignore everything on the same line as your number was typed in
//Create the first guess
int guess = 1 + (int)(100*Math.random());
//Create an array that stores the range of the player's number
int[] range = new int[] {1,100};
//While loop that guesses the number
while(guess != answer)
{
System.out.println("Is your number greater than or less than " + guess + "?" + Arrays.toString(range));
String response = sc.nextLine(); // This reads the whole input line
//Conditionals to set the range of the guess
if(response.equals("less than"))
{
range[1] = guess;
}
else
{
range[0] = guess;
}
//Guess a new number based on the range
guess = range[0] + (int)((range[1] - range[0]) * Math.random());
}
//Final print
System.out.println("Your number was " + answer + ".\nThe computer's guess was: " + guess);
//Close scanner
sc.close();
}
import java.io.IOException;
import java.util.*;
public class task2 {
public static void main (String [] args) throws IOException {
int a;
int b;
String y;
String x;
Scanner input = new Scanner(System.in);
System.out.println("Please enter number A:");
a = input.nextInt();
System.out.println("\nPlease enter number B:");
b = input.nextInt();
System.out.println("\nLastly, enter A if you wish it to be the dividor and/or subtractor, or if you wish it to be B, please enter B :"); //stops running properly here...
y=input.nextLine();
System.out.println("\nWhat would you like to do? Multiply (*), Divide (/), Subtract (-) or Add (+)? Please enter the symbol of which process you would like to have completed:");
x=input.nextLine();
if (y=="b"+"B") {
if (x=="*") {
System.out.println("\nThe product of these numbers is:" + a*b);}
else
if (x=="/") {
System.out.println("\nThe quotient of these numbers is:" + a/b);}
else
if (x=="+") {
System.out.println("\nThe sum of these numbers is:" + a+b);}
else
if (x=="-") {
System.out.println("\nThe difference of these numbers is:" + (a-b));}}
else
if (y=="a"+"A"){
if (x=="*") {
System.out.println("\nThe product of these numbers is:" + b*a);}
else
if (x=="/") {
System.out.println("\nThe quotient of these numbers is:" + b/a);}
else
if (x=="+") {
System.out.println("\nThe sum of these numbers is:" + b+a);}
else
if (x=="-") {
System.out.println("\nThe difference of these numbers is:" + (b-a));}}
}
}
I dont know why it stops but where indicated by "//" the program suddenly stops letting me input information and does not continue the processes i want it to do. I wont bother explaining the program in detial because i believe it is fairly obvious from the code itself what i want to do.
Thanks in adavance for all the help!
Use
input.next();
not
input.nextLine();
Since nextLine() skips over the input and sets the scanner to the NEXT line and returns a string representation of what was skipped. Your program throws the errow because the NEXT line does not exist
Your string comparisons are incorrect--you need to compare strings using the equals() method, like x.equals("*") in order for any of them to work. (This is a pretty common mistake, so even though it's homework, freebie :)
There's no loop, so it'll stop after the first time "through"; this may or may not be what you want.
Hey Guys. thanx for the major help regarding my obstacles.
What my problem this time is, how can I sort the array list that is provided in my code basically dont know WhatI need to add in the provied code below, just to simplyfive it I got 3 arraylist that i want to make them into one arraylist, so they can be sorted in amont of guesses and tries( if 2 players have the same guesses then the time should determine) .
Pretty hard to explain it but i tried my best.............the best thing is to run it then you will figure it what whats the issue is?
Here is the code:
import java.util.*;
import java.util.Scanner.*;
import java.util.ArrayList.*;
public class Main {
public static String ToString(int a, double b, String c)
{
String aS = Integer.toString(a);
String bS = Double.toString(b);
String scoreList = (aS + "\t\t" + bS + "\t\t" + c);
return scoreList;
}
private static void start() {
int tries = 0 ;
int guess = -1;
String name ;
String quit = "quit";
String y = "yes";
String n = "no";
String currentGuess;
String another = ("y") ;
Scanner input = new Scanner (System.in);
ArrayList<String> scores = new ArrayList<String>();
boolean a=false;
do {
a=false;
int answer = (int) (Math.random() * 1000 + 1) ;
System.out.println( " Welcome to Guessing Game " ) ;
System.out.print("Please enter a number between 1 and 1000 : ");
currentGuess = input.nextLine();
long startTime = System.currentTimeMillis();
do
{
if (currentGuess.equalsIgnoreCase(quit))
{
System.out.println("Leaving Us So Soon?");
System.exit(0);
}
try {
guess = Integer.parseInt(currentGuess);
} catch (NumberFormatException nfe)
{
System.out.println(" Dude Can You Read, Only Digits ");
currentGuess = input.nextLine();
}
if (guess < 1 || guess > 1000)
{
System.out.println("Stupid Guess I Wont Count That.");
currentGuess = input.nextLine();
}
if (guess < answer )
{
System.out.println("too low "+answer);
currentGuess = input.nextLine();
tries++;
}
else if(guess > answer )
{
System.out.println("too high "+answer);
currentGuess = input.nextLine();
tries++;
}
else if (guess == answer)
{
//stop stop watch
long endTime = System.currentTimeMillis();
//calculate game time
long gameTime = endTime - startTime;
System.out.println("You Rock Dude, Good Job!");
System.out.println("You guessed " + tries + " times in " + (int)(gameTime/1000) + " seconds.");
System.out.println("Please enter your name.");
name = input.nextLine();
//create score object
String TOString =ToString(tries, gameTime, name);
//add score to arrayList
scores.add(TOString);
boolean s = false ;
while (s==false)
{
System.out.print("Want to go again?(y/n).....");
currentGuess = input.nextLine();
if (currentGuess.matches("y"))
{
System.out.println("HighScore: \nGuess \t Time in milisec\tName");
//print out high score list
for (int i = 0;i < scores.size(); i++)
{
System.out.println(scores.get(i));
}
// Main.start
s=true;
}
//if user doesn't want to play again
if (currentGuess.matches("n"))
{
System.out.println("HighScore:\nGuess \tTime in milisec\tName");
//print out high score list
for (int i = 0;i < scores.size(); i++)
{
System.out.println(scores.get(i));
}
System.out.println("Thanx For Playing.");
a=true;
s=true;
System.exit(0);
}
}
}
} while (guess != answer);
}while(a==false);
}
public static void main(String[] args) {
// ArrayList<Score> scores = new ArrayList<Score>();
Main.start();
}
}
Use Collections.sort() and make sure your class implements Comparable or use something like this:
Collections.sort(list, new Comparator<T>() {
public int compare(T o1, T o2) {
return o1.compareTo(o2);
}});
You can use something like input.nextInt() to read in the next integer instead of the next String. I can see no reason why you are storing Strings instead of ints in your code. Then you can use what everyone else has suggested to combine the lists and/or sort them.
I also think you should do some more reading by yourself. Some of the questions you've asked in your comments are answered in the Java documentation.
When someone posts a suggestion, at the very least look it up in the API and try to understand it. People won't be giving you all the code here, they will just give you hints that you need to follow.
To sort an ArrayList you can use the Collections.sort() method; either with only a List of Comparable elements or with a Comparator.
This is the simplest way.
In your case Collections.sort(scores) will do the thing.
To sort a list, use java.util.Collections.sort( list ).
To make one list out of three, you can use alist.addAll(anotherList). Then sort aList as suggested by Collin Hebert.
I helped to answer this in your previous post. However, I will add it here as well. I think you may want a List instead of a list of Strings. This will allow you to sort on the number of tries the end user has attempted, in a natural way. In addition to the other answers here, the simplest way is then to make a call to Collections.sort(list)
Additionally the toString() method is used for debugging purposes, or to provide human readable information. It shouldn't be used to create objects in the way that you are utilizing it. Just my .02
If you absolutely require a list to be sorted at all times, don't use an ArrayList, use a PriorityQueue. It can be constructed to use the content's natural sort order (i.e. via the Comparable interface on each object), or via a Comparator. The advantage of PriorityQueue is it is always sorted even after new items are added.