This code converts from meters to feet/inches/kilometers. Sorry, I know this is basic, I'm new to Java. When prompted for a number of meters, if 4 or over is entered it doesn't convert and ends the program. Does anyone know what I did wrong?
import javax.swing.JOptionPane;
public class Measurements
{
public static void main(String[] args)
{
// Have user make selection
String input;
int selectedNum; // number chosen
float numMeters; // number of meters
input = JOptionPane.showInputDialog("Enter a distance in meters.");
numMeters = Float.parseFloat(input);
menu();
selectedNum = Integer.parseInt(input);
// Selection results
if (selectedNum < 1 )
{ errorMessage(); }
if (selectedNum == 1)
{ showKilometers(numMeters); }
if (selectedNum == 2)
{ showInches(numMeters); }
if (selectedNum == 3)
{ showFeet(numMeters); }
if (selectedNum == 4)
{
exitSystem();
}
}
/** errorMessage method */
public static double errorMessage()
{
double selectedNum;
String input;
input = JOptionPane.showInputDialog("That is not a valid selection. Please enter 1, 2, 3, or 4.");
selectedNum = Integer.parseInt(input);
return selectedNum;
}
/** menu method */
public static String menu()
{
String input;
input = JOptionPane.showInputDialog("Choose a selection:\n1. Convert to kilometers\n2. Convert to inches\n3. Convert "
+ "to feet\n4. Quit the program.");
return input;
}
/** showKilometers method */
public static void showKilometers(double numMeters)
{
double result;
result = numMeters*.001;
JOptionPane.showMessageDialog(null, numMeters + " meters is " + result + " kilometers.");
}
/** showInches method */
public static void showInches(double numMeters)
{
double inches;
inches = numMeters*(39.37);
JOptionPane.showMessageDialog(null, numMeters + " meters is " + inches + " inches.");
}
/** showFeet */
public static void showFeet(double numMeters)
{
double awesome;
awesome = (3.281*numMeters);
JOptionPane.showMessageDialog(null, numMeters + " meters is " + awesome + " feet.");
}
public static void exitSystem()
{
System.exit(0);
}
}
The String input in menu() is a different variable from the String input in main.
The menu function should be returning the value for selectedNum to use. Once that fix is made,
menu();
selectedNum = Integer.parseInt(input);
should be changed to:
selectedNum = Integer.parseInt(menu());
The input return from menu() is not the input in main, the input in main is always refer to the input of "Enter a distance in meters.", that is the reason why when user enter number of meters >=4 the program either exit or show error. Besides, I would prefer using switch than if else for condition switching scenario;
public static void main(String[] args)
{
double numMeters = Double.parseDouble(JOptionPane.showInputDialog("Enter a distance in meters."));
switch(menu()) {
case 1:
showKilometers(numMeters);
break;
case 2:
showInches(numMeters);
break;
case 3;
showFeet(numMeters);
break;
case 4;
exitSystem();
break;
default;
errorMessage();
break;
}
}
just use this
selectedNum = menu();
instead of
menu();
selectedNum = Integer.parseInt(input);
since the menu() function is already return integer value, no need to parse it.
however you can use switch statement as in this code
switch (selectedNum){
case 1: showKilometers(numMeters);
case 2: showInches(numMeters);
case 3: showFeet(numMeters);
case 4: exitSystem();
default: errorMessage();
}
Related
The title says this is homework, I have been beating my head into the wall for hours, so please help. It works fine, at least the math part does, I work the conversion it worked just fine. I went to change the output dialog box to list what the ending unit was, instead of just listing the variable e.g. your lbs is the end. And not to allow negative starting weights.
Now I can't get the dialog box to not give me an error. (Lines 145 -148) I put in a sample dialog box using the Return option that doesn't work, but if I set it to a variable in my case test, it will work fine. He gave us starting code, I recopied his original code and that doesn't work. The next error I get is I wrote a method that takes two doubles and a char. When I call the function I pass it two doubles and a char it says it can't convert a string (Line 255).
This has been frustrating I over engineered this and now to have it not work is killing me. I don't understand how I can copy his original code in and it no longer works. Dialog boxes confuse me but I think I understand them.
return JOptionPane.showConfirmDialog(A)(null(B), display(C),0,1);
A is the call of the for the box what type
B is the object type my understanding its always call
C is the string, text message of the box
The last two got to do with the the icon and button displayed.
He got us started on eclipse, which said I had error in code where there none, I spent hours looking at them, they went away once I reloaded my code.
Please any thing would be helpful, but an example or corrected code (I know that is a lot) with explanations on why there are correct would be helpful. My husband knows java but not dialog boxes, so he can't help. And the method call looks right to both of us.
/*
* Uses: methods, dialog boxes, and a menu to convert weights
*
*/
import javax.swing.JOptionPane;
public class WeightCon {
char choices, choicee;
public static char menu() {
char choice;
int typeNum = 3;
boolean OK;
String prompt, results, title;
prompt = "Choose Starting Unit\n";
prompt += "A. Pounds\n";
prompt += "B. Kilograms\n";
prompt += "C. Stones\n";
prompt += "D. ounces\n";
prompt += "E. Netons\n";
prompt += "F.Grams\n";
prompt += "\n\nEnter the letter of your choice:";
title = "Weights";
do {
results = JOptionPane.showInputDialog(null,prompt,title, typeNum);
choice = results.toUpperCase().charAt(0);
if(choice >= 'A' && choice <= 'F') {
OK = true;
}
else {
OK = false;
title = "Not Valid Input!";
typeNum = 0;
}
}while(! OK);
return choice;
}
public static double LbstoKG(double k) {
return k * 0.453592;
}
public static double KtoLBS(double L) {
return L / 0.453592;
}
public static double LbstoStone(double S) {
return S / 14;
}
public static double LBStoOunce(double O) {
return O / .0625;
}
public static double LbstoNewton(double N) {
return N * 4.4482216282509;
}
public static double LBStoGarm(double G) {
return G / 0.00220462 ;
}
public static double KtoL(double L) {
return L / 0.453592;
}
public static double stoneToLbs(double L) {
return L * 14;
}
public static double ounceToLBS(double L) {
return L * .0625;
}
public static double NewtonToLBS(double L) {
return L / 4.4482216282509;
}
public static double GramtoLBS(double L) {
return L * 0.00220462 ;
}
//public static double
public static double getDouble(String prompt) {
boolean OK;
double val=0;
String temp, title = "Enter a double value";
int typeNum = 3;
do {
OK = true;
temp = JOptionPane.showInputDialog(null, prompt, title, typeNum);
try {
val = Double.parseDouble(temp);
}
catch(Exception e) {
OK = false;
title = "Error! Invalid input. Must be a double value";
typeNum = 0;
}
try {
val = Double.parseDouble(temp);
}
catch(Exception b) {
if( val < 0) {
title = "Error! Invalid input. Must be a positive double value";
typeNum = 0;
}
}while(! OK);
}while(! OK);
return val;
}
public static String outputResults(double start, double end, char choices){
int test;
String end1;
if(choices == 'A') {
end1 = "Your end weight is the following pounds: ";
} else if (choices == 'B') {
end1 = " Your end weight is the following kilograms: ";
} else if (choices == 'C') {
end1 = " Your end weight is the following stones: ";
} else if (choices == 'D') {
end1 = " Your end weight is the following ounces: ";
} else if (choices == 'E') {
end1 = " Your end weight is the following newtons: ";
} else if (choices == 'F') {
end1 = " Your end weight is the following grams: ";
} else {end1 = " ERROR ERROR UNDEFINDED ERROR PLEASE CONSOLT DOCUMENTATION";}
String endreal = String.valueOf(end);
String display = "" + end1 + endreal;
//int input =
test = JOptionPane.showConfirmDialog(null, display,0,1);
test = JOptionPane.showConfirmDialog(null, display);
return JOptionPane.showConfirmDialog(null, display);
return JOptionPane.showConfirmDialog(null, display,0,1);
}
//display += "Do again?";
//return JOptionPane.showConfirmDialog(null,"test",0,1);
//return JOptionPane.showConfirmDialog(null,display,0,1);}}
//return JOptionPane.showConfirmDialog(null, "test",0,1);}}
//}
//
public static void main(String[] args) {
double get;
double lbs=0,ounce=0,kgs=0, stone=0,newton=0,gram=0 ;
double temp,start, end;
char choice, choices;
int button;
//String end1;
start =-99;
end = -999;
get = 0;
temp = 0;
do {
choice = menu();
choices = choice;
switch(choice) {
case 'A':
get = getDouble("Enter pounds : ");
lbs = get;
start = get; //LbstoKG(get);
temp = kgs;
break;
case 'B':
get = getDouble("Enter kilograms : ");
kgs = get;
start = KtoL(get);
temp = lbs;
break;
case 'C':
get = getDouble("Enter Stones : ");
stone = get;
start = stoneToLbs(get);
temp = lbs;
break;
case 'D':
ounce = getDouble("Enter Ounces : ");
start = ounceToLBS(get);
temp = lbs;
break;
case 'E':
get= getDouble("Enter Newtons : ");
newton = get;
start = NewtonToLBS(get);
temp = lbs;
break;
case 'F':
get = getDouble("Enter grams : ");
gram = get;
start = GramtoLBS(get);
temp = lbs;
break;
}
//button = outputResults(get,get);
//} while(button == 0);
// do {
choice = menu();
switch(choice) {
case 'A':
//get = getDouble("Enter pounds : ");
//lbs = getDouble("Enter pounds : ");
//kgs = get;
end = start;
break;
case 'B':
//get = getDouble("Enter kilograms : ");
end = LbstoKG(start);
break;
case 'C':
//get = getDouble("Enter Stones : ");
//stone = get;
end = LbstoStone(start);
break;
case 'D':
//ounce = getDouble("Enter Ounces : ");
end = LBStoOunce(start);
break;
case 'E':
//get= getDouble("Enter Newtons : ");
end = LbstoNewton(start);
System.out.printf("Hello");
break;
case 'F':
//get = getDouble("Enter grams : ");
end = LBStoGarm(start);
break;
}
button = outputResults(end,start,choice);
} while(button == 0);
}}
After copying and pasting your code into my compiler, there were multiple errors.
First Mistake in outputResults(): Remove the 0, and the 1.
The method showConfirmDialog(Component, Object, String, int) in the type JOptionPane
is not applicable for the arguments (null, String, int, int)
Line:
test = JOptionPane.showConfirmDialog(null, display,0,1);
Correction:
test = JOptionPane.showConfirmDialog(null, display);
Second and Third Mistake also in outputResults(): You cannot return two objects. Also, your method returns a String.
return JOptionPane.showConfirmDialog(null, display);
return JOptionPane.showConfirmDialog(null, display,0,1); // 0, 1 again.
// The second return statement is dead code, and this also makes the first mistake again
Your method returns a String.
JOptionPane.showConfirmDialog(null, display); returns an int.
So in your method returning a String, if you return an int instead, it will be a compiler error. For example:
... String outputResults(...){
return JOptionPane.showConfirmDialog(null, display);
}
1 quick fix: change return type to int (method: String outputResults(double, double, char))
Fourth Mistake in main(): Fix your Third Mistake and ignore this fix.
int button = ...;
...
button = outputResults(end,start,choice); // Returns String, but button is an int
// Change button to a string?
// Integer.parseInt(outputResults(end,start,choice)); ?
I cannot figure out how to have the program loop through the Conversion Menu and then return to the Main Menu from choice "4 Return" as shown in the example.
Example of what the program output might look like:
Main Menu
Enter Distance
Quit the program
Please enter your choice: 1
Enter a distance in meters: 500
Conversion Menu
Convert to kilometers
Convert to inches
Convert to feet
Return
Enter your choice: 1
500 meters is 0.5 kilometers
Conversion Menu
Convert to kilometers
Convert to inches
Convert to feet
Return
Enter your choice: 3
500 meters is 1640.5 feet
Conversion Menu
Convert to kilometers
Convert to inches
Convert to feet
Return
Enter your choice: 4
Main Menu
Enter Distance
Quit the program
Please enter your choice: 2
Good Bye!
I've found multiple solutions for the program when it doesn't include the main menu and the looping back to it but I can't seem to find anything on this.
Here's what I have:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int choice;
int option;
double meters = 0;
conversionControl();
choice = keyboard.nextInt();
switch (choice) {
case 1:
System.out.println("\nEnter a Distance in Meters:");
meters = keyboard.nextDouble();
break;
case 2:
quitProgram();
break;
default:
showError("Please Enter a Valid Option");
conversionControl();
option = keyboard.nextInt();
if (option == 1) {
System.out.println("\nEnter a Distance in Meters:");
meters = keyboard.nextDouble();
}
else if ( option == 2) {
quitProgram();
}
break;
}
do{
menu();
choice = keyboard.nextInt();
switch (choice) {
case 1:
showKilometers(meters);
break;
case 2:
showInches(meters);
break;
case 3:
showFeet(meters);
break;
case 4:
conversionControl();
option = keyboard.nextInt();
if (option == 1) {
System.out.println("\nEnter a Distance in Meters:");
meters = keyboard.nextDouble();
}
else if ( option == 2) {
quitProgram();
}
break;
default:
showError("Please Enter a Valid Option");
menu();
choice = keyboard.nextInt();
break;
}
} while(choice != 0); {
}
}
I guess I did figure my own way out but I keep thinking it isn't the correct way or there's an easier way. Plus, some errors occur when testing some inputs (mainly the the showError method calls will output either the incorrect menu or it will just close the program after so many wrong inputs).
Any help/constructive criticism would be greatly appreciated. I'm somewhat new to coding (know HTML) and new to to this site as well.
Thank you!
Bob
As it look like an exercise I won't give you a complete code, but a pseudo code to help you understand the strategy here.
To clarify, I'll name your first menu as mainMenu and the second as convMenu.
You have already implemented the good strategy for the convMenu. The idea is to make a loop, and exist only when the user tells you so. What you are missing is to do the same for the mainMenu and to think the convMenu as a sub-menu of the mainMenu. Which means when you are in the convMenu you are not outside of the mainMenu.
//That's pseudo code
do {
displayMainMenu();
readUserInput();
switch(userInput) {
case 1 :
//here you put your convMenu
do {
displayConvMenu();
readUserInput();
switch(userInput) {
case 1, 2, 3 :
doConvertion();
case 4 :
exitConvMenu = true;
default :
//wrong input display a message and loop
}
} while(!exitConvMenu)
case 2:
exitMainMenu = true;
default :
//wrong input display a message and loop
}
} while(!exitMainMenu)
Breaking down the code in little pieces usually makes it easier to understand and debug. Divide and conquer! Here is how I would do it:
First create a Menu class which represent a menu, it can print the Menu on screen and check that a choice is valid:
class Menu {
private String title;
private List<String> choices;
private String prompt;
public Menu(String title, List<String> choices, String prompt) {
this.title = title;
this.choices = choices;
this.prompt = prompt;
}
public boolean isChoiceAllowed(int i) {
return i > 0 && i <= choices.size();
}
public void show() {
System.out.println(title);
for(int i=0; i<choices.size(); i++) {
System.out.println(" " + (i+1) + ". " + choices.get(i));
}
System.out.println(prompt);
}
}
Then define your 2 menus:
private static final Menu mainMenu = new Menu(
"Main Menu",
Arrays.asList("Enter Distance", "Quit the program"),
"Please enter your choice");
private static final Menu conversionMenu = new Menu(
"Conversion Menu",
Arrays.asList("Convert to kilometers", "Convert to inches", "Convert to feet", "Return"),
"Please enter your choice");
Have a method to read the user input:
private static int readUserInput() {
int input = keyboard.nextInt();
// Check if input is valid, if not call back readUserInput() until a valid input is given
if(!currentMenu.isChoiceAllowed(input)) {
System.out.println("Please Enter a valid option");
return readUserInput();
}
return input;
}
Have a method to handle choices in the Main Menu
private static void handleMainMenuChoice(int choice) {
switch (choice) {
case 1:
System.out.println("\nEnter a Distance in Meters:");
meters = keyboard.nextDouble();
// Set the current menu to be the Conversion Menu
currentMenu = conversionMenu;
break;
case 2:
quitProgram();
break;
}
}
Have a method to handle choices in the Conversion Menu
private static void handleConversionMenuChoice(int choice) {
switch (choice) {
case 1:
showKilometers(meters);
break;
case 2:
showInches(meters);
break;
case 3:
showFeet(meters);
break;
case 4:
// Set the current menu to be the Main Menu
currentMenu = mainMenu;
break;
}
}
Have a method to handle the user choice and dispatch it to the appropriate method above:
private static void handleChoice(int choice) {
if(currentMenu == mainMenu) {
handleMainMenuChoice(choice);
} else {
handleConversionMenuChoice(choice);
}
}
Then tie it up together:
private static double meters;
private static Menu currentMenu;
private static Scanner keyboard = new Scanner(System.in);
<Insert menu definitions here>
public static void main(String[] args) {
currentMenu = mainMenu;
int choice;
while (true) {
// Show the current menu
currentMenu.show();
// Read the user input
choice = readUserInput();
// Handle the user choice
handleChoice(choice);
}
}
public static void main(String[] args) {
int choice = 0;
int option;
double meters = 0;
Scanner keyboard = new Scanner(System.in);
boolean exit = false;
while(!exit) {
System.out.println("\nEnter your choice :Enter Distance.. click1\r\n" +
"\r\n" +
"Quit the program.. click2");
choice = keyboard.nextInt();
switch (choice) {
case 1:
System.out.println("\nEnter a Distance in Meters:");
meters = keyboard.nextDouble();
System.out.println("Conversion Menu\r\n" +
"\r\n" +
"Convert to kilometers .. click1\r\n" +
"\r\n" +
"Convert to inches .. click2\r\n" +
"\r\n" +
"Convert to feet .. click3\r\n" +
"\r\n" +
"Return.... .. click4");
int choice1 = keyboard.nextInt();
switch(choice1) {
case 1:
showKilometers(meters);
break;
case 2:
showInches(meters);
break;
case 3:
showFeet(meters);
break;
case 4:
exit = true;
break;
}
break;
case 2:
exit = true;
break;
default:
break;
}
}
}
I need to make atm machine for school project.
I finished all and all is working fine, and i make the validation for the pin because it is string. So my problem is how to make validation for all other methods to check if anything else but numbers is entered to say the user that is wrong and to return him on the start of that method. All variables are stored into array as integers.
So here is my code please help i tried so many things and i cant make it work..
public class Banka {
static Scanner skener = new Scanner(System.in);
static String pin[] = {"1234","2345","3456","4567","5678"};
static String username[] = {"Mate","Nathan","John","Michelle","Angelina"};
static int balance[] = {200,100,250,150,300};
static boolean overdraft[] = {true,true,false,true,false};
static int index;
public static void main(String[] args) {
login();
}
public static void login() {
Date datum = new Date();
System.out.println("" +datum);
System.out.println("------------------------------");
System.out.println("Welcome to the Illuminati Bank \n Please log in with your PIN");
String login = skener.next();
checkpin(login);
for (int i = 0; i< pin.length; i++) {
if (login.matches(pin[i])) {
index = i;
System.out.println("\nWelcome " + username[index]);
Menu();
}
}
System.out.println("Wrong PIN entered, please login again \n");
login();
}
public static void Menu() {
System.out.println("Please select an option");
System.out.println("\n 1.View Bank Statement \n 2.Deposit \n 3.Withdraw \n 4.Change Pin \n 5.Exit \n");
int choice = skener.nextInt();
switch (choice) {
case 1: statement();
break;
case 2: deposit();
break;
case 3: withdraw();
break;
case 4: change();
break;
case 5: exit();
break;
default: System.out.println("Incorrect Choice ");
Menu();
}
}
public static void statement() {
switch(index) {
case 0: case 1: case 2: case 3: case 4:
System.out.println("" +username[index]+ ", your balance is: " +balance[index]+ "€");
if (overdraft[index] == true) {
System.out.println("You are entitled to overdraft");
}
else {
System.out.println("You are NOT entitled to overdraft");
}
Menu();
}
}
public static void deposit() {
System.out.println("" +username[index]+ ", how much you wish to deposit?");
int deposit = skener.nextInt();
balance[index] = balance[index] + deposit;
System.out.println("Thank you, you deposited " +deposit+ "€, now you have " +balance[index]+ "€ total");
depositm();
}
public static void depositm(){
System.out.println("\n 1.Deposit more \n 2.Exit to menu");
int more = skener.nextInt();
switch (more) {
case 1: deposit();
break;
case 2: Menu();
default: System.out.println("Wrong choice, please choose again");
depositm();
}
}
public static void withdraw() {
System.out.println("" +username[index]+ ", how much you wish to withdraw?");
int withdraw = skener.nextInt();
if (overdraft[index] == true) {
balance[index] = balance[index] - withdraw;
System.out.println("Thank you, you withdrawed the money, now you have " +balance[index]+ "€");
Menu();
}
if(overdraft[index] == false && balance[index] >= withdraw)
{balance[index] = balance[index] - withdraw;
System.out.println("Thank you, you withdrawed the money, now you have " +balance[index]+ "€");
Menu();
}
else {
System.out.println("You have insufficient funds \nPlease try again");
withdraw();
}
}
public static void change() {
System.out.println("" +username[index]+ ", do you want to change your pin?");
System.out.println("Press 1 to change or 2 to exit to menu");
int change = skener.nextInt();
switch (change) {
case 1: System.out.println("Please enter new PIN");
pin[index] = skener.next();
System.out.println("You successfully changed your PIN");
Menu();
case 2: System.out.println("Your PIN remains unchanged");
Menu();
default: System.out.println("Wrong choice, please choose again");
change();
}
}
public static void exit(){
System.out.println("Goodbye " +username[index]+ ", Illuminati Bank wish you all the best \n");
login();
}
public static int checkpin(String x){
while(!x.matches("\\d{4}")){
System.err.println("\n Error.\n Please enter 4 digit pin.");
login();
}
return 0;
}
}
so if any one can help me how to validate all other methods with user inputs where is INTs that would be great.
Try this
String input = "xxxx";
int pin;
try{
pin = Integer.parseInt(input);
}catch(NumberFormatException e){
// input contains letters or symbols.
}
Or here's another one using the Character class.
String input = "xxxx";
boolean allDigits = true;
for(char ch: input.toCharArray()){
if(!Character.isDigit(ch)) {
allDigits = false;
break;
}
}
if(allDigits){
// input contains only digits.
}
Edit: Answering this comment.
You can modify your method like this,
public static void checkpin(String x) {
if (x.length() == 4) {
try {
Integer.parseInt(x);
login();
} catch (NumberFormatException e) {
System.err.println("\n Error.\n Invalid pin.");
}
} else {
System.err.println("\n Error.\n Please enter 4 digit pin.");
}
}
this way the method login() is called only if the pin has 4 digits and all the digits are numbers.
I have this program that asks user to enter a value and it calculates it as the user like to initial value of zero, then it ask the user what process to do again and ask the user to enter a value again and it calculates it to the last value of the instance, the problem is every time it asks the user to enter value it calculates it to zero not to the last entry. Please help me find the bug:
The program has to has two classes, one for the calculator and the other for the methods:
FIRST CLASS
public class MainClass {
public static void main(String[] args) {
MemoryCalculator calc = new MemoryCalculator();
calc.getCurrentValue();
displayMenu();
}
public static int displayMenu() {
Scanner input = new Scanner(System.in);
int choice;
do {
System.out.println("Menu");
System.out.println("1.Add");
System.out.println("2.Subtract");
System.out.println("3.Multiply");
System.out.println("4.Divide");
System.out.println("5.Clear");
System.out.println("6.Quit");
System.out.println("");
System.out.println("What would you like to do?");
choice = input.nextInt();
if (choice > 6 || choice < 1) {
System.out.println("Sorry," + choice + " was not an option");
return displayMenu();
}
} while (choice > 6 || choice < 1);
MemoryCalculator calc = new MemoryCalculator();
if (choice == 5) {
calc.clear();
return 0;
} else if (choice == 6) {
System.out.println("Goodbye! ");
System.exit(0);
}
System.out.println("What is the second number? ");
double operand2 = input.nextDouble();
switch (choice) {
case 1:
calc.add(operand2);
break;
case 2:
calc.subtract(operand2);
break;
case 3:
calc.multiply(operand2);
break;
case 4:
calc.divide(operand2);
break;
}
return displayMenu();
}
public static double getOperand(String prompt) {
return 0;
}
}
SECOND CLASS
public class MemoryCalculator {
private double currentValue;
public double getCurrentValue() {
System.out.println("The current value is " + currentValue);
return 0;
}
public void add(double operand2) {
currentValue = currentValue + operand2;
getCurrentValue();
}
public void subtract(double operand2) {
currentValue -= operand2;
getCurrentValue();
}
public void multiply(double operand2) {
currentValue *= operand2;
getCurrentValue();
}
public void divide(double operand2) {
if (operand2 == 0) {
System.out.println("Sorry, you can not divide by 0");
}
currentValue /= operand2;
getCurrentValue();
}
public void clear() {
currentValue = 0;
getCurrentValue();
}
}
You probably want to keep the last value stored in "calc". I see 3 bugs.
Move this line before the start of your "do" loop. This will keep it from reseting the value inside this variable/class.
MemoryCalculator calc = new MemoryCalculator();
Move your ending "while" loop line to the bottom of your method(right before the return statement). It only appears to be working because in your return statement you are calling your method again...see #3. Also you will want to change the "or" to the "and" operator in the while statement "choice>6 && choice<1"
}while(choice>6 && choice<1);
In you displayMenu method change the return statement, because you don't want it to call itself in an infinite loop... now that the do while loop is fixed.
return displayMenu();
to this
return choice;
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)