I'm trying to solve this program using recursive function which is needed for our program. The program is converting a decimal number system from a decimal 16 divided to a base of 2 using recursion, but my problem is that instead of the expected output of 10000 somehow it is reversed into 00001.
public static void main(String[] args) {
int decimalValue = 0;
int targetBase = 0;
while (decimalValue != -1){
Scanner input = new Scanner(System.in);
System.out.print("Decimal value: ");
decimalValue = input.nextInt();
if (decimalValue == -1){
System.out.println("Thank you for using the program. bye!");
System.exit(0);
}
while (targetBase < 2 || targetBase > 16){
System.out.print("Target base: ");
targetBase = input.nextInt();
}
System.out.print("Value of " + decimalValue + " in base " + targetBase + " is ");
recursionFunction(decimalValue, targetBase);
targetBase = 0;
}
}
public static void recursionFunction(int Decimal, int Base){
int result,test1;
if (Decimal == 0) {
System.out.println(" " );
return;
}
result = Decimal / Base;
System.out.print(Decimal % Base);
recursionFunction(result, Base);
}
I am making a fraction calculator in JAVA that keeps inputting a fraction and then an operator and then the next fraction and so on. I've successfully made this thing work for matrices and integers but can't make a function to input fraction so that I can call that function from the loop every time a new fraction has to be inputted.
This is how its working for now but I want the inputting fraction part to be another function so that the function could be used for various occasions .
System.out.println("Enter Numerator 1");
num1=Integer.parseInt(sc.readLine());
System.out.println("Enter Denominator 1");
den1=Integer.parseInt(sc.readLine());
System.out.println("Enter Numerator 2");
num2=Integer.parseInt(sc.readLine());
System.out.println("Enter Denominator 2");
den2=Integer.parseInt(sc.readLine());
Here is an example of a Fraction class that can prompt user for a new fraction.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Fraction {
private final int nom;
private final int den;
public Fraction(int nom, int den) {
if (den <= 0)
throw new IllegalArgumentException("Invalid denominator: " + den);
this.nom = nom;
this.den = den;
}
public int getNom() {
return this.nom;
}
public int getDen() {
return this.den;
}
#Override
public String toString() {
return (this.den == 1 ? String.valueOf(this.nom) : this.nom + "/" + this.den);
}
public static Fraction prompt(Scanner sc, String message) {
Pattern p = Pattern.compile("\\s*(?:(?:(\\d+)\\s+)?(\\d+)/)?(\\d+)\\s*");
for (;;) {
System.out.print(message + ": ");
String line = sc.nextLine();
Matcher m = p.matcher(line);
if (m.matches()) {
if (m.start(2) == -1)
return new Fraction(Integer.parseInt(m.group(3)), 1); // whole number
int nom = Integer.parseInt(m.group(2));
int den = Integer.parseInt(m.group(3));
if (m.start(1) != -1)
nom += Integer.parseInt(m.group(1)) * den;
return new Fraction(nom, den);
}
System.out.println("** Not a valid fraction. Please enter values like 2/3 or 4 3/7 or 13");
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
for (;;) {
Fraction fraction = Fraction.prompt(sc, "Enter value");
if (fraction.getNom() == 0)
break;
System.out.println("You entered: " + fraction);
}
}
}
So, the issue is that my program goes fine through the process of collecting the two integers to go into the rational class, but then upon getting to the menu, it just exits after taking the choice. I've no idea why and no one is around to help.
EDIT: After significant fiddling, I've managed to at least get the system to give me some output: that is, that regardless of the number that I put in it is giving me the invalid output. I'm thinking maybe I should go back to the switch/case?
Here's the code:
import java.util.Scanner;
public class RationalDriver
{
private static Scanner in = new Scanner(System.in);
private static char choice;
private static String input;
public static void main(String[] args)
{
printHeading();
Rational first = new Rational();
numberOne(first);
Rational second = new Rational();
numberTwo(second);
menu(first, second);
}
public static void menu(Rational first, Rational second)
{
try{
displayMenu();
getValue(choice);
if(choice == '1')
{
System.out.println("\n" + first + " + " + second + " equals ");
first.add(second);
System.out.println(first);
}
else if(choice == '2')
{
System.out.println("\n" + first + " - " + second + " equals ");
first.subtract(second);
System.out.println(first);
}
else if(choice == '3')
{
System.out.println("\n" + first + " * " + second + " equals ");
first.multiply(second);
System.out.println(first);
}
else if(choice == '4')
{
System.out.println("\n" + first + " / " + second + " equals ");
first.divide(second);
System.out.println(first);
}
else if(choice == '5')
{
System.out.println("\nAre " + first + " and " + second + " equal?");
if(first.equals(second))
{
System.out.println("\nYes!");
}
}
else if(choice == '6')
{
System.out.println("Please enter a new rational number: ");
numberOne(first);
}
else if(choice == '7')
{
System.out.println("Please enter a new rational number: ");
numberTwo(second);
}
else if(choice == '8')
{
System.out.println("You chose to exit.");
System.exit(0);
}
else
{
System.out.println("You did not choose a valid entry.");
}
}
catch (Exception e) { e.printStackTrace(); }
}
private static void printHeading() // printHeading method
{
System.out.println("Oliver, James");
System.out.println("CSC201-02PR");
System.out.println("Dr. Java");
System.out.println("Project 7");
System.out.println("Rational Number");
System.out.println();
}
private static void displayMenu()
{
System.out.println("Enter the corresponding number for the desired action:");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.println("5. Test for Equality");
System.out.println("6. Change 1st Rational Number");
System.out.println("7. Change 2nd Rational Number");
System.out.println("8. Exit");
}
public static char getValue(char choice)
{
System.out.println("\nPlease enter your menu option (1 - 8):");
choice = in.next().charAt(0);
return choice;
}
public static void numberOne(Rational first)
{
int numer = 0;
int denom = 1;
boolean breaker = false;
while(!breaker)
{
System.out.println("Please enter your first numerator:");
input = in.next();
numer = Integer.parseInt(input);
System.out.println("Please enter your first denominator:");
input = in.next();
denom = Integer.parseInt(input);
if(denom == 0)
{
System.out.println("Denominator cannot be undefined.");
denom = in.nextInt();
}
else
breaker = true;
}
first.setNumer(numer);
first.setDenom(denom);
first.normalize();
System.out.println("Your rational number is: " + first + "\n");
}
public static void numberTwo(Rational second)
{
int numer = 0;
int denom = 1;
boolean breaker = false;
while(!breaker)
{
System.out.println("Please enter your second numerator:");
input = in.next();
numer = Integer.parseInt(input);
System.out.println("Please enter your second denominator:");
input = in.next();
denom = Integer.parseInt(input);
if(denom == 0)
{
System.out.println("Denominator cannot be undefined.");
denom = in.nextInt();
}
else
breaker = true;
}
second.setNumer(numer);
second.setDenom(denom);
second.normalize();
System.out.println("\nYour rational number is: " + second + "\n");
}
}
Here's the Rational class that I've made:
public class Rational
{
private int numerator; // instance variable for the numerator
private int denominator; // instance variable for the denominator
public Rational() // Constructor
{
numerator = 0;
denominator = 1;
}
public Rational(int numer, int denom) // Overloaded Constructor
{
numerator = numer;
denominator = denom;
normalize();
}
public void setNumer(int numer) // Setter for the Numerator value
{
numerator = numer;
}
public void setDenom(int denom) // Setter for the Denominator value
{
denominator = denom;
}
public void normalize()
{
if(denominator < 0)
{
denominator = -denominator;
numerator = -numerator;
}
}
public int getNumer() // Numerator Getter
{
return numerator;
}
public int getDenom() // Denominator Getter
{
return denominator;
}
public void add(Rational second) // Addition method
{
int a = this.getNumer();
int b = this.getDenom();
int c = second.getNumer();
int d = second.getDenom();
numerator = ((a * d) + (b * c));
denominator = (b * d);
this.normalize();
}
public void subtract(Rational second) // Subtraction Method
{
int a = this.getNumer();
int b = this.getDenom();
int c = second.getNumer();
int d = second.getDenom();
numerator = ((a * d) - (b * c));
denominator = (b * d);
this.normalize();
}
public void multiply(Rational second) // Multiplication Method
{
int a = this.getNumer();
int b = this.getDenom();
int c = second.getNumer();
int d = second.getDenom();
numerator = (a * c);
denominator = (b * d);
this.normalize();
}
public void divide(Rational second) // Division Method
{
int a = this.getNumer();
int b = this.getDenom();
int c = second.getNumer();
int d = second.getDenom();
numerator = (a * d);
denominator = (b * c);
this.normalize();
}
public boolean equals(Object second) // Equals method
{
if(second == null)
{
return false;
}
if(!(second instanceof Rational))
{
return false;
}
Rational other = (Rational)second;
return this.getNumer() * other.getDenom() == other.getNumer() * this.getDenom();
}
public String toString() // toString method
{
if(numerator == 0)
{
return "Result = 0";
}
if(denominator == 1)
{
return Integer.toString(numerator);
}
return Integer.toString(numerator) + "/" + Integer.toString(denominator);
}
}
I'm working on a program where the user inputs two different fractions and the computer then runs them through a Fraction method to test if they're equal or not. An additional step in the assignment is to throw an IllegalArgumentException to identify if one of the denominators is 0 and in turn restart the program. The Fraction and testFraction classes are as follows:
Fraction class:
class Fraction {
private int numerator;
private int denominator;
Fraction() {
numerator = 0;
denominator = 1;
}
Fraction (int num, int den) {
numerator = num;
denominator = den;
if (denominator == 0){
throw new IllegalArgumentException (
"Denominator cannot be zero");
}
}
public void setNum(int num){
numerator = num;
}
public void setDen(int den){
denominator = den;
}
public int getNum(){
return numerator;
}
public int getDen(){
return denominator;
}
public String toString() {
return numerator + "/" + denominator;
}
public boolean equals(Fraction other){
if (numerator * other.getDen() == denominator * other.getNum()){
return true;
}
else {
return false;
}
}
}
testFraction Class:
import java.util.Scanner;
public class testFraction {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int a = 1;
int b = 1;
int c = 1;
int d = 1;
Fraction f1 = new Fraction(a, b);
Fraction f2 = new Fraction(c, d);
System.out.println("Enter the numerator of the first fraction: ");
f1.setNum(keyboard.nextInt());
System.out.println("Enter the denominator of the first fraction: ");
f1.setDen(keyboard.nextInt());
try{
int fraction = a/b;
}
catch (IllegalArgumentException e){
System.out.println(e.getMessage);
main(args);
}
System.out.println("\nEnter the numerator of the second fraction: ");
f2.setNum(keyboard.nextInt());
System.out.println("Enter the denominator of the second fraction: ");
f2.setDen(keyboard.nextInt());
System.out.println("\nFraction 1: " + f1);
System.out.println("Fraction 2: " + f2);
System.out.println("\nAre fractions equal? " + f1.equals(f2));
System.out.println(("\nWould you like to run the counter with a different integer? \n(1 for YES - 0 for NO): "));
int answer = keyboard.nextInt();
if (answer == 1){
System.out.println("\nLet's Rock 'n Roll! ");
main(args);
}
else if (answer == 0){
System.out.println("\nLater Dude! ");
System.exit(0);
}
}
}
I feel like I'm incorrectly working in the try/catch. Thanks for your help.
You're throwing an IllegalArgumentException when initializing your Fraction, yet you try to catch it when you do an actual division in testFraction. Your catch will never be reached, since the exception at initialization will stop the code from reaching the incorrect division. You should instead put your try/catch around the code creating Fractions.
Moreover, you initialize your Fractions with mock values : 1. This isn't really useful, and pose a problem : your constructor will never throw its IllegalArgumentException, since it is called with correct values. You should raise the IllegalArgumentException in your setDenominator instead, and call it from your constructor.
I need to create a program in Java that determines if a number is prime.
The user should enter any number, and the program will determine if it's prime or not, and display "not prime" or "prime." My code now compiles and runs but it always says a number isn't prime even if it is.
import java.util.Scanner;
public class PrimeNumber
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int constant = 0;
int variable = 0;
System.out.println("Enter a Number to test if Prime or Not");
constant = input.nextInt();
variable = constant;
double answer = 0.0;
answer = testPrime(constant, variable);
System.out.println(+answer);
if (answer == 1)
{
System.out.println(+constant + " is a prime number.");
}
else
{
System.out.println(+constant + " is NOT a prime number.");
}
}
public static double testPrime(int number, int divide)
{
double prime = 0.0;
prime = number%divide;
if (prime > 0 && divide != number)
{
return testPrime(number, divide - 1);
}
else
{
return prime;
}
}
}
if (prime > 0 && divide != number)
This will never be true. Because your divide and number are always equal.
See that you have assigned variable=constant and that's what you pass to the method
constant = input.nextInt();
variable = constant;
answer = testPrime(constant, variable);
That said, you need go so complex to find out if a number is prime or not. Check the web for simple algorithms. See http://www.mkyong.com/java/how-to-determine-a-prime-number-in-java/ for example.
Not the answer as the OP wants recursion (homework I guess).
You need to only go till the square root of n to see if it has a divisor (divisor besides self will be < sqrt(n))
boolean isPrime(int n) {
if(n % 2 == 0)return false;
int till = (int)java.lang.Math.pow(n, 0.5); //(int)n / 2;
for(int i= 3;i<till;i+=2) {
if(n % i == 0)
return false;
}
return true;
}
I see you want recursion for this, so I converted tgkprog's answer to a recursive method (although his is definitely more efficient). Additionally, I think you may want to return a prime factor if the input isn't prime? I'm just speculating this judging from the OP's return value of a double instead of a boolean. Mine will return an int though, because returning a double is silly.
int isPrime(int n){ //starter function
if(n<=1) return n; //sanity check for weird inputs
if(n % 2 == 0) return 2; //2 is a prime factor
int start = (int)java.lang.Math.pow(n, 0.5);
return isPrime(n,start-(start%2)); //makes start odd if it wasn't already
}
int isPrime(int n, int testval){ //recursive function
if(testval<=1) return 1; //n is prime, return n since it has no prime factors
if(n % i == 0)
return i; //found a prime factor!
return isPrime(n,i-2);
}
with recursion
import java.util.Scanner;
public class PrimeRecursion
{
static int dbg;
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter non 0 if you want debug :");
dbg = input.nextInt();
long constant = 3;
long variable = 0;
while(true){
System.out.println("Enter a Number to test if Prime or Not (1 to exit)");
constant = input.nextLong();
if(constant < 3){
if(constant == 2){
System.out.println("2 is a special prime");
}
return;
}
if(constant % 2 == 0){
System.out.println(constant + " is NOT a prime number, even number.");
}else{
variable = (long)Math.pow(constant, 0.5);
variable = (variable % 2 == 1) ? variable : variable + 1;//odd number
double answer = 0.0;
answer = testPrime(constant, variable);
System.out.println("End answer : " + answer);
if (answer == 1){
System.out.println(+constant + " is a prime number. answer : " + answer);
}
else{
System.out.println(constant + " is NOT a prime number.answer : " + answer);
}
}
System.out.println();
}
}
static double testPrime(long number, long divide)
{
double prime = 0.0;
prime = (double)number / divide;
if(dbg > 0){
System.out.println("Debug number " + number + " | divide " + divide + " |prime : " + prime + " | Math.abs(prime) " + Math.abs(prime));
}
if (prime == ((long)prime))//whats the best way to do this?
{
//divided evenly
return divide;
}
else{
return testPrime(number, divide - 2);
}
}
}
the recursive function for me goes like-Correct me if i am wrong.Thank you.calling statement >Boolean b=isPrime(number,number-1);
recursive function-
void isPrime(int p,int d);
{
int prime=p%d;
if((p==0&&d>1)||p%2==0)
return true;//that the number is not prime
if(d==1)
return false;
else
return isPrime(p,d-2);//calls the function again
}
Well I am directly giving you all the code instead of writing snippet. Hope you all may like this one as I have tried my best to make it as simple as possible.
The code is :>
import java.util.*;
class Prime_Number
{
static int c=0;
public static void main(String args[])
{
int n,i,sq=0;
Scanner in=new Scanner(System.in);
Prime_Number ob=new Prime_Number();
System.out.print("Enter a no.:>");
n=in.nextInt();
i=n;
sq=(int)(Math.sqrt(n));//square root is been taken since a no. cannot have factors greater than its square root
int k=ob.prime_Chk(n,i,sq);
if(k==1)
{
System.out.println("Prime");
}
else
{
System.out.println("Non-Prime");
}
}
public int prime_Chk(int g,int i,int sq)
{
if(i==sq)
{
return c;
}
else
{
if(g%i==0)
{
c++;
}
i--;
return(prime_Chk(g,i,sq));
}
}
}
Well in the prime() I have taken int i , int sq and int g as arguments.Instead of those if you wish then you can take other variables also.
import java.util.Scanner;
public class HW8R_T03 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.print("Enter number: ");
int n = sc.nextInt();
int simple = prime(n,n-1);
System.out.println(simple==1 ? "prime" : "not prime");
}
static int prime(int x, int y){
int div = 1;
if (y==0 || y==1){
return div;
}
if (x%y==0){
div = y;
} else {
div = prime (x, --y);
}
return div;
}
}