Need help compiling this iteration and interface program - java

I'm trying to write this java program for a user to input two rational numbers and ask from a menu of options to compute some sort of function A. I'm stuck in a few places and don't know what else to do. I need some guidance. it wont compile. says constructor Rational is undefined and the last default is an invalid label .it is two class files were the driver files uses the rational file. both files are uploaded and separated by text. need help
import java.util.Scanner;
import java.util.*;
public class RationalDriver{
public static void main(String[] args){
int rationalNum1, rationalDen1, rationalNum2, rationalDen2;
Scanner in = new Scanner(System.in);
// first rational
System.out.println(" Input first rational number for the Numerator");
rationalNum1 = in.nextInt();
System.out.println(" Input first rational number for the Denominator");
rationalDen1 = in.nextInt();
if (rationalDen1 == 0){
System.out.println(" Cannont divide by zero ");
System.out.println(" please re enter another number ");
}
System.out.println("Rational Number #1 = ("+rationalNum1+"/"+rationalDen1+")");
//Displays 1st Rational Number
// second rational
System.out.println(" Input 2nd rational number for the 2nd Numerator");
rationalNum2 = in.nextInt();
System.out.println(" Input 2nd rational number for the 2nd Denominator");
rationalDen2 = in.nextInt();
if (rationalDen2 == 0){
System.out.println("Cannont divide by zero");
System.out.println(" please re enter another number");
}
System.out.println("Rational Number #2 = ("+rationalNum2+"/"+rationalDen2+")");
//Displays 2nd Rational Number
Rational r1 = new Rational ( rationalNum1, rationalDen1);
Rational r2 = new Rational ( rationalNum2, rationalDen2);
// System.out.println;//toString
}
public void display_menu() //menu options
{
System.out.print(" Enter the corresponding number for the desired action ");
System.out.println("1) Addition\n2) 2) Subtraction\n3) 3) Multiplication\n4) 4)Division\n5) 5) Test for Eqaulity\n6) 6) Change 1st rational number\n7) 7) Change 2nd rational number");
}
public void question()
{
System.out.println("Do you want to exit? [y/n]"); // ask user if they want to quit with yes or no option
Scanner q = new Scanner(System.in);
switch (q.nextInt())
{
case 'y' :
System.out.println ("Thank you and goodbye.");
break;
case 'n' :
InputMenu();
break;
default:
System.err.println ( "Unrecognized option" );
break;
}
}
public void InputMenu() // keys for the menu
{
Scanner in = new Scanner(System.in);
display_menu();
switch (in.nextInt())
{
case 1: //addition
System.out.println ( "1" );
System.out.println( "("+rationalNum1+"/"+rationalDen1+")"+ " + " + " ("+rationalNum2+"/"+rationalDen2+")" + "=" + r1.add(r2));
break;
case 2: //subtraction
System.out.println ( "2" );
System.out.println( "("+rationalNum1+"/"+rationalDen1+")"+ " - " + "("+rationalNum2+"/"+rationalDen2+")" + "=" + r1.subtract(r2));
break;
case 3: //mulitplication
System.out.println ( "3" );
System.out.println( "("+rationalNum1+"/"+rationalDen1+")"+ " * " + " ("+rationalNum2+"/"+rationalDen2+")" + "=" + r1.multiply(r2));
break;
case 4: //division
System.out.println ( "4" );
System.out.println( "("+rationalNum1+"/"+rationalDen1+")"+ " / " + "("+rationalNum2+"/"+rationalDen2+")" + "=" + r1.divide(r2));
break;
case 5: //compare to
System.out.println ( "5" );
question();
break;
case 6: //change the 1st Rational Number
System.out.println ( "6" );
Scanner in = new Scanner(System.in);
System.out.println(" Input first rational number for the Numerator");
rationalNum1 = in.nextInt();
System.out.println(" Input first rational number for the Denominator");
rationalDen1 = in.nextInt();
if (rationalDen1 == 0){
System.out.println(" Cannont divide by zero");
System.out.println(" please re enter another number");
}
break;
case 7: //change the 2nd Rational Number
System.out.println ( "7" );
System.out.println(" Input 2nd rational number for the 2nd Numerator");
rationalNum2 = in.nextInt();
System.out.println(" Input 2nd rational number for the 2nd Denominator");
rationalDen2 = in.nextInt();
if (rationalDen2 == 0){
System.out.println("Cannont divide by zero");
System.out.println(" please re enter another number");
break;
default:
System.err.println ( "Unrecognized option" );
break;
}
}
}
}
Here is the class file for rational
public class Rational{
private int Numerator;
private int Denominator;
//constructors
public Rational(){
Numerator = 1;
Denominator = 1 ;
}
//setters
//a-numerator
//b-denmonator
//c other.getNumerator
//d-other.getDenominator
public void add (Rational other){ // (ad + bc) / bd
Numerator = (Numerator*other.getDenominator() + Denominator*other.getNumerator());
Denominator = (Denominator*other.getDenominator());
//Normalize();
}
public void subtract (Rational other){ // (ad-bc) / bd
Numerator = (Numerator*other.getDenominator() - Denominator*other.getNumerator());
Denominator = (Denominator*other.getDenominator());
//Normalize();
}
public void multiply (Rational other){ // ac/db
Numerator = (Numerator*other.getNumerator() / other.getDenominator()* Denominator);
// Normalize();
}
public void divide (Rational other){//
}
public int getNumerator(){
return Numerator;
}
public int getDenominator(){
return Denominator;
}
//toString
//public String toString(){
//return toString()+ (rationalNum1 + "/" + rationalDen1);
}

In your main class you have:
Rational r1 = new Rational ( rationalNum1, rationalDen1);
Rational r2 = new Rational ( rationalNum2, rationalDen2);
you are passing 2 integers to a constructer that recives void, so you have to change your constructer (of Rational class) like this:
public Rational(int rationalNumber, int rationalDen){
Numerator = rationalNumber;
Denominator = rationalDen;
}
Hope it helps, let me know if it worked or if there is more something wrong...
Edit: your Scanner and print error.
You have this:
public void question()
{
System.out.println("Do you want to exit? [y/n]"); // ask user if they want to quit with yes or no option
Scanner q = new Scanner(System.in);
switch (q.nextInt()) // here you are assuming that you are reading a int in step
{ // of a string
case 'y' : // ' ' arent used for strings...
System.out.println ("Thank you and goodbye.");
break;
case 'n' :
InputMenu();
break;
default:
System.err.println ( "Unrecognized option" );
break;
}
}
so, what you need is:
public void question()
{
System.out.println("Do you want to exit? [y/n]"); // ask user if they want to quit with yes or no option
Scanner q = new Scanner(System.in);
switch (q.nextLine()) // change nextInt to nextLine, that is the string method
{ // of a string
case "y" : //change ' ' to " "
System.out.println ("Thank you and goodbye.");
break;
case "n" : //change ' ' to " "
InputMenu();
break;
default:
System.err.println ( "Unrecognized option" );
break;
}
}
Hope it help :)
Edit 3:
in your code you have: `
public class RationalDriver{
public static void main(String[] args){
int rationalNum1, rationalDen1, rationalNum2, rationalDen2; // this are local variables, they only exist inside main method
...`
}
So, what you can do is:
public class RationalDriver{
private static int rationalNum1, rationalDen1, rationalNum2, rationalDen2;
public static void main(String[] args){
// your main
}
what i did was take your local variables that only exists in your main and turn them in global variables so when you want change their value or give them a value you just do:
rationalNum1 = your valor;
Please note that if you use any variable without initialize it with a value you will get a null point exception...

you need to create a constructor Rational (int rationalNum1, int rationalDen1){}
In your program you used the constructor Rational ( rationalNum1, rationalDen1)
when you have only declared the default constructor public Rational(), which does no accept any arguments.
It is possible to have multiple constructor for a class and they are differentiated by the type and number of argument they accept.
E.g
class A(int a, int b);
is same as
Class A(int c, int b);
but not
Class(int a, float d)

Related

How to take multiple data types in single line on java?

I am new at coding and now I am learning Java. I tryed to write something like calculator. I wrote it with switch case but then I realized I must take all inputs in single line. For example in this code I took 3 inputs but in 3 different lines. But I must take 2 input and 1 char in single line. First first number second char and then third number. Can you help me ?
Public static void main(String[] args) {
int opr1,opr2,answer;
char opr;
Scanner sc =new Scanner(System.in);
System.out.println("Enter first number");
opr1=sc.nextInt();
System.out.println("Enter operation for");
opr=sc.next().charAt(0);
System.out.println("Enter second number");
opr2=sc.nextInt();
switch (opr){
case '+':
answer=opr1+opr2;
System.out.println("The answer is: " +answer);
break;
case '-':
answer=opr1-opr2;
System.out.println("The answer is: " +answer);
break;
case '*':
answer=opr1*opr2;
System.out.println("The answer is: " +answer);
break;
case '/':
if(opr2>0) {
answer = opr1 / opr2;
System.out.println("The answer is: " + answer);
}
else {
System.out.println("You can't divide to zero");
}
break;
default:
System.out.println("Unknown command");
break;
}
Try following way
System.out.print("Enter a number then operator then another number : ");
String input = scanner.nextLine(); // get the entire line after the prompt
String[] sum = input.split(" ");
Here numbers and operator separated by "space". Now, you can call them by sum array.
int num1 = Integer.parseInt(sum[0]);
String operator = sum[1]; //They are already string value
int num2 = Integer.parseInt(sum[2]);
Then, you can do as you did than.
You can try something like this:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter number, operation and number. For example: 2+2");
String value = scanner.next();
Character operation = null;
StringBuilder a = new StringBuilder();
StringBuilder b = new StringBuilder();
for (int i = 0; i < value.length(); i++) {
Character c = value.charAt(i);
// If operation is null, the digits belongs to the first number.
if (operation == null && Character.isDigit(c)) {
a.append(c);
}
// If operation is not null, the digits belongs to the second number.
else if (operation != null && Character.isDigit(c)) {
b.append(c);
}
// It's not a digit, therefore it's the operation itself.
else {
operation = c;
}
}
Integer aNumber = Integer.valueOf(a.toString());
Integer bNumber = Integer.valueOf(b.toString());
// Switch goes here...
}
Note: didn't validate input here.

An algebra program in java is not working correctly

I made a program which should display an equation after choosing a type of algebra equation which doesn't works for some reason.
I have tried changing the scanners name but it just displays Wrong choice when an expression is chosen.
I would really appreciate it if you can help me thank you.
This is the code:
/** WAP using switch case to print the following :
1. 3X+4Y+Z
2. 3A^2+4B^3+3C*/
import java.util.*;
class F
{
public static void main(String a[])
{
Scanner in = new Scanner(System.in);
System.out.println("Algebra Program executed : No. to be typed: ");
System.out.println(" (i) 3X+4Y+Z 1 ");
System.out.println(" (ii) 3A^2+4B^3+3C 2 ");
int ch = in.nextInt();
switch(ch)
{
//Program 1
case '1': Scanner sc = new Scanner(System.in);
System.out.println("Type a number for X...");
int X = sc.nextInt();
System.out.println("Type a number for Y...");
int Y = sc.nextInt();
System.out.println("Type a number for Z...");
int Z = sc.nextInt();
int sum = (3*X)+(4*Y)+Z;
System.out.println(" ");
System.out.println("Value of X is "+X);
System.out.println("Value of Y is "+Y);
System.out.println("Value of Z is "+Z);
System.out.println("Value of 3X+4Y+Z is "+sum);
break;
//Program 2
case '2': Scanner hi = new Scanner(System.in);
System.out.println("Type a number for A...");
double A = hi.nextDouble();
System.out.println("Type a number for B...");
double B = hi.nextDouble();
System.out.println("Type a number for C...");
double C = hi.nextDouble();
double pro = 3*Math.pow(A, 2) + 4*Math.pow(B, 3) + 3*C;
int isum = (int) pro;
System.out.println(" ");
System.out.println("Value of A is "+A);
System.out.println("Value of B is "+B);
System.out.println("Value of C is "+C);
System.out.println("Value of 3A^2+4B^3+3C is "+isum);
break;
//Else
default: System.out.println("Wrong Choice");
}
}
}```
You need to change the case to case 1 and case 2 instead of case '1' and case '2'.
Note that '1' and '2' are char literals; not the int literals. the ASCII value of '1' is 49 and that of '2' is 50.

how to stop the while loop in java? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I am new to Java and I am creating a simple calculator. I used while loop to run it continuously but I couldn't stop it, Please help me with the code.
My calculator class code is:
package calculator;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Boolean keepRunning = true;
while (keepRunning) {
double a, b, out;
int n;
String ans = null;
Scanner in = new Scanner(System.in);
System.out.println("Enter two Numbers ");
a = in.nextDouble();
b = in.nextDouble();
System.out.println("Enter the mode of operation:" + "\n"
+ "1. Addition" + "\n"
+ "2. Subtraction" + "\n"
+ "3. Multiplication" + "\n"
+ "4. Division");
n = in.nextInt();
switch(n){
case 1:
out = add(a,b);
System.out.println("The output is: "+ out );
break;
case 2:
out = sub(a,b);
System.out.println("The output is: "+ out );
break;
case 3:
out = mul(a,b);
System.out.println("The output is: "+ out );
break;
case 4:
out = div(a,b);
System.out.println("The output is: "+ out );
break;
default:
System.out.println("Enter Valid option");
break;
}
System.out.println("Do you want to continue? (Y/N)");
Scanner in1 = new Scanner(System.in);
ans = in1.next();
if(ans == "Y" || ans == "y"){
}else if(ans == "N" || ans == "n"){
keepRunning = false;
System.exit(0);
}
}
}
public static double add(double a, double b){
return a+b;
}
public static double sub(double a, double b){
return a-b;
}
public static double mul(double a, double b){
return a*b;
}
public static double div(double a, double b){
return a/b;
}
}
The if loop is not at all running what's the problem in it.
Note: This question is already exist in Stackoverflow but I can't find my answer.
Don't compare strings with == in Java, use "N".equals(ans), for example. Look out to the duplicate that #EJP post for you

For loop printing twice sometimes

In my convertEuro method the for loop is causing the output to be printed twice, but only sometimes. What I mean is this is what gets displayed:
Converting values to Euros.
£4.00 >>> €5.45
£123.44 >>> €168.13
Converting values to Euros.
£4.00 >>> €5.45
£123.44 >>> €168.13
During testing it seems to do this maybe 2 times out of 10, and I can't figure out why. Code below if someone can please help:
import java.util.Scanner;
import java.text.DecimalFormat;
import java.util.ArrayList;
public class Conversion {
public void mainMenu(Scanner scan, ArrayList<Double> values, DecimalFormat twoDecimal) {
int menuChoice;
System.out.println("1. Enter values and type -1 to stop");
System.out.println("2. Euros");
System.out.println("3. Dollars");
System.out.println("4. Yen");
System.out.println("5. Rupees");
System.out.println("6. Exit");
menuChoice = scan.nextInt();
switch (menuChoice) {
case 1:
enterValues(scan, values, twoDecimal);
case 2:
scan.nextLine();
convertEuro(scan, values, twoDecimal);
}
}
public void enterValues(Scanner scan, ArrayList<Double> values, DecimalFormat twoDecimal) {
double value = 0;
do {
System.out.print("Enter value. Enter -1 to stop: £");
while (!scan.hasNextDouble()) {
System.out.print("Please enter a double (£xx.xx): £");
scan.nextLine(); //Consumes \n
scan.next();
}
value = scan.nextDouble();
if (value != -1) {
values.add(value);
System.out.println("Value entered.");
}
}
while (value != -1);
System.out.println("Returning to main menu. ");
mainMenu(scan, values, twoDecimal);
}
public void convertEuro(Scanner scan, ArrayList<Double> values, DecimalFormat twoDecimal) {
System.out.println("Converting values to Euros.");
for (int i = 0; i < values.size(); i++) {
System.out.println("£" + twoDecimal.format(values.get(i)) + " >>> " + "\u20ac" + twoDecimal.format(values.get(i) * 1.362));
}
}
public static void main(String[] args) {
Conversion conv = new Conversion();
Scanner scan = new Scanner(System.in);
ArrayList<Double> values = new ArrayList<Double>();
DecimalFormat twoDecimal = new DecimalFormat("0.00");
conv.mainMenu(scan, values, twoDecimal);
scan.close();
}
}
You need to add a break; statement:
case 1:
enterValues(scan, values, twoDecimal);
break;
When the switch statement hits the correct case, it executes it and proceeds executing other cases which are below until and unless it hit an break statement.
The correct process is
switch (menuChoice) {
case 1:
enterValues(scan, values, twoDecimal);
break;
case 2:
scan.nextLine();
convertEuro(scan, values, twoDecimal);
break;
}
Thats why best practice is to put break statement after every case end.
Thank you

Why does my calculator automatically answer "0" before i can put my sign in?

Somewhere around line 15 it gives me issues.
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in); //scanner object created
System.out.println("Enter your first number");
int nr1 = sc.nextInt();
System.out.println("Enter your second number");
int nr2 = sc.nextInt();
System.out.println("Enter your sign (+ , - , /, *)");
String anvin = sc.nextLine();
int ans = 0;
//somewhere around this line is where it is having the problems. it gives me the answer before i can put in my sign;
if(anvin.equalsIgnoreCase("+")) {
ans = nr1 + nr2;
}
else if(anvin.equalsIgnoreCase("-")) {
ans = nr1 - nr2;
}
else if(anvin.equalsIgnoreCase("*")) {
ans = nr1 * nr2;
}
else if(anvin.equalsIgnoreCase("/")) {
ans = nr1 / nr2;
}
System.out.println(ans);
System.out.println("To continue type yes");
String yes= sc.nextLine();
if(yes.equalsIgnoreCase("yes")) {
return;
}
}
}
it answers "0" whatever I enter before I can put in my sign
Enter your first number
9
Enter your second number
9
Enter your sign (+ , - , /, *)
0
To continue type yes
please tell me what I did wrong and possibly correct it so I can understand further
Try changing your sc.nextInt() lines to Integer.parseInt(sc.nextLine()). This should make your code work correctly.
EDIT: updated the code to include a while loop to make it so you can do multiple runs per your comment. This would also require you changing your last if statement to break; instead of return;
Scanner sc = new Scanner(System. in ); //scanner object created
while (true) {
System.out.println("Enter your first number");
int nr1 = Integer.parseInt(sc.nextLine());
System.out.println("Enter your second number");
int nr2 = Integer.parseInt(sc.nextLine());
System.out.println("Enter your sign (+ , - , /, *)");
String anvin = sc.nextLine();
int ans = 0;
//somewhere around this line is where it is having the problems. it gives me the answer before i can put in my sign;
if (anvin.equalsIgnoreCase("+")) {
ans = nr1 + nr2;
} else if (anvin.equalsIgnoreCase("-")) {
ans = nr1 - nr2;
} else if (anvin.equalsIgnoreCase("*")) {
ans = nr1 * nr2;
} else if (anvin.equalsIgnoreCase("/")) {
ans = nr1 / nr2;
}
System.out.println(ans);
System.out.println("To continue type yes");
String yes = sc.nextLine();
if (!yes.equalsIgnoreCase("yes")) {
break;
}
}
Change
String anvin = sc.nextLine();
to
String anvin = sc.next();
Also keep in mind that you might divide through zero ;-)
Edit:
also change
String yes= sc.nextLine();
to
String yes= sc.next();
Instead of sc.nextLine(); use sc.next();
I would suggest you this, you can not only learn using objects but learn a better way of writing managed codes too,
Calculator.java -> a class
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
//Instantiate
Scanner input = new Scanner(System.in);
Calculations calc = new Calculations();
// Variable declarations
double answer = 0, entry1 , entry2 ;
char operator;
// Start
System.out.println("***** Welcome to the Command line calculator program *****");
System.out.print("Please enter the first number :");
entry1 = input.nextDouble();
System.out.print("Please enter the second number:");
entry2 = input.nextDouble();
System.out.println("Please enter the operation : ");
System.out.println("***** Operations :- + -> Add ; - ->Substract ; / -> Divide ; * -> Multiply ; ^ : Power *****");
operator = input.next().charAt(0);
// Switch case
switch (operator){
case '+' : answer = calc.add(entry1, entry2);
break;
case '-' : answer = calc.substract(entry1, entry2);
break;
case '/' : answer = calc.divide(entry1, entry2);
break;
case '*' : answer = calc.multiply(entry1, entry2);
break;
case '^' : answer = calc.power(entry1, entry2);
break;
}
System.out.println(entry1 + " " + operator + " " + entry2 + " = " + answer);
}
}`
Calculations.java -->another class holding calculations
import java.math.*;
public class Calculations {
// Addition Method
double add (double first, double second){
double answer = first + second;
return answer;
}
// Substraction Method
double substract (double first, double second){
double answer = first - second;
return answer;
}
// Multiplication Method
double multiply (double first, double second){
double answer = first * second;
return answer;
}
// Division Method
double divide (double first, double second){
double answer = first / second;
return answer;
}
// Power Method
double power(double a, double b){
double answer =Math.pow(a, b);
return answer;
}
}

Categories