Adding loops to an existing java program? - java

I need to modify my program so that I can run it more than once if need be. I need to quit the program if the user enters a Q or q and if anything other than the requested entry (or the quit command) is entered the question will be repeated.
Here is the code I have so far:
import java.util.Scanner;
public class TemperatureLoop
{
private static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("Enter a temperature in degrees (for example 32.6): ");
double temp;
temp = keyboard.nextDouble();
System.out.println("Enter 'F' (or 'f') for Fahrenheit or 'C' (or 'c') for Celsius: ");
String letter = keyboard.next();
double total = 0;
//if Farenheit then do this equation
if (letter.equals("F") || (letter.equals("f")))
{
total = ((temp-32)*5)/9; //convert the entered temperature to Celsius
System.out.println(temp + " degrees F = " + total + " degrees Celsius");
}
else //if Celsius then do this
if (letter.equals("C") || (letter.equals("c")) )
{
total = (((temp*9))/5)+32; //convert the entered temperature to Farenheit
System.out.println(temp + " degrees C = " + total + " degrees Fahrenheit");
}
}
}

I would suggest putting what you have into a while loop that breaks out if the user enters 'Q' or 'q'. Something similar to below:
// Declare your breaking condition variable outside the while loop
boolean done = false;
while (!done){
// Your existing code here
// A conditional to check for 'Q' or 'q'
// set done to true if the above line evaluates as true.
}

You should use a do-while loop in this case,
String letter = "";
do{
System.out.println("Enter a temperature in degrees (for example 32.6): ");
double temp = 0;
while(true){
if(keyboard.hasNextDouble())
{
temp = keyboard.nextDouble();
break;
}
else
{
System.out.println("Enter a valid double");
sc.nextLine();
}
}
System.out.println("Enter 'F' (or 'f') for Fahrenheit or 'C' (or 'c') for Celsius: ");
letter = keyboard.next();
double total = 0;
//if Farenheit then do this equation
if (letter.equalsIgnoreCase("F"))
{
total = ((temp-32)*5)/9; //convert the entered temperature to Celsius
System.out.println(temp + " degrees F = " + total + " degrees Celsius");
}
else if (letter.equalsIgnoreCase("C"))
{ //if Celsius then do this
total = (((temp*9))/5)+32; //convert the entered temperature to Farenheit
System.out.println(temp + " degrees C = " + total + " degrees Fahrenheit");
}
}while(!letter.equalsIgnoreCase("Q"));
How the loop works is, whatever is in the do part will always execute at least once. Then it will check the while condition to determine whether or not to execute the do part again. Like you said, once the user enters Q or q, the program will end because the while condition will evaluate to false and the do part will no longer be executed. Therefore, the loop will terminate in that case.
What exactly happens when you enter Q or q? The do part will technically happen, but your if-statements will be ignored since it doesn't satisfy those conditions. Once the while check is reached, the condition will evaluate to false, causing the loop to end. If you entered something like M or g, then the if-statements will be ignored but the loop won't end because the while condition won't evaluate to false so the program will ask you once again for a temperature and degrees.

Related

Java checking if input is a double or character

I'm writing a program in Java that does temperature conversion, but running into an issue.
import java.util.*;
public class TempCon2 {
public static void main (String[] args) {
double f,c,temp;
char ch,op;
Scanner sc = new Scanner(System.in);
System.out.println("This program converts temperatures from Fahrenheit to Celsius and vica versa.");
do {
System.out.print("Please enter your temperature: ");
temp = sc.nextDouble();
System.out.print("Please enter the units (F/C): ");
ch = sc.next().charAt(0);
if(ch=='F') {
c=(temp-32)*5/9;
System.out.println("\nThe temperature of " + temp + " degrees Fahrenheit is equivalent to " + c + " degrees Celsius!"); }
else if(ch=='C') {
f=(temp*9/5)+32;
System.out.println("\n The temperature of " + temp + " degrees Celsius is equivalent to " + f + " degrees Fahrenheit!"); }
System.out.print("Do you wish to do another conversion? (Y/N): ");
op=sc.next().charAt(0);
System.out.println();
if(op=='N' || op=='n') {
break; }
}while((op=='Y' || op=='y'));
System.out.println("Thank you, Goodbye");
}
}
I want to be able to check when the user inputs their temperature if its a number, and if not it returns a message that says " 'user input' is not a number. Please enter a number". As well as when it asks for the units that if you enter anything other than "F" or "C" it does the same as the number one.
You can try by parsing the String value to Double:
Double temp;
try {
temp = Double.parseDouble(sc.nextLine());
} catch (NumberFormatException nfe){
System.out.println("The input is not a number");
break;
}
From Double.parseDouble doc:
NumberFormatException – if the string does not contain a parsable
double.
What you want is 'complex', in the sense that you don't hunt for a single method that does this; there is no scanner.askForCorFAndKeepAskingIfTheyEnterSomethingElse();.
So, you do the same thing you always do when faced with a task you want to do repeatedly which isn't trivial: You make a method.
public static char askTemperatureUnit(Scanner s) {
...
}
public static double askTemperatureAmount(Scanner s) {
...
}
These methods will use a few aspects:
a while (true) loop. If the result is what you wanted, return it. (which also ends the loop by returning out of it). Otherwise, you tell the user they didn't enter what you wanted and let it loop.
A way to respond when the user fails to enter a double value:
while (true) {
try {
return scanner.nextDouble();
} catch (InputMismatchException e) {
scanner.next(); // eat the invalid input away
System.out.println("Hey now enter a number please!");
}
}
You can also call scanner.next() and then use try/catch to run Double.parseDouble - same end result, whatever you feel is best.
While you're at it, c = Character.toUpperCase(c) lets you turn an n into an N which is nice.
You need a couple of more do-while loops the way you have put for prompting the user if they want to continue.
I also recommend you use Scanner::nextLine to avoid the problems mentioned in this thread.
public class Main {
public static void main(String[] args) {
double f, c, temp;
char ch, op;
Scanner sc = new Scanner(System.in);
System.out.println("This program converts temperatures from Fahrenheit to Celsius and vica versa.");
do {
boolean valid;
do {
valid = true;
System.out.print("Please enter your temperature: ");
try {
temp = Double.parseDouble(sc.nextLine());
do {
valid = true;
System.out.print("Please enter the units (F/C): ");
ch = sc.nextLine().charAt(0);
if (ch == 'F') {
c = (temp - 32) * 5 / 9;
System.out.println(
"\nThe temperature of " + temp + " degrees Fahrenheit is equivalent to " + c
+ " degrees Celsius!");
} else if (ch == 'C') {
f = (temp * 9 / 5) + 32;
System.out
.println("\n The temperature of " + temp + " degrees Celsius is equivalent to " + f
+ " degrees Fahrenheit!");
} else {
System.out.println("Invalid input. Enter F or C");
valid = false;
}
} while (!valid);
} catch (NumberFormatException e) {
System.out.println("Invalid input. Enter a number only");
valid = false;
}
} while (!valid);
System.out.print("Do you wish to do another conversion? (Y/N): ");
op = sc.nextLine().charAt(0);
System.out.println();
if (op == 'N' || op == 'n') {
break;
}
} while ((op == 'Y' || op == 'y'));
System.out.println("Thank you, Goodbye");
}
}
A sample run:
This program converts temperatures from Fahrenheit to Celsius and vica versa.
Please enter your temperature: abc
Invalid input. Enter a number only
Please enter your temperature: 12.5
Please enter the units (F/C): X
Invalid input. Enter F or C
Please enter the units (F/C): F
The temperature of 12.5 degrees Fahrenheit is equivalent to -10.833333333333334 degrees Celsius!
Do you wish to do another conversion? (Y/N): y
Please enter your temperature: xyz
Invalid input. Enter a number only
Please enter your temperature: pqr
Invalid input. Enter a number only
Please enter your temperature: -40
Please enter the units (F/C): a
Invalid input. Enter F or C
Please enter the units (F/C): F
The temperature of -40.0 degrees Fahrenheit is equivalent to -40.0 degrees Celsius!
Do you wish to do another conversion? (Y/N): n
Thank you, Goodbye

I cannot get my if statement to loop correctly

I am trying to prompt the user if the information they entered is correct and the program just proceeds anyway instead of re-prompting the user. I think i need to change how I loop this do some type of do-while loop, but I don't quite know what to do.
{
//Here we will set up our method of data entry and decimal format
Scanner keyboard = new Scanner(System.in);
DecimalFormat eNotation1 = new DecimalFormat("00.00");
//Let's introduce our program to the user
System.out.println("Hi, This is a program to calculate quarterly interest growth");
//Here we will prompt the user to enter the amount of quarters
System.out.println("How many quarters would you like to display? Please pick a number greater than zero and less than or equal to 10");
int quarterNumber = keyboard.nextInt();
if (quarterNumber > 10 || quarterNumber < 0)
{
System.out.println("You entered a number outside of the boundrys. Please run the program again and choose a number between 0 and 10 (number can include 10)");
System.exit(0);
}
//Here we will prompt the user for the starting balance.
System.out.println("What is the starting balance of this account?");
double startingBalance = keyboard.nextDouble();
//Here we will prompt the user for the interest rate
System.out.println("What is the interest rate (in percent) in your area? Please pick a number from 1 - 20.");
double interestRate = keyboard.nextDouble();
if (interestRate < 1 || interestRate > 20)
{
System.out.println("You entered a number outside of the boundrys. Please run the program again and choose a number between 1 and 20 (can include 1 and 20)");
System.exit(0);
}
//Here we will double check with the user that the info is correct.
System.out.println("The amount of quarters you would like displayed is " + quarterNumber);
System.out.println("The starting balance you would like to work with is " + startingBalance);
System.out.println("The interest rate in your area is " + interestRate);
System.out.println("Is this information correct?");
keyboard.nextLine();
String answer = keyboard.nextLine();
System.out.println("");
//We will have them enter the information again if the answer is no or No
if (answer == "no" || answer == "No")
{
//Here we will prompt the user to enter the amount of quarters
System.out.println("How many quarters would you like to display? Please pick a number greater than zero and less than or equal to 10");
keyboard.nextInt();
quarterNumber = keyboard.nextInt();
//Here we will prompt the user for the starting balance.
System.out.println("What is the starting balance of this account?");
keyboard.nextDouble();
startingBalance = keyboard.nextDouble();
//Here we will prompt the user for the interest rate
System.out.println("What is the interest rate (in percent) in your area? Please pick a number from 1 - 20.");
keyboard.nextDouble();
interestRate = keyboard.nextDouble();
}
//Next we will proceed with the calculation if the information is indeed correct
double endingBalance = startingBalance + (startingBalance * (interestRate / 100 * .25));
double interestEarned = endingBalance - startingBalance;
//Now we will output the information
for (int qn = 1; qn < (quarterNumber + 1); qn++ , startingBalance = startingBalance + interestEarned , endingBalance =startingBalance + (startingBalance * (interestRate / 100 * .25)), interestEarned = endingBalance - startingBalance )
{
System.out.println("Quarter Number Starting Balance Interest Earned Ending Balance ");
System.out.println(qn + " " + eNotation1.format(startingBalance) + " " + eNotation1.format(interestEarned) + " " + eNotation1.format(endingBalance) + " ");
}
}
}
I probably figured what your problem is.
Example code snippet: (Note I am doing without an actual java editor so just handle any missing syntax
//Here we will prompt the user to enter the amount of quarters
int quarters = 0;
System.out.println("How many quarters would you like to display? Please pick a number greater than zero and less than or equal to 10");
do
{
quarters = keyboard.nextInt();
if (quarters <= 0 || quarters >= 10)
{
System.out.println("You entered a number outside of the boundrys. Please Type a number greater than 0 and less than equal to 10 again)");
}
}
while (quarters <= 0 || quarters >= 10)
The idea is for a recursive prompt. The application first prompts the user to type in the result, and then you handle the amount of So you have to handle the prompt within the do-while loop. Assuming you don't want to repeat the same old text, you can do what I did (which is much cleaner in my opinion).
EDIT: Assuming you want to handle the entire repeating of the application. place everything for the declaration of variables into a method (or better various methods for cleaner handling, and handle something like this.
int quarters;
double balance;
//TODO : Add all other required variables
string verification;
do
{
quarters = getNumberOfQuartersFromUser();
balance = getStartingBalance();
... //TODO : all the other methods
//verification
System.out.println("Is this accepted?");
verification = keyboard.nextString();
//Handle verfication if it is no or No
if (verification == null || verification == "No" || verification == "no")
{
System.out.println("Starting from the beginning again");
}
}
while (verification == null || verification == "No" || verification == "no")
//out of loop, so handle calculation.
...
and a method snippet
private int getNumberOfQuartersFromUser()
{
int quarters = 0;
System.out.println("How many quarters would you like to display? Please pick a number greater than zero and less than or equal to 10");
do
{
quarters = keyboard.nextInt();
if (quarters <= 0 || quarters >= 10)
{
System.out.println("You entered a number outside of the boundrys. Please Type a number greater than 0 and less than equal to 10 again)");
}
}
while (quarters <= 0 || quarters >= 10)
return quarters;
}
I think you should enclose your codes to Else statement to avoid proceeding unintentionally. Remember that else limits the run-time of your codes and put it on a more specified path for you.
{
//Here we will set up our method of data entry and decimal format
Scanner keyboard = new Scanner(System.in);
DecimalFormat eNotation1 = new DecimalFormat("00.00");
//Let's introduce our program to the user
System.out.println("Hi, This is a program to calculate quarterly interest growth");
//Here we will prompt the user to enter the amount of quarters
System.out.println("How many quarters would you like to display? Please pick a number greater than zero and less than or equal to 10");
int quarterNumber = keyboard.nextInt();
//Here you had started your condition I'll try to make it nested if statement
if (quarterNumber > 10 || quarterNumber < 0)
//if the condition is true perform this
{
System.out.println("You entered a number outside of the boundrys. Please run the program again and choose a number between 0 and 10 (number can include 10)");
System.exit(0);
}
else{
//if false conditions inside else statement should be performed
//Here we will prompt the user for the starting balance.
System.out.println("What is the starting balance of this account?");
double startingBalance = keyboard.nextDouble();
//Here we will prompt the user for the interest rate
System.out.println("What is the interest rate (in percent) in your area? Please pick a number from 1 - 20.");
double interestRate = keyboard.nextDouble();
//you could put another if statement inside if statement which is known as nested if statement.
if (interestRate < 1 || interestRate > 20)
{
System.out.println("You entered a number outside of the boundrys. Please run the program again and choose a number between 1 and 20 (can include 1 and 20)");
System.exit(0);
}
else{
//like before you should enclose this to else to avoid confusion
//Here we will double check with the user that the info is correct.
System.out.println("The amount of quarters you would like displayed is " + quarterNumber);
System.out.println("The starting balance you would like to work with is " + startingBalance);
System.out.println("The interest rate in your area is " + interestRate);
System.out.println("Is this information correct?");
keyboard.nextLine();
String answer = keyboard.nextLine();
System.out.println("");
//We will have them enter the information again if the answer is no or No
if (answer == "no" || answer == "No")
{
//Here we will prompt the user to enter the amount of quarters
System.out.println("How many quarters would you like to display? Please pick a number greater than zero and less than or equal to 10");
keyboard.nextInt();
quarterNumber = keyboard.nextInt();
//Here we will prompt the user for the starting balance.
System.out.println("What is the starting balance of this account?");
keyboard.nextDouble();
startingBalance = keyboard.nextDouble();
//Here we will prompt the user for the interest rate
System.out.println("What is the interest rate (in percent) in your area? Please pick a number from 1 - 20.");
keyboard.nextDouble();
interestRate = keyboard.nextDouble();
}
//Next we will proceed with the calculation if the information is indeed correct
double endingBalance = startingBalance + (startingBalance * (interestRate / 100 * .25));
double interestEarned = endingBalance - startingBalance;
//Now we will output the information
for (int qn = 1; qn < (quarterNumber + 1); qn++ , startingBalance = startingBalance + interestEarned , endingBalance =startingBalance + (startingBalance * (interestRate / 100 * .25)), interestEarned = endingBalance - startingBalance )
{
System.out.println("Quarter Number Starting Balance Interest Earned Ending Balance ");
System.out.println(qn + " " + eNotation1.format(startingBalance) + " " + eNotation1.format(interestEarned) + " " + eNotation1.format(endingBalance) + " ");
}
}
}
}
Remember that learning nested if statement is essential to a programmer. without this, all your conditions will literally proceed.

Allow the user to continue entering numbers until they choose to quit

This program's objective is to calculate the n-th Fibonacci number. How do I allow the user to continue entering numbers until they choose to quit? Thanks.
public class FibonacciNUmbers
{
public static int calcFibNum(int x)
{
if (x == 0)
return 0;
else if (x == 1)
return 1;
else
return calcFibNum(x-1) + calcFibNum(x-2);
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("What number would you like to find the Fibonacci number for?");
int x = in.nextInt();
System.out.println("The Fibonacci number of " + x + " is " + calcFibNum(x));
System.out.println("Would you like to find the Fibonaci number of another number?");
String answer = in.next();
if (answer.equalsIgnoreCase("Y"));
{
System.out.println("What number would you like to find the Fibonacci number for?");
x = in.nextInt();
System.out.println("The Fibonacci number for " + x + " is " + calcFibNum(x));
}
else
{
System.out.println();
}
}
}
By the way your code prints all the Fibonacci numbers up to n and not the nth number.Below is just an example of how to keep entering input from Scanner. Use that to build upon what you want to do:
int num = 0;
while (in.hasNextInt()) {
num = in.nextInt();
}
Happy coding!
//start your while loop here
while (true)
{
System.out.println("Would you like to find the Fibonacci number of another number?");
String answer = in.next();
if (answer.equalsIgnoreCase("Y"));
{
System.out.println("What number would you like to find the Fibonacci number for?");
x = in.nextInt();
System.out.println("The Fibonacci number for " + x + " is " + calcFibNum(x));
}
else
{
System.out.println("Thanks for playing");
break; // ends the while loop.
}
}
For loops are used when you can count things or have a set of things. While loops are used when you're not sure how long it might go on for, or if you want it to continue until some event occurs (user pressing a certain letter for example)
Slight variation of the above that is probly a bit more elegant:
String answer = "Y";
//start your while loop here
while (answer.equals("Y")) {
System.out.println("Would you like to find the Fibonacci number of another number?");
answer = in.next(); //declare your variable answer outside the loop so you can use it in the evaluation of how many times to do the loop.
if (answer.equalsIgnoreCase("Y"));
{
System.out.println("What number would you like to find the Fibonacci number for?");
x = in.nextInt();
System.out.println("The Fibonacci number for " + x + " is " + calcFibNum(x));
}
else
{
System.out.println("Thanks for playing");
// no need to break out.
}
}

Issues with loop skipping every other input in java

I'm trying to create this rather simple program for my java class. Everything is working, except for when I tried to have an input loop. I've never done that before, and it's ignoring every other input. Here is the problem prompt:
B. Ch. 4 – Average - Write a program that will read an unspecified number of integer grades and find the summary total and average. Print grades, total and average. The last record will be the trailer record of -1. Also output the final letter grade per syllabus grading scale.
And here is the code:
import java.util.Scanner;
public class Average
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
float counter = 0;
float accum = 0;
float addAccum = 0;
float tempLoop = 0;
System.out.println("Please Enter Grade, Enter -1 to Finish: ");
while (tempLoop != -1)
{
addAccum = in.nextFloat();
counter++;
accum = addAccum + accum;
tempLoop = in.nextFloat();
}
float avgGrade = accum / counter;
if(avgGrade >= 90)
{
System.out.println("\nYour Grade is: " + "A");
}else if(avgGrade >=80)
{
System.out.println("\nYour Grade is: " + "B");
}else if(avgGrade >=70)
{
System.out.println("\nYour Grade is: " + "C");
}else if(avgGrade >=60)
{
System.out.println("\nYour Grade is: " + "D");
}else
{
System.out.println("\nYour Grade is: " + "F");
}
System.out.println("\nGrade Total: " + accum);
System.out.println("\nCounter Num :" + counter); // for testing only
System.out.println("\nAverage Grade: " + avgGrade);
}
}
This is the console input/output:
Please Enter Grade, Enter -1 to Finish:
100
100
100
100
100
100
-1
-1
Your Grade is: C
Grade Total: 299.0
Counter Num :4.0
Average Grade: 74.75
You have in.nextFloat() twice in your while loop.
Change your logic to look for -1 first and then process the input.
Something like :
tempLoop = in.nextFloat();
while(tempLoop != -1){
sum += tempLoop;
tempLoop = in.nextFloat();
}
Hope this helps.
What you're doing is reading twice;
while (tempLoop != -1)
{
addAccum = in.nextFloat(); // Once Here
counter++;
accum = addAccum + accum;
tempLoop = in.nextFloat(); // Again Here
}
Thus only half of the data is being processed;
You'll need to read the first value before entering the loop, and then only read once at the end before checking that the new value is not -1
To avoid reading twice and reading inside the loop, or add ugly break statements, i would do it like this:
while ((addAccum = in.nextFloat()) != -1) {
counter++;
accum = addAccum + accum;
}

I can't figure out my simple Java homework

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.

Categories