I have implemented a calculator, however, I only want the user to be able to pick two options then close the program. My code is having the user cycle through each operation. I would like the user to pick a number 1 through 6 and have it complete the operation the selected. Also if someone knows how to get the program to exit if they press 0 at the menu that would be fantastic.
import java.util.*;
public class Calculator
{
private int option = -1; // option is initially not 0
to 6
private Scanner scan; // we’ll use scan to read input
// constructor for class
public Calculator()
{
System.out.println ("java Homework1");
System.out.println ("Welcome to Math Calculator!");
System.out.println ("Please choose an option:");
System.out.println (" ");
System.out.println ("1 - add two real numbers");
System.out.println ("2 - subtract two real numbers");
System.out.println ("3 - multiply two real numbers");
System.out.println ("4 - divide two real numbers");
System.out.println ("5 - get the factorial of an
number");
System.out.println ("6 - menu");
System.out.println ("0 - exit");
scan = new Scanner(System.in); // creates scan
}
// entry point for class
public void run()
{
// stick code for calculator in here...may want to
create
// other functions to make code more readable
int selection1;
Scanner first = new Scanner(System.in);
selection1 = first.nextInt();
if (selection1 == 1);
{
System.out.println ("Enter 1st value: ");
int firstnum = scan.nextInt();
System.out.println ("Enter 2nd value: ");
int secondnum = scan.nextInt();
System.out.println ("your answer is: " + (firstnum
+ secondnum));
}
if (selection1 == 2);
{
System.out.println ("Enter 1st value: ");
int firstnum = scan.nextInt();
System.out.println ("Enter 2nd value: ");
int secondnum = scan.nextInt();
System.out.println ("your answer is: " + (firstnum
- secondnum));
}
if (selection1 == 3);
{
System.out.println ("Enter 1st value: ");
int firstnum = scan.nextInt();
System.out.println ("Enter 2nd value: ");
int secondnum = scan.nextInt();
System.out.println ("your answer is: " + (firstnum
* secondnum));
}
if (selection1 == 4);
{
System.out.println ("Enter 1st value: ");
int firstnum = scan.nextInt();
System.out.println ("Enter 2nd value: ");
int secondnum = scan.nextInt();
System.out.println ("your answer is: " + (firstnum
/ secondnum));
}
if (selection1 == 5);
System.out.println ("Enter the number you would
like the factorial of: ");
int factorialnum = scan.nextInt();
int i,start = 1;
for (i = 1; i <= factorialnum;i++)
{
start = start*i;
}
System.out.println ("your answer is: " + start);
}
}
The problem is with the if conditions. The following if condition is not correct. It will have no effect on the section following it, since it is ended with the semicolon (;)
if (selection1 == 1); //This condition will have no effect on the section following it
This is the correct way to write the if condition.
if (selection1 == 1){
//your logic here
}
Also, note the last if condition for factorial. It does not have braces for the code following it.
Code for menu options won't loop, but has no errors. I intentionally wrote it similar to my while loop that loops just fine. I have to use only integers, and my instructor did tell me to turn my inputs into variables. Most of it isn't quite finished but I'm working on that at the same time as trying to figure all this out.
//Loop to check user input
num=-1;
while (num<0)
{
//Getting user entered interger
System.out.print("Please enter a positive number: ");
num = kb.nextInt();
//Ensuring positive interger
if (num >= 0)
{
System.out.println("You've entered the number " + num + ".");
}
else
{
System.out.println("Error! The number you've entered is not a valid interger.");
}
}
copy = num;
//Printing menu loop
copy2 = -1;
do
{
//Menu making
System.out.println(" ");
System.out.println("1. Enter a new number.");
System.out.println("2. Print the number of odd digits, even digits, and zeros in the interger.");
System.out.println("3. print if the number is light or heavy.");
System.out.println("4. Print the prime numbers between 2 and the interger (inclusive).");
System.out.println("5. Quit the program.");
System.out.println(" ");
System.out.print("Please enter your menu choice: ");
choice = kb.nextInt();
copy2 =choice;
//Checking entry
if (0<copy2 && copy2<=5)
{
System.out.println("You chose option " +copy2+".");
}
//Option one
if (copy2 == 1)
{
System.out.print("Will work on soon.");
}
//Option two
if (copy2 == 2)
{
oddNum=0;
evenNum=0;
zero=0;
while (copy>0)
{
if (copy %10==0)
{
zero++;
}
else if (copy %2==1)
{
evenNum++;
}
else
{
oddNum++;
}
}
copy = copy/10;
System.out.println("Even numbers: " + evenNum+
"\nOdd numbers: "+ oddNum +
"\nZeros: " +zero );
}
//Option three
if (copy2 == 3)
{
loh = 0;
do
{
System.out.println("To check if your number is light or heavy, we need a second interger.");
System.out.print("Please enter a second positive interger: ");
loh = kb.nextInt();
if (loh >= 0)
{
numWeight = ((loh +copy)/2);
//Test num weight
System.out.println("Check: " +numWeight);
if (numWeight > copy)
{
System.out.print("The number " + copy + " compared to the number "
+ loh + " is a heavy number.");
}
else
{
System.out.print("The number " + copy + " compared to the number "
+ loh + " is a light number.");
}
}
if (loh < 0)
{
System.out.println("Error! The number you've entered is not a valid interger.");
}
}while (loh <=0);
}
//Option four
if (copy2 ==4)
{
primeNumbers = 0;
for (int i=1; i<=copy; i++)
{
int counter = 0;
for(int prime = i; prime>=1; prime--)
{
if (i%prime==0)
{
counter = counter +1;
}
}
if (counter==2)
{
primeNumbers = primeNumbers + i;
}
}
System.out.println("Prime numbers from 2-"+copy+" are: ");
System.out.println(primeNumbers);
}
//Option five
else
{
System.out.print("Error! Please enter a valid menu option.");
}
}while (copy2 <0 && copy2 >=6);
}//End main
}//End class
You should use switch case for your purpose. nested if/else isn't good idea for menu options but switch case make it more clear to understand what are you going to do.
switch (num) {
case c1:
statements // they are executed if variable == c1
System.out.println("1. Enter a new number.");
break;
case c2:
System.out.println("2. Print the number of odd digits, even digits, and zeros in the interger.");
statements // they are executed if variable == c2
break;
case c3:
case c4:
statements // they are executed if variable == any of the above c's
break;
. . .
default:
statements // they are executed if none of the above case is satisfied
break;
}
import java.util.*;
public class TestProject
{
public static void theMath()
{
double add = 1;
double subtract = 2;
double multiply = 3;
double divide = 4;
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
//Pick first number
System.out.println("Please enter a number: ");
int intOne = input.nextInt();
// Pick second number
System.out.println("Please enter another number: ");
int intTwo = input.nextInt();
//User chooses operator
System.out.println("Now please choose an operator (1 for add, 2 for subtract, 3 for mulitply, 4 for divide): ");
int userChoice = input.nextInt();
// Add
if (userChoice == add)
System.out.println("Your answer is: " + (intOne + intTwo));
// Subtract
else if (userChoice == subtract)
System.out.println("Your answer is: " + (intOne - intTwo));
// Multiply
else if (userChoice == multiply)
System.out.println("Your answer is: " + (intOne * intTwo));
// Divide
else if (userChoice == divide)
System.out.println("Your answer is: " + (intOne / intTwo));
// If wrong input
else
{
System.out.println("Nothing happens!");
System.out.println("Please make sure you entered a number and an operator.");
}
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
theMath();
System.out.println("Would you like to do another calculation?");
String redo = input.nextLine();
if(redo.equals("yes"))
theMath();
else if(redo.equals("no"))
System.out.println("Thanks for calculating with me! It certainly was fun!");
else
System.out.println("Please enter 'yes' or 'no' only.");
String yesNo = input.nextLine();
if(yesNo.equals("yes"))
theMath();
else
System.out.println("Thanks for calculating with me! It certainly was fun!");
}
}
I was wondering how I could recall the main method an infinite amount of times if I wanted to. What I was doing was just copying and pasting it over and over again but there has to be a better way. And also, I would like to know how to return a value has a decimal(so I could do 25/6 and get the correct answer).
Why not put only the statements that should be repeated inside a loop?
String redo;
do{
System.out.println("Would you like to do another calculation?");
redo = input.nextLine();
if(redo.equals("yes"))
theMath();
else if(redo.equals("no"))
System.out.println("Thanks for calculating with me! It certainly was fun!");
else
System.out.println("Please enter 'yes' or 'no' only.");
String yesNo = input.nextLine();
if(yesNo.equals("yes"))
theMath();
else
System.out.println("Thanks for calculating with me! It certainly was fun!");
}while(redo.equals("yes"))
As for the other part of your question. If you have two int values and want to get a decimal from a division, you can do it like this:
int x = 2;
int y = 3;
double result = (double)x/y;
System.out.println(result);
This is called casting.
sorry for asking such an in depth question, but I'm very lost. I am working on a problem and I am stuck. I am supposed to make a basic menu driven calculator that add, subtract, multiply, divide, or generate a random number between an upper and lower limit. I made that without too much difficulty, but now I need to change it so that after it performs an operation it starts over again and displays the menu. Also, if I enter an invalid response, it needs to let them try again until they enter a valid one UNLESS they enter an invalid response THREE TIMES IN A ROW; then it needs to display a message about trying again later and exiting the program. This is there I am stuck. I have tried every combination of for and while in the following code but i can not get this to work. I would really appreciate any pointers.
Here are the requirements:
The menu is repeatedly displayed until a valid option is entered
If the user enters three invalid choices in a row, the program ends
If the user enters two invalid choices, then a valid one, then another invalid one, the program does NOT end
The program computes the correct answers for each menu option
The program continues after a valid operation by re-displaying the menu
The program ends when the user chooses the Quit option from the menu
• The program does not end on division by zero – just display an error message and allow the user to retry
And here is what i have thus far.
import java.util.Scanner;
public class BasicCalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double numONE = 0.0;
double numTWO = 0.0;
double upperLimit = 0.0;
double lowerLimit = 0.0;
System.out.println("MENU");
System.out.println("1. +");
System.out.println("2. -");
System.out.println("3. *");
System.out.println("4. /");
System.out.println("5. Generate a random number.");
System.out.println("6. Quit");
System.out.println("What would you like to do?");
int menuSelect = input.nextInt();
//Selects an item from the menu
if(menuSelect == 1 || menuSelect == 2 || menuSelect == 3 || menuSelect == 4){
System.out.println("Enter first number.");
numONE = input.nextDouble();
//Stores input as numONE
System.out.println("Enter second number.");
numTWO = input.nextDouble();
//Stores input as numTWO
}
if(menuSelect == 1){
System.out.println(numONE + numTWO);
//Adds two numbers
}
else if(menuSelect == 2){
System.out.println(numONE - numTWO);
//Subtracts second number from first number
}
else if(menuSelect == 3){
System.out.println(numONE * numTWO);
//Multiplies two numbers
}
else if(menuSelect == 4){
if(numTWO != 0){
System.out.println(numONE / numTWO);
//Divides first number by second number
}
else if(numTWO == 0){
System.out.println("I'm sorry, you cannot divide by zero.");
}
}
else if(menuSelect == 5){
System.out.println("Enter upper limit.");
upperLimit = input.nextDouble();
System.out.println("Enter lower limit.");
lowerLimit = input.nextDouble();
double randomVal = (lowerLimit + (int)(Math.random() * ((upperLimit - lowerLimit)+1)));
System.out.println(randomVal);
//Displays a random integer between an upper and a lower limit
}
else if(menuSelect==6){
System.out.println("Goodbye");
System.exit(0);
}
else{
System.out.println("Sorry, "+menuSelect+" is not an option.");
}
}
}
Look at lines I added ( // <- new code )
import java.util.Scanner;
public class BasicCalculator {
public static void main(String[] args) {
int counter_WrongAttempts = 0; // <- new code
boolean flag_Quit = false; // <- new code
while (!flag_Quit) { // <- new code
boolean wrongAttempt = false; // <- new code
Scanner input = new Scanner(System.in);
double numONE = 0.0;
double numTWO = 0.0;
double upperLimit = 0.0;
double lowerLimit = 0.0;
System.out.println("MENU");
System.out.println("1. +");
System.out.println("2. -");
System.out.println("3. *");
System.out.println("4. /");
System.out.println("5. Generate a random number.");
System.out.println("6. Quit");
System.out.println("What would you like to do?");
int menuSelect = input.nextInt();
//Selects an item from the menu
if(menuSelect == 1 || menuSelect == 2 || menuSelect == 3 || menuSelect == 4){
System.out.println("Enter first number.");
numONE = input.nextDouble();
//Stores input as numONE
System.out.println("Enter second number.");
numTWO = input.nextDouble();
//Stores input as numTWO
}
if(menuSelect == 1){
System.out.println(numONE + numTWO);
//Adds two numbers
}
else if(menuSelect == 2){
System.out.println(numONE - numTWO);
//Subtracts second number from first number
}
else if(menuSelect == 3){
System.out.println(numONE * numTWO);
//Multiplies two numbers
}
else if(menuSelect == 4){
if(numTWO != 0){
System.out.println(numONE / numTWO);
//Divides first number by second number
}
else if(numTWO == 0){
System.out.println("I'm sorry, you cannot divide by zero.");
}
}
else if(menuSelect == 5){
System.out.println("Enter upper limit.");
upperLimit = input.nextDouble();
System.out.println("Enter lower limit.");
lowerLimit = input.nextDouble();
double randomVal = (lowerLimit + (int)(Math.random() * ((upperLimit - lowerLimit)+1)));
System.out.println(randomVal);
//Displays a random integer between an upper and a lower limit
}
else if(menuSelect==6){
System.out.println("Goodbye");
System.exit(0);
flag_Quit = true; // <- new code
}
else{
System.out.println("Sorry, "+menuSelect+" is not an option.");
wrongAttempt = true; // <- new code
}
if (wrongAttempt) // <- new code
counter_WrongAttempts++; // <- new code
else // <- new code
counter_WrongAttempts = 0; // <- new code
flag_Quit = flag_Quit || (counter_WrongAttempts >= 3); // <- new code
}
}
}
This isn't about a 'for loop inside a while loop', you don't even need it.
Imagine the following pseudo-code:
int invalidOptions = 0;
while ( invalidOptions < 3 ) {
// show menu
displayMenu();
// read option
int input = readInput();
// validate input
if ( isInputValid(input) ) {
// check whether the user wants to exit or not
if (input == EXIT_INPUT) {
break;
}
// handle other commands
handleInput(input);
} else {
// input is invalid
invalidOptions++;
}
}
That's all you need, it's better to split your program into smaller pieces, it will be easier to maintain and understand.
First things first, you don't really need four variables for this program. Since you are always taking two numbers as input you can easily store them in two variables, instead of having different variable names for each case.
As mentioned above, you don't need such complex loop nesting. A simple while that checks the number of errors is less than 3 will do just fine. Also, you seem to work well with the System.out.println() command, but for some applications, like input, it may be better to work with System.out.print(), it's basically the same but does not start a new line. Try the code below to see the results.
Another thing you might consider is using a switch sentence instead of the if, else if, else if statements.
import java.util.Scanner;
public class BasicCalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double firstNumber = 0.0;
double secondNumber = 0.0;
//New variable
int errors = 0;
while (errors < 3) {
System.out.println("MENU");
System.out.println("1. +");
System.out.println("2. -");
System.out.println("3. *");
System.out.println("4. /");
System.out.println("5. Generate a random number.");
System.out.println("6. Quit");
System.out.println("What would you like to do?");
System.out.print("> ");
int menuSelect = input.nextInt();
//Selects an item from the menu
if(menuSelect == 1 || menuSelect == 2 || menuSelect == 3 || menuSelect == 4) {
errors = 0;
System.out.print("Enter first number: ");
firstNumber = input.nextDouble();
//Stores input as the firstNumber
System.out.print("Enter second number: ");
secondNumber = input.nextDouble();
//Stores input as the secondNumber
}
if(menuSelect == 1){
System.out.println(firstNumber + secondNumber);
//Adds two numbers
}
else if(menuSelect == 2){
System.out.println(firstNumber - secondNumber);
//Subtracts second number from first number
}
else if(menuSelect == 3){
System.out.println(firstNumber * secondNumber);
//Multiplies two numbers
}
else if(menuSelect == 4){
if(secondNumber != 0){
System.out.println(firstNumber / secondNumber);
//Divides first number by second number
}
else if(secondNumber == 0){
System.out.println("I'm sorry, you cannot divide by zero.");
}
}
else if(menuSelect == 5){
errors = 0;
System.out.print("Enter upper limit: ");
firstNumber = input.nextDouble();
System.out.print("Enter lower limit: ");
secondNumber = input.nextDouble();
double randomVal = (firstNumber + (int)(Math.random() * ((firstNumber - secondNumber)+1)));
System.out.println(randomVal);
//Displays a random integer between an upper and a lower limit
}
else if (menuSelect==6){
System.out.println("Goodbye");
System.exit(0);
}
else{
errors++;
System.out.println("Sorry, "+ menuSelect + " is not an option.");
}
}
input.close();
System.out.println("Program will exit now");
}
}
int unvalid = 0;
while (unvalid < 3)
{
//read stuff
if ([stuff is valid])
{
unvalid = 0;
}
else
{
unvalid++;
}
}
You probably don't want a for loop inside a while loop to handle this. I would just have a variable to track how many invalid inputs you've received, increment it when they enter something invalid, reset it to zero if they enter something valid, and kick them out if it gets too high.
eg:
import java.util.Scanner;
public class BasicCalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double numONE = 0.0;
double numTWO = 0.0;
double upperLimit = 0.0;
double lowerLimit = 0.0;
int invalid = 0;
System.out.println("MENU");
System.out.println("1. +");
System.out.println("2. -");
System.out.println("3. *");
System.out.println("4. /");
System.out.println("5. Generate a random number.");
System.out.println("6. Quit");
System.out.println("What would you like to do?");
int menuSelect = input.nextInt();
//Selects an item from the menu
while(invalid < 3){
if(menuSelect == 1 || menuSelect == 2 || menuSelect == 3 || menuSelect == 4){
System.out.println("Enter first number.");
numONE = input.nextDouble();
//Stores input as numONE
System.out.println("Enter second number.");
numTWO = input.nextDouble();
//Stores input as numTWO
invalid = 0;
}
if(menuSelect == 1){
System.out.println(numONE + numTWO);
//Adds two numbers
}
else if(menuSelect == 2){
System.out.println(numONE - numTWO);
//Subtracts second number from first number
}
else if(menuSelect == 3){
System.out.println(numONE * numTWO);
//Multiplies two numbers
}
else if(menuSelect == 4){
if(numTWO != 0){
System.out.println(numONE / numTWO);
//Divides first number by second number
}
else if(numTWO == 0){
System.out.println("I'm sorry, you cannot divide by zero.");
}
}
else if(menuSelect == 5){
System.out.println("Enter upper limit.");
upperLimit = input.nextDouble();
System.out.println("Enter lower limit.");
lowerLimit = input.nextDouble();
double randomVal = (lowerLimit + (int)(Math.random() * ((upperLimit - lowerLimit)+1)));
System.out.println(randomVal);
//Displays a random integer between an upper and a lower limit
invalid = 0;
}
else if(menuSelect==6){
System.out.println("Goodbye");
System.exit(0);
}
else{
System.out.println("Sorry, "+menuSelect+" is not an option.");
invalid++;
}
}
System.out.println("Too many invalid inputs. Try again later");
}
}
I have this programming assignment that converts between meters and feet, and between kilograms and pounds. When I tell the program I want to convert weight (by entering "w" when prompted), it gives me my the following error:
Error: Too many input characters error.
I worked on this for a long time, but can't figure it out. Can someone please tell me how to make the weight conversion work like the length conversion?
import java.util.Scanner;
/**
* This class..
*/
public class UnitConversion3b
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String maxInputWarning = "\nError: Too many input characters."
+ "\nProgram is now terminating.";
String lengthOrWeight;
final double LENGTH_CONVERSION_FACTOR = 3.2808399;
final double WEIGHT_CONVERSION_FACTOR = 2.20462;
String whichWeightConversion = "empty" , whichLengthConversion = "empty";
double feet = 0, meters = 0, pounds =0 , kilograms = 0;
double metersConvertedToFeet, feetConvertedToMeters;
double poundsConvertedToKilograms, kilogramsConvertedToPounds;
System.out.println("");
System.out.print("What kind of value would you like to convert?");
System.out.print("\nEnter L for length, or W for weight: ");
lengthOrWeight = keyboard.nextLine();
if (lengthOrWeight.length() > 1 ) {
System.out.println(maxInputWarning);
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
} else if ((!(lengthOrWeight.equalsIgnoreCase("l"))
&& (!(lengthOrWeight.equalsIgnoreCase("w"))))){
System.out.println("\nError: Unrecognized conversion type."
+ "\nProgram is now terminating.");
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
} else if (lengthOrWeight.equalsIgnoreCase("l")){
System.out.println("\nConverting feet or meters?");
System.out.print("Enter F to convert feet, or M for meters: ");
whichLengthConversion = keyboard.nextLine();
}
if (whichLengthConversion.length() > 1 ) {
System.out.println(maxInputWarning);
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
} else if ((!(whichLengthConversion.equalsIgnoreCase("f"))
&& (!(whichLengthConversion.equalsIgnoreCase("m"))))){
System.out.println("\nError: Unrecognized unit of "
+ "measurement.\nProgram is now terminating." );
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
} else if (whichLengthConversion.equalsIgnoreCase("f")){
System.out.print ("Enter the number of feet to"
+ " convert to meters: ");
feet = keyboard.nextDouble();
feetConvertedToMeters = feet / LENGTH_CONVERSION_FACTOR;
System.out.println("The number of meters in " + feet +
" feet is " + feetConvertedToMeters + ".");
keyboard.nextLine();
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
} else if (whichLengthConversion.equalsIgnoreCase("m")){
System.out.print ("Enter the number of meters to"
+ " convert to feet: ");
meters = keyboard.nextDouble();
metersConvertedToFeet = meters * LENGTH_CONVERSION_FACTOR;
System.out.println("The number of feet in " + meters +
" meters is " + metersConvertedToFeet + ".");
keyboard.nextLine();
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
}
if (lengthOrWeight.equalsIgnoreCase("w")){
System.out.println("Converting pounds or kilograms?");
System.out.print("Enter P to convert pounds, or K for kilograms: ");
whichWeightConversion = keyboard.nextLine();
}
if (whichWeightConversion.length() > 1 ) {
System.out.println(maxInputWarning);
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
} else if ((!(whichWeightConversion.equalsIgnoreCase("p"))
&& (!(whichWeightConversion.equalsIgnoreCase("k"))))){
System.out.println("\nError: Unrecognized unit of "
+ "measurement.\nProgram is now terminating." );
System.out.print("Press Enter to continue ... ");
return;
} else if (whichWeightConversion.equalsIgnoreCase("p")){
System.out.println("Enter the number of pounds to"
+ " convert to kilograms:");
pounds = keyboard.nextDouble();
poundsConvertedToKilograms = pounds / WEIGHT_CONVERSION_FACTOR;
System.out.println("The number of pounds in " + kilograms +
" kilograms is " + poundsConvertedToKilograms + ".");
keyboard.nextLine();
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
} else if (whichLengthConversion.equalsIgnoreCase("k")){
System.out.print ("Enter the number of kilograms to"
+ " convert to pounds: ");
kilograms = keyboard.nextDouble();
kilogramsConvertedToPounds = kilograms * WEIGHT_CONVERSION_FACTOR;
System.out.println("The number of pounds in " + pounds +
"pounds is " + kilogramsConvertedToPounds + ".");
keyboard.nextLine();
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
} else{
return;
}
}
}
You made lots of errors by not changing the code while copy pasting the logic from one place to the other. Your code can be improved a lot by reducing the repetitions and I will be more optimistic in my 'if' 'else' conditions to capture the right cases first and leaving all the wrong cases to the end...Below is the working version of your code modified slightly by fixing the typos and order of the logic.
import java.util.Scanner;
public class UnitConversion3b {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String maxInputWarning = "\nError: Too many input characters."
+ "\nProgram is now terminating.";
String lengthOrWeight;
final double LENGTH_CONVERSION_FACTOR = 3.2808399;
final double WEIGHT_CONVERSION_FACTOR = 2.20462;
String whichWeightConversion = "empty", whichLengthConversion = "empty";
double feet = 0, meters = 0, pounds = 0, kilograms = 0;
double metersConvertedToFeet, feetConvertedToMeters;
double poundsConvertedToKilograms, kilogramsConvertedToPounds;
System.out.println("");
System.out.print("What kind of value would you like to convert?");
System.out.print("\nEnter L for length, or W for weight: ");
lengthOrWeight = keyboard.nextLine();
if (lengthOrWeight.length() > 1) {
System.out.println(maxInputWarning);
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
} else if ((!(lengthOrWeight.equalsIgnoreCase("l")) && (!(lengthOrWeight
.equalsIgnoreCase("w"))))) {
System.out.println("\nError: Unrecognized conversion type."
+ "\nProgram is now terminating.");
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
} else if (lengthOrWeight.equalsIgnoreCase("l")) {
System.out.println("\nConverting feet or meters?");
System.out.print("Enter F to convert feet, or M for meters: ");
whichLengthConversion = keyboard.nextLine();
if (whichLengthConversion.length() > 1) {
System.out.println(maxInputWarning);
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
} else if ((!(whichLengthConversion.equalsIgnoreCase("f")) && (!(whichLengthConversion
.equalsIgnoreCase("m"))))) {
System.out.println("\nError: Unrecognized unit of "
+ "measurement.\nProgram is now terminating.");
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
} else if (whichLengthConversion.equalsIgnoreCase("f")) {
System.out.print("Enter the number of feet to"
+ " convert to meters: ");
feet = keyboard.nextDouble();
feetConvertedToMeters = feet / LENGTH_CONVERSION_FACTOR;
System.out.println(feet + " Feet in Meters is "
+ feetConvertedToMeters + ".");
keyboard.nextLine();
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
} else if (whichLengthConversion.equalsIgnoreCase("m")) {
System.out.print("Enter the number of meters to"
+ " convert to feet: ");
meters = keyboard.nextDouble();
metersConvertedToFeet = meters * LENGTH_CONVERSION_FACTOR;
System.out.println(meters + " Meters in Feet is "
+ metersConvertedToFeet + ".");
keyboard.nextLine();
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
}
}
else {
System.out.println("Converting pounds or kilograms?");
System.out.print("Enter P to convert pounds, or K for kilograms: ");
whichWeightConversion = keyboard.nextLine();
if (whichWeightConversion.length() > 1) {
System.out.println(maxInputWarning);
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
} else if ((!(whichWeightConversion.equalsIgnoreCase("p")) && (!(whichWeightConversion
.equalsIgnoreCase("k"))))) {
System.out.println("\nError: Unrecognized unit of "
+ "measurement.\nProgram is now terminating.");
System.out.print("Press Enter to continue ... ");
return;
} else if (whichWeightConversion.equalsIgnoreCase("p")) {
System.out.println("Enter the number of pounds to"
+ " convert to kilograms:");
pounds = keyboard.nextDouble();
poundsConvertedToKilograms = pounds / WEIGHT_CONVERSION_FACTOR;
System.out.println(pounds + " Pounds in Kilograms is "
+ poundsConvertedToKilograms + ".");
keyboard.nextLine();
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
} else if (whichWeightConversion.equalsIgnoreCase("k")) {
System.out.print("Enter the number of kilograms to"
+ " convert to pounds: ");
kilograms = keyboard.nextDouble();
kilogramsConvertedToPounds = kilograms
* WEIGHT_CONVERSION_FACTOR;
System.out.println(kilograms + " Kilograms in Pounds is "
+ kilogramsConvertedToPounds + ".");
keyboard.nextLine();
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
}
}
}
}
You're missing a right curly-brace after your meters-to-feet case.
There are some other curly-brace issues throughout your code -- for example, on line 47, there's a right brace where you don't want one. Check over your block structure and, in each case, make sure you're opening and closing blocks where it makes logical sense to do so.
My professor makes us seperate our main class from the Class that is doing the work. It helps a lot. I know it seems like a lot of extra work, but if you pulled your SOPs/inputs out into a DemoMain class and then had your UnitConversion3b class seperate it would be a lot easier to read. Also, I know a lot of people put their {'s right after the close of a paren, but honestly I find my own code a lot easier to read if I drop my opening { down a line. I think your logic is good statement wise, but it's so hard to tell with the brace issues. I think you have some hanging if issues, where you mean to have some of the statements inside a conditional but they are actually outside :-/
Try getting rid of
(!(lengthOrWeight.equalsIgnoreCase("l"))
&& (!(lengthOrWeight.equalsIgnoreCase("w"))))){
and just putting the following block in the else
else{
System.out.println("\nError: Unrecognized conversion type."
+ "\nProgram is now terminating.");
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
}
It might not help but it will make things clearer.
Also you don't need to check length when you can do line.equalsIgnoreCase("l"), if the input is longer it will not be equal.
The reason why it gives you that error is because Scanner's nextLine() method returns the line as well as the newline character ('\n') that ends the line.
Try this line instead, using String's trim() method to cut off all whitespace from either end :
lengthOrWeight = keyboard.nextLine().trim();
OK, so here is an example of two classes, a main demo class and the actual working class:
TestMain.java goes like this:
import java.util.Scanner;
public class TestMain
{
public static void main(String[] args)
{
float theValue;
float theAnswerIs;
char getLengthOrWeight;
String theValueAsString;
boolean lOrW; //length or width
boolean fOrM; //feet or meters
boolean pOrK; //pounds or kilos... it's a CS joke haha
char getFeetOrMeters;
char getPoundsOrKilos;
//Set up a Scanner instance called keyboard
Scanner keyboard = new Scanner(System.in);
UnitConversion3b converterInstance = new UnitConversion3b();
//Request user for the number to convert
System.out.println("What is the value you will be converting?");
theValueAsString = keyboard.nextLine();
//convert that value and trap
theValue = floatToString(theValueAsString);
//Request user for length or weight conversion
System.out.println("What kind of value would you like to convert?");
System.out.println("Enter L for length, or W for weight: ");
//variable = console.next().charAt(0);
getLengthOrWeight = keyboard.next().charAt(0);
lOrW = converterInstance.lengthOrWeight(getLengthOrWeight);
//create a new UnitConversion3B object and pass it the L or W or bad string the user inputs
//if(true) then user asked for length
if(lOrW)
{
System.out.println("\nConverting feet or meters?");
System.out.print("Enter F to convert feet to meters, or M for meters to feet: ");
//set our main's feetOrMeters variable to the value received when we ask our
//converterInstance the question whichLengthConversion?
getFeetOrMeters = keyboard.next().charAt(0);
fOrM = converterInstance.feetOrMeters(getFeetOrMeters);
//if(fOrM) aka user asked for a length conversion in feet, let's convert it:
if(fOrM)
{
theAnswerIs = (float) (theValue * 3.28083);
System.out.println("The answer is: " + theAnswerIs + " feet.");
}
//if(!fOrM) aka user asked for a length conversion in meters, let's convert it:
if(!fOrM)
{
theAnswerIs = (float) (theValue * 0.3048);
System.out.println("The answer is: " + theAnswerIs + " feet.");
}
//bad input should be trapped in the feetOrMeters function of the converterInstance
}
//if(false) then user asked for weight
else if(!lOrW)
{
System.out.println("Converting pounds or kilograms?");
System.out.print("Enter P to convert pounds to kilos, or K for kilograms to pounds: ");
getPoundsOrKilos = keyboard.next().charAt(0);
pOrK = converterInstance.poundsOrKilos(getPoundsOrKilos);
//if(pOrK) aka user asked for a pounds to kilos conversion, let's convert it:
if(pOrK)
{
theAnswerIs = (float) (theValue * 0.45359237);
System.out.println("The answer is: " + theAnswerIs + " feet.");
}
//if(!pOrK) aka user asked for a kilos to pounds conversion, let's convert it:
if(!pOrK)
{
theAnswerIs = (float) (theValue * 2.20462262);
System.out.println("The answer is: " + theAnswerIs + " feet.");
}
//bad input should be trapped in the poundsOrKilos function of the converterInstance
}
}
private static float floatToString(String theValueAsString) {
// thanks for this method from http://devdaily.com/java/edu/qanda/pjqa00013.shtml
float f = 0;
try
{
f = Float.valueOf(theValueAsString.trim()).floatValue();
}
catch (NumberFormatException nfe)
{
System.out.println("NumberFormatException: " + nfe.getMessage());
}
return f;
}
}
and UnitConversion3b.java goes like:
public class UnitConversion3b
{
private boolean lengthOrWeightSwitch;
boolean feetOrMeters;
final double LENGTH_CONVERSION_FACTOR = 3.2808399;
final double WEIGHT_CONVERSION_FACTOR = 2.20462;
boolean poundsOrKilograms;
public UnitConversion3b(String getLengthOrWeight) {
if(getLengthOrWeight == "W")
lengthOrWeightSwitch = true;
else if(getLengthOrWeight == "L")
lengthOrWeightSwitch = false;
else
{
badInput();
}
}
public boolean getConversionType()
{
return lengthOrWeightSwitch;
}
public boolean whichLengthConversion(String whichLength)
{
if(whichLength == "F")
feetOrMeters = true;
else if(whichLength == "M")
feetOrMeters = false;
else
{
badInput();
}
return feetOrMeters;
}
public boolean whichWeightConversion(String whichWeight)
{
if(whichWeight == "P")
poundsOrKilograms = true;
else if(whichWeight == "K")
poundsOrKilograms = false;
else
{
badInput();
}
return poundsOrKilograms;
}
public void badInput()
{
System.out.println("Invalid input");
System.exit(0);
}
public String valueToFeet(float theValue) {
//assumes value entered need to be converted from meters to feet
return "" + (theValue*LENGTH_CONVERSION_FACTOR);
}
public String valueToMeters(float theValue) {
//assumes value entered need to be converted from feet to meters
return "" + (theValue/LENGTH_CONVERSION_FACTOR);
}
public String valueToPounds(float theValue) {
// assumes value entered needs to be converted to pounds
return ""+ (theValue * WEIGHT_CONVERSION_FACTOR);
}
public String valueToKilos(float theValue) {
// TODO Auto-generated method stub
return ""+ (theValue / WEIGHT_CONVERSION_FACTOR);
}
public void setConversionType(char getLengthOrWeight) {
if(getLengthOrWeight == 'L')
lengthOrWeightSwitch = true;
if(getLengthOrWeight == 'W')
lengthOrWeightSwitch = false;
else
badInput();
}
public boolean lengthOrWeight(char getLengthOrWeight) {
if(getLengthOrWeight == 'L')
return true;
if(getLengthOrWeight == 'W')
return false;
return false;
}
public boolean feetOrMeters(char getFeetOrMeters) {
if(getFeetOrMeters == 'F')
return true;
if(getFeetOrMeters == 'M')
return false;
//these functions return false under 'false' conditions... work on the logic :-)
return false;
}
public boolean poundsOrKilos(char getPoundsOrKilos) {
if(getPoundsOrKilos == 'P')
return true;
if(getPoundsOrKilos == 'K')
return false;
//these functions return false under 'false' conditions... work on the logic :-)
return false;
}
}
Now please note, even if I pasted this correctly you are going to get a worse than bad score on your assignment if you turn in this code. It compiles and runs, but it ignores the max char# input you seemed to have constrained on your assignment. Probably there are other issues, howver, I think it is somewhat followable code. I would probably want to break it even further into more classes, but I hope this helps.
I know this may sound a little nutty, but it works: Imagine your user input as a little animal and you have set a trap for it. You need to catch the animal and do something to it. For our animal lovers' sake, let's say you need to catch it, tranquilize it, weigh it, and put a radio collar on it and then release it relatively unharmed provided it is of type Cougar. So, our trap is a multi-function trap. Whatever enters it, a value will be produced.
WHAM!!! Something is in the trap. Luckily, our trap is automatic. If it doesn't land a float value, then the trap opens and it leaves. It isn't a Cougar.
OK, the trap is still closed. It must be a Cougar. We can work on it.
Now, we ask the guy wearing the Banana Republic gear with the big Nikon around his neck for some help. We have this Float value in the trap. Now, we ask the Scientist in the Banana Repubic gear what our number means.
"Hey, Scientist Guy, what does the number in our trap mean?"
If "It's the length", he answers:
This is the length of the Cougar in feet, I need it it converted to meters...
This is the length of the Cougar in meters, I need it it converted to feet...
If "it's the weight", he answers:
This is the weight in pounds, I need it converted to kilos...
This is the weight in kilos, I need it converted to pounds...
You may find that, when you think about it, your Teacher was asking 'how do you set up the problem'? In other words, by asking the user for the value first, you can cut down on the amount of questions the program has to answer.