Java multiplication using Recursion - java

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

Related

How to find factorial and show result of counting in console?

public class Car {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
System.out.println(n+"!="+factorial(n));
}
public static int factorial(int num) {
return (num == 0) ? 1 : num * factorial (num - 1);
}
}
how make this code to text in console 3! = 1*2*3 = 6?
Don't use recursion for this. Besides, it isn't really efficient or necessary.
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int fact = 1;
String s = n + "! = 1";
for (int i = 2; i <= n; i++) {
fact *= i;
s += "*" + i;
}
s += " = ";
System.out.println(s + fact);
There can be many ways to do it e.g. you can build the required string or print the trail while calculating the factorial. In the following example, I have done the former.
As an aside, you should check the input whether it is a positive integer.
import java.util.Scanner;
public class Car {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int n = in.nextInt();
if (n >= 0) {
StringBuilder strFact = new StringBuilder();
int fact = factorial(n, strFact);
if (strFact.length() > 0) {
// Delete the last '*'
strFact.deleteCharAt(strFact.length() - 1);
System.out.println(n + "!= " + strFact + " = " + fact);
} else {
System.out.println(n + "!= " + fact);
}
} else {
System.out.println("This is an invalid input.");
}
}
public static int factorial(int num, StringBuilder strFact) {
int fact;
if (num == 0) {
fact = 1;
} else {
fact = num * factorial(num - 1, strFact);
strFact.append(num + "*");
}
return fact;
}
}
A sample run:
Enter an integer: 3
3!= 1*2*3 = 6

I have to create a program that compares SAT/ACT scores of two students. It technically works but it's missing something

So the program works, it just has a few things that I cant seem to fix:
1) It feels like it can be simplified using more/different methods. I don't want ot be redundant.
2) At the end of the program, I can't get figure out how to turn the two final scores into "first" and "second" We aren't allowed to use several sopln's the program has to be able to identify which of the two scores is highest and be able to recognize if it was the first or second applicant. Here is the code
import java.util.Scanner;
public class Admissions {
public static void main(String[] args) {
questionaire();
Scanner console = new Scanner(System.in);
double first = designation(console, " first ");
double second = designation(console, " second ");
System.out.println("First applicant overall score = " + first);
System.out.println("Second applicant overall score = " + second);
System.out.println();
double mostQualified = (Math.max(first,second));
System.out.println("The " + mostQualified + " applicant is better qualified.");
}
// *** Methods ***
public static void questionaire() {
System.out.println(" This program compares two applicants to \n " +
"determine which one is the stronger candidate. \n " +
"For each candidate please provide either SAT \n " +
"or ACT scores, plus a weighted GPA.");
System.out.println();
}
public static double designation(Scanner console, String x) {
System.out.println("Information for the" + x + "applicant: \n" +
"do you have 1) SAT scores or 2) ACT scores?");
int answer = console.nextInt();
if(answer == 2){
return act(console);
} else if (answer == 1){
return sat(console);
}else{
return cheat();
}
}
public static double designation2(Scanner console) {
System.out.println("Information for the second applicant: \n" +
"do you have 1) SAT scores or 2) ACT scores?");
int answer2 = console.nextInt();
if(answer2 == 2){
return act(console);
} else if (answer2 == 1){
return sat(console);
}else {
return cheat();
}
}
public static double act(Scanner console) {
System.out.println("ACT English?");
int actEnglish = console.nextInt();
if ((actEnglish < 1) || (actEnglish > 36)){
return cheat();
}
System.out.println("ACT math?");
int actMath = console.nextInt();
if ((actMath < 1) || (actMath > 36)){
return cheat();
}
System.out.println("ACT reading?");
int actReading = console.nextInt();
if ((actReading < 1) || (actReading > 36)){
return cheat();
}
System.out.println("ACT science?");
int actScience = console.nextInt();
if ((actScience < 1) || (actScience > 36)){
return cheat();
}
System.out.println("Overall GPA?");
double overallGPA = console.nextDouble();
if ((overallGPA < 0.0) || (overallGPA > 4.0)){
return cheat();
}
System.out.println("Maximum GPA?");
double maxGPA = console.nextDouble();
if ((overallGPA < 0.0) || (overallGPA > 4.0)){
return cheat();
}
int actScore = ((actScience - 1) + (actMath - 1) + (actReading - 1) + (actEnglish - 1) / (4*35));
double actGPA = ((overallGPA) / (maxGPA) * 100);
double finalActScore = (actScore + actGPA);
return finalActScore;
}
public static double sat(Scanner console){
System.out.println("SAT math?");
int satMath = console.nextInt();
if ((satMath < 200) || (satMath > 800)){
return cheat();
}
System.out.println("SAT verbal?");
int satVerbal = console.nextInt();
if ((satVerbal < 200) || (satVerbal > 800)){
return cheat();
}
System.out.println("Overall GPA?");
double overallGPA = console.nextDouble();
if ((overallGPA < 0.0) || (overallGPA > 4.0)){
return cheat();
}
System.out.println("Maximum GPA?");
double maxGPA = console.nextDouble();
if ((overallGPA < 0.0) || (overallGPA > 4.0)){
return cheat();
}
int satScore = ((satVerbal - 200) + (satMath - 200)) / (2*600);
double satGPA = ((overallGPA) / (maxGPA) * 100);
double finalSatScore = (satScore + satGPA);
return finalSatScore;
}
public static double cheat(){
System.out.println("YOU'RE A CHEATER.");
System.exit(-1);
return 0;
}
1) You can factorize part of your code
You already did it with your designation method which is good. You can delete the designation2 method.
In your act method. There is 4 repetitions of this test :
if ((value < 1) || (value > 36)){
return cheat();
}
You can factorise it inside a method like this :
private void checkScoreForAct(int value) {
if ((value < 1) || (value > 36)){
cheat();
}
}
Then in your act method, you call it to check the ACT score for the english, math, reading and science.
System.out.println("ACT English?");
int actEnglish = console.nextInt();
checkScoreForAct(actEnglish);
That's one exemple but you could also factorise the part where you calculate the overall GPA (present in the act and sat method).
Same for when you calculate the satGPA and actGPA, you could put this logic in a method.
2) How to turn the two final scores into first and second ?
You can easily check who is the applicant who have the best score.
public static String FIRST = "first";
public static String SECOND = "second";
public static String BOTH = "both";
String bestApplicant;
if (first == second) {
bestApplicant = BOTH;
} else if (first > second) {
bestApplicant = FIRST;
} else {
bestApplicant = SECOND;
}
double maxScore = (Math.max(first,second));
if (bestApplicant.equals(BOTH)) {
System.out.println("Both applicant are equally qualified with a score of " + maxScore);
} else {
System.out.println("The " + bestApplicant + " applicant is better qualified with a score of " + maxScore);
}
I'm not sure if your parameters exclude this, as what you say you aren't allowed to do makes no sense to me. Here's what you seem to be asking how to do:
String mostQualified = (first > second)? "first" : "second";
double bestScore = Math.max(first, second);
System.out.println("The " + mostQualified
+ " applicant is better qualified, with a score of "
+ bestScore);
Sample result:
The first applicant is better qualified, with a score of 88.1

Java classes and calling variables in other classes

I'm still fairly new in java programming and I've gotten some aspects down but the classes within Java are by far giving me the most trouble. What I'm trying to do is make a random number game where the player has to pick a number 1 through 10 and if it's wrong then try again and have the program record how many times they guessed (but not add to the number of guess when a number has been picked previously or if the number that was picked is outside the specified range) I have already worked out the logic code and was trying to make a class specifically for just the logic and a class that is specifically just for the I/O interface. But I'm having one heck of a time. Any input or tips will be very appreciated and I will provide the code that I already have below:
This is the Logic class where I want it to handle all the logic
package guessapp;
import java.util.HashSet;
import java.util.Scanner;
public class GuessLogic {
public static int Logic() {
HashSet<Integer> hs = new HashSet<>();
int GuessLogic = (int) (Math.random() * 10 + 1);
Scanner keyboard = new Scanner(System.in);
int A;
int guess;
int NumGuess = 1;
do {
guess = keyboard.nextInt();
if (hs.contains(guess)) {
A = 1;
return A;
}
if (guess < 0 || guess > 10) {
A = 2;
return A;
}
if (guess == GuessLogic) {
A = 3;
return A; // this will stop the loop
} else if (guess < GuessLogic) {
NumGuess++;
A = 4;
return A;
} else if (guess > GuessLogic) {
NumGuess++;
A = 5;
return A;
}
hs.add(guess);
} while (true);
}
public static int getGuess() {
int guess;
Scanner keyboard = new Scanner(System.in);
guess = keyboard.nextInt();
return guess;
}
}
And this is the class I want to handle all I/O interface
import java.util.HashSet;
import java.util.Scanner;
public class GuessApp {
public static void main(String[] args) {
int r, w, y;
r = GuessLogic.Logic();
w = GuessLogic.getGuess();
int NumGuess;
NumGuess = 2;
System.out.print("Enter a guess: ");
if (r == 1) {
System.out.println("You have already entered this number");
}
if (r == 2) {
System.out.println("Your guess is out of the specified range. Please try again.");
}
System.out.println("Your guess is " + w);
if (r == 3) {
System.out.println("You got it right!! Congrats!! Total Number of Guesses: " + NumGuess);
} else if (r == 4) {
System.out.println("You are wrong!!! Hint: Guess Higher, Guess number: " + NumGuess);
} else if (r == 5) {
System.out.println("You are wrong!!! Hint: Guess Lower, Guess number: " + NumGuess);
}
}
}
Below is the modified codes. There are some general ideas:
GuessLogic should be used as an instance rather than a static class. Because you need GuessLogic to save the operations and the target number.
The while loop should be coded in main. Because GuessLogic is responsible for logic only.
The elements is Set is unique, so there is no need to count how many different number by yourself.
GuessApp:
public class GuessApp {
public static void main(String[] args) {
int r, w, y;
GuessLogic guessLogic = new GuessLogic();
while(true){
System.out.print("Enter a guess: ");
w = guessLogic.getGuess();
r = guessLogic.Logic();
if (r == 1) {
System.out.println("You have already entered this number");
continue;
}
if (r == 2) {
System.out.println("Your guess is out of the specified range. Please try again.");
continue;
}
System.out.println("Your guess is " + w);
if (r == 3) {
System.out.println("You got it right!! Congrats!! Total Number of Guesses: " + guessLogic.getNumber());
break;
} else if (r == 4) {
System.out.println("You are wrong!!! Hint: Guess Higher, Guess number: " + guessLogic.getNumber());
} else if (r == 5) {
System.out.println("You are wrong!!! Hint: Guess Lower, Guess number: " + guessLogic.getNumber());
}
}
}
}
GuessLogic:
public class GuessLogic {
HashSet<Integer> hs = new HashSet<>();
int number = (int) (Math.random() * 10 + 1);
public int getNumber(){
return hs.size();
}
public int Logic(int guess) {
if (hs.contains(guess)) {
return 1;
}
if (guess < 0 || guess > 10) {
return 2;
}
if (guess == number) {
return 3; // this will stop the loop
} else if (guess < number) {
// just add to the set. The set will guarantee that there is no repetitive item.
hs.add(guess);
return 4;
} else if (guess > number) {
hs.add(guess);
return 5;
}
return -1;
}
public int getGuess() {
int guess;
Scanner keyboard = new Scanner(System.in);
guess = keyboard.nextInt();
return guess;
}
}

How to pass information with a get properly in java

I new to java, still trying to get down arguments and passing info. I am writing a blood pressure program for school and have some issue passing info from one class to another.
I have a fully functioning system to take in the user info in one class and have to set up another to check if the average is above or below range. Now, the range is easy, but the passing of info is another thing.
So, here's the code i wrote. the ONLY thing I'm worried about is the very last part, the 'getSystolic' and its return. I need to send the info to another part of the program not in main or in this PressueInput (its BPChecker btw) and just banging my head against the problem.
Thank you for the input:
` import java.util.Scanner;
public class PressureInput
{
private int sysInput;
private int diaInput;
private int sysAvrg;
private int diaAvrg;
public PressureInput()
{
sysInput = 0;
diaInput = 0;
sysAvrg = 0;
diaAvrg = 0;
}
public void setSysPressure()
{
sysInput = 0;
while(sysInput <= 0 || sysInput >= 320)
{
Scanner cin = new Scanner(System.in);
System.out.println("Please enter a systolic reading> ");
sysInput= cin.nextInt();
System.out.println("You have entered " + sysInput + "\n");
if(sysInput <=0 || sysInput >= 320)
{
System.out.println("You're either dead or entered"
+ " an error. Try again." + "\n");
}
}
sysAvrg += sysInput;
}
public int getSysPressure()
{
return sysInput;
}
public void setDiaPressure()
{
diaInput = 0;
while(diaInput <= 0 || diaInput >= 320)
{
Scanner cin = new Scanner(System.in);
System.out.println("Please enter a systolic reading> ");
diaInput= cin.nextInt();
System.out.println("You have entered " + diaInput + "\n");
if(diaInput <=0 || diaInput >= 320)
{
System.out.println("You're either dead or entered"
+ " an error. Try again." + "\n");
}
}
diaAvrg += diaAvrg;
}
public int getDiaPressure()
{
return diaInput;
}
public void sysAvrgRead()
{
sysAvrg = sysAvrg / 3;
System.out.println("\n" + "The systolic averge is " + sysAvrg);
}
public void diaAvrgRead()
{
diaAvrg = diaAvrg / 3;
System.out.println("The diastolic averge is " + diaAvrg + "\n");
}
public void setSystolic(int sys)
{
sysAvrg = sys;
}
public int getSystolic()
{
return sys;
}
} `
If you have a funftion in the class, that exhibits the var, then it should be fine. You need to make PressureInput a object, with PressureInput varnamePI = new PressureInput();
Then, access the var through varnamePI.sysAvrg=0; or so...

Java - Optional loop

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

Categories