Java - Optional loop - java

This is my code:
/* Linear equation student quiz
* This program creates equations of the form ax + b = c for students to solve.
*/
import java.util.Random;
import java.util.Scanner;
public class MathFunction {
public static void main(String[] args) {
int a, b, c;
double userAnswer, correctAnswer;
int numCorrect = 0;
Random ranNum = new Random();
Scanner input = new Scanner(System.in);
for (int problem = 1; problem <= 10; problem++)
{
a = ranNum.nextInt(2) + 1;
b = ranNum.nextInt(41) - 20;
c = ranNum.nextInt(41) - 20;
System.out.print("\n"+ a + "x + " + b + " = " + c + " ... x = ");
userAnswer = input.nextDouble();
correctAnswer = 1.0 * (c - b) / a;
if (userAnswer == correctAnswer)
{
System.out.println("Correct!");
numCorrect =+ 1;
}
else
{
System.out.println("Sorry, correct answer is " + correctAnswer);
}
}//end for loop
System.out.println("You got " + numCorrect + " out of ten.");
System.out.println("\nWant to do 10 more questions? <y/n>");
}//end main
}//end class
I want to be able to return to the loop if the user enters the character 'y'. The user will be prompted of this option every time they complete 10 of the math problems. Would I use a 'do-while'?

Yes, you should wrap the for loop with a do-while loop that checks if the user entered 'y'.
do {
for (...) {
...
}
System.out.println("You got " + numCorrect + " out of ten.");
System.out.println("\nWant to do 10 more questions? <y/n>");
input.nextLine();
String repeat = input.nextLine();
} while (repeat.equals("y"));

Here what I mean by breaking your program into methods,
/* Linear equation student quiz
* This program creates equations of the form ax + b = c for students to solve.
*/
import java.util.Random;
import java.util.Scanner;
public class MathFunction {
int a, b, c;
double userAnswer, correctAnswer;
int numCorrect = 0;
Random ranNum = new Random();
Scanner input = new Scanner(System.in);
//You function to calculate
public static compute()
{
for (int problem = 1; problem <= 10; problem++)
{
a = ranNum.nextInt(2) + 1;
b = ranNum.nextInt(41) - 20;
c = ranNum.nextInt(41) - 20;
System.out.print("\n"+ a + "x + " + b + " = " + c + " ... x = ");
userAnswer = input.nextDouble();
correctAnswer = 1.0 * (c - b) / a;
if (userAnswer == correctAnswer)
{
System.out.println("Correct!");
numCorrect =+ 1;
}
else
{
System.out.println("Sorry, correct answer is " + correctAnswer);
}
}//end for loop
System.out.println("You got " + numCorrect + " out of ten.");
System.out.println("\nWant to do 10 more questions? <y/n>");
}
public static void main(String[] args) {
// Then start by sking a question like "Ready to staxt Y/N"
//get user responce or user input and if user input is Y then call the compute method else system exit.
if(userAnswer=="Y")
{
compute();
}
else{
//Thanks for participating system closes.
System.exit(0);
}
}//end main
}//end class

Here is the simple solution
String choice = "y";
while(choice.equals("y")){
for (int problem = 1; problem <= 10; problem++)
{
a = ranNum.nextInt(2) + 1;
b = ranNum.nextInt(41) - 20;
c = ranNum.nextInt(41) - 20;
System.out.print("\n"+ a + "x + " + b + " = " + c + " ... x = ");
userAnswer = input.nextDouble();
correctAnswer = 1.0 * (c - b) / a;
if (userAnswer == correctAnswer)
{
System.out.println("Correct!");
numCorrect =+ 1;
}
else
{
System.out.println("Sorry, correct answer is " + correctAnswer);
}
}//end for loop
System.out.println("You got " + numCorrect + " out of ten.");
System.out.println("\nWant to do 10 more questions? <y/n>");
choice = input.nextLine(); // get the input
}

-> Wrap your code in a do while loop.
-> Also use input.nextLine() for reading all user inputs (double value and string "y" or "n"), as switching between input.nextDouble() and input.nextLine() , can sometimes cause errors. Parse the input value to double after user input.
outer: //label
do{
for (int problem = 1; problem <= 10; problem++)
{
a = ranNum.nextInt(2) + 1;
b = ranNum.nextInt(41) - 20;
c = ranNum.nextInt(41) - 20;
System.out.print("\n"+ a + "x + " + b + " = " + c + " ... x = ");
try{
userAnswer = Double.parseDouble(input.nextLine()); //use this to get double input from user
}
catch(NumberFormatException e){
//warn user of wrong input
break outer;
}
correctAnswer = 1.0 * (c - b) / a;
if (userAnswer == correctAnswer)
{
System.out.println("Correct!");
numCorrect =+ 1;
}
else
{
System.out.println("Sorry, correct answer is " + correctAnswer);
}
}//end for loop
System.out.println("You got " + numCorrect + " out of ten.");
System.out.println("\nWant to do 10 more questions? <y/n>");
if(input.nextLine().equalsIgnoreCase("y")){
continue outer; //if user wants to continue
}
else{
break outer; //if user does not want to continue, break out of outer do-while loop
}
}
while(true);

Related

How to output random letters in java and get the total, high score and lowest score?

Basically, I'm trying to output random uppercase letters and the loops go on forever what am I doing wrong?
I've tried other methods using java.util.Scanner for my input dialog but other than that I can't see what's wrong.
import javax.swing.*;
public class SlotMachine {
public static void main (String[] args) {
String HOWN = JOptionPane.showInputDialog ("Enter how many times you are going to play");
int HOW = Integer.parseInt (HOWN);
double counter = 0;
System.out.println("You chose to play " + HOW + " times");
for (int i = 0; i<HOW; i++) {
for (int b = 0; b<3; i++) {
double result = Math.random();
result = Math.round (result );
result = result * ((90 - 65)+1) - 65;
char resultF = (char)result;
counter = counter + result;
System.out.println ("");
System.out.println("you got: " + resultF + " which is " + result + "in ASCII code");
System.out.println("your total is: " + counter);
}
}
}
}
You have done
for (int b = 0; b<3; i++)
instead of the correct
for (int b = 0; b<3; b++)
This should help your loop terminate.

Java multiplication using Recursion

I am writing a simple code in Java that is using recursion. I want to show the product of two numbers that a user will enter. I managed to do that using recursion, but stuck at the point where I want to show that the product could be written as (example) 10*5 = 5+5+5+5+5+5+5+5+5+5 (10 times), or 12*3 = 3+3+3+3+3+3+3+3+3+3+3+3 (12 times). Here is my code so far. In the code i put a comment where it should be written (example). Thanks.
import java.util.Scanner;
public class RecursiveMultiplication {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int a, b;
System.out.print("Enter first number: ");
a = key.nextInt();
System.out.print("Enter second number: ");
b = key.nextInt();
System.out.println("The product of " + a + " and "
+ b + " is: " + multiRec(a, b));
System.out.println("It could also be written as: "); //Here should product be broken into smaller numbers
}
public static int multiRec(int x, int y) {
if (x == 0 || y == 0) {
return 0;
} else {
if (x == 1) {
return y;
} else {
return x + (multiRec(x, y - 1));
}
}
}
}
A StringBuilder should be defiend as
StringBuilder buf = new StringBuilder (a);
Pass this StringBuilder paramater into multiRec
and then change multiRec to be
public static int multiRec(int x, int y, StringBuilder buf) {
if (x == 0 || y == 0) {
return 0;
} else {
if (x == 1) {
return y;
} else {
buf.append (" + ").append (x);
return x + (multiRec(x, y - 1, buf));
}
}
}
}
Then when completed simply printout its value
import java.util.Scanner;
public class RecursiveMultiplication {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int a , b;
System.out.print("Enter first number: ");
a = key.nextInt();
System.out.print("Enter second number: ");
b = key.nextInt();
System.out.printf("%d %s %d %s",a , "*" , b ,"= ");
System.out.println("\nThe product of " + a + " and "
+ b + " is: " + multiRec(b, a));
// System.out.println("It could also be written as: "); //Here should product be broken into smaller numbers
}
public static int multiRec(int x, int y) {
if (x == 0 || y == 0) {
return 0;
} else {
System.out.print(x+" ");
if (y == 1) {
return x;
} else {
System.out.print(" + ");
return x + (multiRec(x, y - 1));
}
}
}
}

How to randomly position a variable within X + Y = Z operation and loop

I basically want to be able to loop an X + Y = Z equation until the user inputs something other than an integer, like the letter "A" and also when having any number make the loop stop displaying a message.
Also, I am confused on how to randomly position the "?" which the user must input the correct answer.
For example
System.out.println("What is: " + num1 + " + ? = " + answer);
So far:
I am positioning the "?" manually through the IF statements. Can this be done in a more efficient way?
public static void main(String[] args) {
Random rand = new Random();
Scanner input = new Scanner(System.in);
int num1, num2, number3, answer;
do {
num1= 1 + rand.nextInt(10);
num2= 1 + rand.nextInt(10);
answer= num1 + num2;
System.out.println("What is: " + num1 + " + ? = " + answer);
number3= input.nextInt();
if (number3 == num2)
System.out.println("That is correct");
else
System.out.println("That is wrong");
num1= 1 + rand.nextInt(10);
num2= 1 + rand.nextInt(10);
answer= num1 + num2;
System.out.println(num1 + " + ? = " + answer);
number3= input.nextInt();
} while(number3 !=0);
}
Here is one way to do it:
public static void main(String[] args) {
Random rand = new Random();
Scanner scanner = new Scanner(System.in);
int[] xyz = new int[3];
String[] display = new String[3];
int answer, position;
do {
xyz[0] = 1 + rand.nextInt(10);
xyz[1] = 1 + rand.nextInt(10);
xyz[2] = xyz[0] + xyz[1];
for (int i = 0; i < xyz.length; i++)
display[i] = String.valueOf(xyz[i]);
position = rand.nextInt(3);
display[position] = "?";
System.out.println("What is: " + display[0] + " + " + display[1] + " = " + display[2]);
do {
System.out.println("Please enter an integer or 'S' to stop");
String input = scanner.nextLine();
if (input.equals("S")) {
scanner.close();
System.out.println("Stopped");
return;
}
else if (input.matches("\\d+")) { // \\d+ means "a digit (0-9) once or more
answer = Integer.parseInt(input);
break;
}
} while (true);
if (answer == xyz[position])
System.out.println("That is correct");
else
System.out.println("That is wrong");
} while (true);
}
Notes:
I use an inner do-while loop to repeatedly check the input and ask the user for a valid input.
I use 2 arrays: one for storing the numbers and another for storing the display values.
I also added a stop condition since the outer loop is infinite. Always close the Scanner when you finish.
I randomly pick 1 of 3 positions for the "?".

Java Unexpected Programming Result

I would like to write a game about who would take the last marble and I've successfully run it. But when I attempted to add some error messages to it, such as showing "Incorrect range" when the inputs are out of range, it doesn't work properly. I know the problem is due to the incorrect recognition of variable "totalNum", but how to solve it? Thanks in advance :)
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int pn = 1;
System.out.print("Intial no. of marbles [10 ~ 100]: ");
int totalNum = in.nextInt();
int input = 0;
int from = 1;
int to = totalNum/2;
if (totalNum < 10||totalNum > 100) {
System.out.println("Incorrect range. Try again!");
System.out.print("Intial no. of marbles [10 ~ 100]: ");
totalNum = in.nextInt();
}
else {
while (totalNum > 1) {
totalNum = in.nextInt();
System.out.print("Player" + pn + " [" + from + " ~ " + to + "]: ");
input = in.nextInt();
if (input < from||input > to) {
System.out.println("Incorrect range. Try again!");
continue;
}
totalNum = totalNum - input;
System.out.println("Remaining no. of marbles: " + totalNum);
if (pn == 1) {
pn = 2;
}
else {
pn = 1;
}
}
}
System.out.println("Player" + pn + " takes the last marble.");
if (pn == 1) {
pn = 2;
}
else {
pn = 1;
}
System.out.println("Player" + pn + " wins!");
}
I imagine this line in the while loop is the problem:
totalNum = in.nextInt();
It keeps trying to take the next input from the user but there isn't a second integer. Not sure what happens after that.
Also, your entire program seems to be roughly equivalent to doing
totalNum%2+1
and printing the answer.

Speeding up Pythogrean triple calculator

So far my code runs fine, but I need a way to speed it up. When the user enters max_values to be 25000 it takes about 1.81 seconds and I need it to be less than one second. I tried my best to optimize my triples method but I don't know what else to do.
import java.util.InputMismatchException;
import java.util.Scanner;
public class Pythagorean {
public static void triples(int max_values){
int x = 0;
for(int c = 5; c <= max_values; c++){
int cTwo = c * c;
int b = c - 1;
for (int a = 0;a <= cTwo - b*b;a++){
if (a*a + b*b == cTwo){
x++;
System.out.println(x + ") " + a + " " + b + " " +c);
}
}
}
}
public static void main(String[] args){
System.out.println("--- Pythagorean Triple Generator ---");
System.out.println();
Scanner input = new Scanner(System.in);
int max_value = 0;
System.out.print("Enter max value for c: ");
try{
max_value = input.nextInt();
} catch (InputMismatchException ime) {
input.nextLine();
System.err.println("Error: Input is not an integer.");
System.exit(1);
}
input.close();
long start = System.currentTimeMillis();
triples(max_value);
double elapsed = (System.currentTimeMillis() - start)/ 1000.0;
System.out.println("Searching complete...");
System.out.printf("Elpased time: %.3f\n", elapsed);
}
}
This just ran in 0.999 seconds on my PC.
It uses a single StringBuilder to collect all the output, then does just one println at the end.
public static void triples(final int max_values)
{
int x = 0;
final StringBuilder sb = new StringBuilder(24000);
for (int c = 5; c <= max_values; c++)
{
final int cTwo = c * c;
final int b = c - 1;
final int bTwo = b * b;
final int cTwoLessB = cTwo - bTwo;
for (int a = 0; a <= cTwoLessB; a++)
{
if (a * a + bTwo == cTwo)
{
x++;
sb.append(x);
sb.append(") ");
sb.append(a);
sb.append(" ");
sb.append(b);
sb.append(" ");
sb.append(c);
sb.append("\n");
}
}
}
System.out.println(sb.toString());
}
The bottleneck is most likely System.out.println. Writing to the console often takes time.
for (int a = 0;a <= cTwo - b*b;a++){
if (a*a + b*b == cTwo){
x++;
System.out.println(x + ") " + a + " " + b + " " +c);//Do you really need this?
}
}
Maybe you could store it in a collection and do the printing after the loop is done (or use Stringbuilder as suggested).
Some optimizations:
int multiplyB = b*b ;//multiplication can also be slow.
for (int a = 0;a <= cTwo - multiplyB;a++){
if (a*a + multiplyB == cTwo){
++x;//use preincrement operator
str.append(x ).append(") ").append(a).append( " ").append(b).append(" ").append(c).append("\n");
}
}

Categories