Multiplication Tutor Java Program - java

I am working on writing a program that follows these instructions:
Your little sister asks you to help her with her multiplication, and you decide to write a Java program that tests her skills. The program will let her input a starting number, such as 5. It will generate ten multiplication problems ranging from 5×1 to 5×10. For each problem she will be prompted to enter the correct answer. The program should check her answer and should not let her advance to the next question until the correct answer is given to the current question.
After testing ten multiplication problems, your program should ask whether she would like to try another starting number. If yes, your program should generate another corresponding ten multiplication problems. This procedure should repeat until she indicates no.
I have the code correct to ask for the multiplication part, but I can't quite figure out how to get the program to ask if the user wants to continue.
The following code has the program run through once:
package hw5;
import java.util.Scanner;
public class HW5 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number you would like to attempt: ");
int start = input.nextInt();
int mult;
for (mult = 1; mult <= 10; mult++) {
int num = start * mult;
System.out.print(start + " x " + mult + " = ");
int ans = input.nextInt();
while (ans != num) {
System.out.print("Wrong answer, try again: ");
int ans2 = input.nextInt();
if (ans2 == num) {
break;
}
}
//System.out.print("Would you like to do another problem? ");
}
}
}
When I uncomment out line 21 the program returns:
Enter number you would like to attempt: 1
1 x 1 = 1
Would you like to do another problem? 1 x 2 = 2
Would you like to do another problem? 1 x 3 =
etc...
If I take the code from line 21 and put it outside of the for loop the program runs the for loop once and then jumps straight to the question.
How do I go about fixing this and successfully completing the instructions?

Here's how I'd do it:
package hw5;
import java.util.Scanner;
public class HW5 {
public static void main(String[] args)
{
boolean wantsToContinue = true;
while(wantsToContinue)
{
wantsToContinue = mathProblem();
}
}
public static boolean mathProblem()
{
Scanner input = new Scanner(System.in);
System.out.print("Enter number you would like to attempt: ");
int start = input.nextInt();
int mult;
for (mult = 1; mult <= 10; mult++) {
int num = start * mult;
System.out.print(start + " x " + mult + " = ");
int ans = input.nextInt();
while (ans != num) {
System.out.print("Wrong answer, try again: ");
int ans2 = input.nextInt();
if (ans2 == num) {
break;
}
}
//System.out.print("Would you like to do another problem? ");
}
boolean wantsToContinue;
//Ask if the user would like to do another problem here, set "wantsToContinue" accordingly
return wantsToContinue;
}
}

Related

User input never enters if statement

The point of the program is to have a user input an amount of integers endlessly (until they enter something other than an integer), and for each integer the user inputs, it should check if the integer is greater than or less than the value entered.
The problem: When the program runs, everything is fine until reaching
number = scanner.nextInt();
At this point, the user inputs their integer, but never makes it inside the following if statements. I would love a hint instead of an answer, but I'll take what I can get.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
do {
System.out.println("Enter number: ");
int number = 0;
int minNumber = 0;
int maxNumber = 0;
boolean hasInt = scanner.hasNextInt();
if (hasInt) {
number = scanner.nextInt();
if (maxNumber < number) {
maxNumber = number;
}
if (minNumber > number) {
minNumber = number;
}
} else {
System.out.println("Your minimum number: " + number);
System.out.println("Your maximum number: " + maxNumber);
break;
}
} while (true);
scanner.close();
}
}
Your minNumber and maxNumber declarations should be out side of the loop. Also, you need to initialize the values as below to get correct min and max comparison with the entered values only:
int minNumber = Integer.MAX_VALUE;
int maxNumber = Integer.MIN_VALUE;
In print statement instead of minNumber you are printing number!
It's not reaching the if statements, because if it did, the user input would update to the value entered I would think. It doesn't. It outputs the values initially declared.
You're not getting the right output and you have a hypothesis that the cause is the code not entering the if statements. Following the scientific method, the next step is to test your hypothesis.
If you put printouts inside the if statements you'll see that they are indeed running. That's not it. The mistake must be elsewhere. You should collect more evidence and develop a new hypothesis.
Hint: Try printing out the values of your variables at the beginning and end of each iteration. I've marked the places below. Are they what you expect them to be? You're going to see an anomaly that should point you in the right direction.
do {
System.out.println("Enter number: ");
int number = 0;
int minNumber = 0;
int maxNumber = 0;
// Print number, minNumber, and maxNumber.
boolean hasInt = scanner.hasNextInt();
if (hasInt) {
number = scanner.nextInt();
if (maxNumber < number) {
maxNumber = number;
}
if (minNumber > number) {
minNumber = number;
}
} else {
System.out.println("Your minimum number: " + number);
System.out.println("Your maximum number: " + maxNumber);
break;
}
// Print number, minNumber, and maxNumber.
} while (true);

Recursive Factorial Java

First off, yes this a HW assignment. Having issues with recursive factorials in Java. Everything I'm finding on here and elsewhere already shows me what I've done is correct. However I'm having issues with an additional step. Basically what I need is the 1) User to enter a number 2) Factorial to be calculated 3) If user enters anything but a character or string (rather than an int) for an error message to come out 4) The question to repeat until user enters "0" to exit.
Steps 1 and 2 I have completed. I'm having issues with step 3. It seems like I am missing a return statement if the user enters anything but an int but I can't seem to figure out exactly what.
Here is code thus far:
import java.util.Scanner;
public class Recursive
{
public static void main(String[] args)
{
int number; // To hold a number
char letter; // To hold a character
//Create a Scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
//Get a number from the user
System.out.print("Enter an integer to find the factorial: ");
number = keyboard.nextInt();
//Display the factorial
System.out.println(number + "! is " + factorial(number));
}
private static int factorial(int n)
{
if (n == 0)
return 1; // Base Case
else if (n > 0)
return n * factorial(n-1);
else (!(n>0))
return
System.out.println(number + "is invalid");
}
}
After getting the user input, before doing factorial, we have to check if input is a number or not. We can use pattern. Check regular expression patterns to do that. After checking if it is a number or not, check if it is zero, if yes use exit (0) to come out of the program. If not do the factorial
while (true) {
// Get a number from the user
System.out.print("Enter an integer to find the factorial: ");
int number = keyboard.nextInt();
if (Pattern.matches("\\d+", String.valueOf(number))) {
if (Integer.valueOf(number) == 0)
System.exit(0);
// Display the factorial
System.out.println(number + "! is " + factorial(number));
}
else
System.out.println("Error");
}
My answer is based on an assumption that your factorial function is working properly.In order to complete your step 3 and 4 you need to take input in a loop. In that loop, take input as string and parse it into integer, use try catch so that you can catch exception when a non-integer is given as input and you can prompt an error message.
public static void main(String[] args)
{
Integer number; // To hold a number
String letter; // To hold a character
//Create a Scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
//Get a number from the user
System.out.print("Enter an integer to find the factorial: ");
while(keyboard.hasNext()){
letter = keyboard.next();
try{
number = Integer.parseInt(letter);
if(number==0){
//Exiting
break;
}
int fact = factorial(number);
//Display the factorial
System.out.println(number + "! is " + fact);
System.out.print("Enter an integer to find the factorial: ");
}
catch(NumberFormatException e){
System.out.println("Invalid input please enter integers only");
}
}
}
Also your factorial function is having compilation issues currently. You need to fix it for proper functioning of your code.
My solution for recursive factorial using Java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.*;
import java.util.*;
class Main {
public static String factorial(int n,String s){
if(n>0){
BigInteger fact = new BigInteger(s);
fact = fact.multiply(new BigInteger(n + ""));
return factorial(n-1,fact.toString());
}
else{
return s.toString();
}
}
public static void main(String args[] ) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int n = Integer.parseInt(line);
if(n==0)
System.out.println("Factorial is 0");
else{
String s = factorial(n,"1");
System.out.println("Factorial is " + s);
}
}
}
the example of factorial using recursive in Java
public class MainClass {
public static void main(String args[]) {
for (int counter = 0; counter <= 10; counter++){
System.out.printf("%d! = %d\n", counter,
factorial(counter));
}
}
public static long factorial(long number) {
if (number <= 1)
return 1;
else
return number * factorial(number - 1);
}
}

Do Loops to create read user input to repeat or exit program Java

This is my first post.
Using a Scanner class, I'm trying to let user input to choose to repeat the program or quit. The thing is my Do loop statement repeats the program and does not exit even if the Do Loop is false and should exit the program.
// loop repeat or quit
do {
//initialize variable
int integer;
int x = 1;
int factorial = 1;
System.out.print("Please enter an integer \n");
integer = getInt.nextInt();
//loop for factorial
//multiple each increment until it reaches the integer
while (x <= integer) {
factorial *= x;
x++;
}; // factorial=x*x
System.out.println("the factorial of the integer " + integer + " is " + factorial);
System.out.print("do you want to quit? y or n \n");
quit = getString.next();
} while(quit != yes);
System.exit(0);
}
There were a few mistakes in your code, so I rewrote it a little bit and used the correct functions where you used incorrect ones.
public static void main(String args[])
{
// Scanner is used to take in inputs from user
Scanner scan = new Scanner (System.in);
String quit = "";
// loop repeat or quit
do {
//initialize variable
int integer = 0;
int x = 1;
int factorial = 1;
// User needs to enter integer, or it'll throw exception.
System.out.println("Please enter an integer");
integer = scan.nextInt();
//loop for factorial
//multiple each increment until it reaches the integer
// factorial = x!
while (x <= integer) {
factorial *= x;
x++;
};
System.out.println("the factorial of the integer " + integer + " is " + factorial);
System.out.println("do you want to quit? y or n");
quit = scan.next();
// if quit is NOT equal to y, we do it again
} while(!quit.equals("y"));
System.exit(0);
}
I hope the comments helps :)
I've edited your code and it now runs.
For future reference: include more comprehensive snippets so viewers of your code can more easily discover mistakes.
Problem: There is no way to guarantee the user only inputs y without any spaces . THe easy solution to this problem is to use the string method contains(). I've modified your loop so that if the user input y the program will exit and it now works. Let me know if this works and happy coding!
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String quit ="";
do { //initialize variable
int integer; int x = 1; int factorial = 1;
System.out.print("Please enter an integer \n");
integer = in.nextInt();
//loop for factorial
//multiple each increment until it reaches the integer
while (x <= integer) {
factorial *= x;
x++;
}; // factorial=x*x
System.out.println("the factorial of the integer " + integer + " is " + factorial);
System.out.print("do you want to quit? y or n \n");
quit = in.next();
} while(!quit.contains("y"));
System.exit(0);
}
Shouldn't it be
while(quit != "y");
I also don't understand why you use System.out.print(); and then use \n when there's a perfectly good System.out.pritnln();
Also, since we're dealing with Strings the .nextLine(); is good enough for the Scanner. (You'll have to declare String quit as well.)

Methods Help in Java

public static void main(String[] args)
{
int i = 0;
i = rollDice(11);
System.out.print(" \nThe number of rolls it took: " + i);
i = rollDice(5);
System.out.print(" \nThe number of rolls it took: " + i);
}
public static int rollDice(int desiredNum)
{
int dice1 = 0;
int dice2 = 0;
Random rand = new Random();
int sum = 0;
int count = 0;
do
{
dice1 = rand.nextInt(6) +1;
dice2 = rand.nextInt(6) +1;
sum = dice1 + dice2;
count++;
} while(sum != desiredNum);
return count;
}
}
Im wanting to make it where the user can enter their own desired sum of the numbers to be rolled .Also I'm wanting it to display the value of each rolled die as its rolled. It needs to allow the user to call the rollDice method as many times as they want to.
Heres my exmaple output
EX- Please enter the Desired number: 8
Roll 1: 4 6 Sum: 10
Roll 2: 3 5 Sum: 8
It took 2 rolls to get the Desired number.
The original code above WAS a lab i had to do a few weeks ago. But we have just started this. And im trying to get ahead of the class. And this community helps alot. Thanks in advance.
The simplest solution here is to read user input using a Scanner, until the user enters a nominated character which ends the program.
e.g.
public static void Main(String[] args) {
Scanner scan = new Scanner(System.in);
do {
System.out.println("Enter desired number:");
String in = scan.nextLine();
rollDice(Integer.parseInt(in));
// Implement console output formatting here
} while(!in.equalsIgnoreCase("q"))
}
Here, the user can roll the dice for their desired number as many times as they want. When they are finished, entering "q" or "Q" in the console will end the program.
Also see the Javadoc for Scanner.
Try separating it into a few different methods like this. It'll help you think about the problem in smaller parts.
public static void main(String[] args) {
String input = "";
while(true) {
//Request input
System.out.println("Please enter the Desired number:");
input = getInput();
//Try to turn the string into an integer
try {
int parsed = Integer.parseInt(input);
rollDice(parsed);
} catch (Exception e) {
break; //Stop asking when they enter something other than a number
}
}
}
private static String getInput() {
//Write the method for getting user input
}
private static void rollDice(int desiredNum) {
//Roll the dice and print the output until you get desiredNum
}
To repeat, add a statement where the user enters a character that determines whether or not the program repeats itself. For example:
char repeat = 'Y';
while (repeat == 'Y' || repeat == 'y') {
// Previous code goes here
System.out.println("Try again? {Y/N} --> ");
String temp = input.nextLine();
repeat = temp.charAt(0);
}

Right Loop for this exercise in Java

Hi guys i am learning java in order to code in Android, i got some experience in PHP, so i got assigned an exercise but cant find the right loop for it, i tried else/if, while, still cant find it, this is the exercise:
1- prompt the user to enter number of students, it must be a number that can divide by 10 (number / 10) = 0
2- check of user input, if user input not dividable by 10 keep asking the user for input until he enter the right input
How i code it so far, the while loop not working any ideas how to improve it or make it work?
package whiledowhile;
import java.util.Scanner;
public class WhileDoWhile {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
/* int counter = 0;
int num;
while (counter <= 100) {
System.out.println("Enter number");
num = user_input.nextInt();
counter += num; // counter = counter + num
//counter ++ = counter =counter +1
}
System.out.println("Sum = "+ counter);
*/
int count = 0;
int num;
System.out.println("Please enter a number: ");
num = user_input.nextInt();
String ex;
do {
System.out.print("Wrong Number please enter again: " );
num++;
}
while(num/10 != 0 );
}
}
When using a while loop, you'll want to execute some code while a condition is true. This code needs to go inside the do or while block. For your example, a do-while loop seems more appropriate, since you want the code to execute at least one time. Also, you'll want to use the modulo operator, %, inside of your while condition, not /. See below:
Scanner s = new Scanner(System.in);
int userInput;
do {
// Do something
System.out.print("Enter a number: ");
userInput = s.nextInt();
} while(userInput % 10 != 0);
Two things:
I think you mean to use %, not /
You probably want to have your data entry inside of your while loop
while (num % 10 != 0) {
// request user input, update num
}
// do something with your divisible by 10 variable

Categories