Java checking if input is a double or character - java

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

Related

Illegal start of expression on my function public static void

My code is about looping and method, A program that will let user either compute an area or use the 4 basic math operations. the (Triangle, Square,Rectangle) with their choice of process: Addition, Subtraction, Multiplication and Division.
I think i properly closed the addition function there and i already check the closing every functions they seem work well other than the addtion function since thats the only error i got.
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//WHILE LOOP FOR CHOICES
while(true){//CHOICES LOOP
System.out.println("∘₊✧─────────────────────────────────────✧₊∘");
System.out.println("Input Choice of Process");
System.out.println("1 - Addition process");
System.out.println("2 - Subtraction process");
System.out.println("3 - Multiplication process");
System.out.println("4 - Division process");
System.out.println("5 - Compute process");
System.out.println("Your choice: ");
int option = scan.nextInt();
System.out.println("∘₊✧─────────────────────────────────────✧₊∘");
if(option == 1){
Add();
}
else if(option == 2){
Sub();
}
else if(option == 3){
Mul();
}
else if(option == 4){
Div();
}
else if(option == 5){
Com();
}
else if((option>=6)&&(option<=100)){//INVALID
System.out.println("Invalid Input, Please Input Choice Again.");
}
else{//- if user input other number, the program will break and stop from looping
break;
}
Here Im getting a error here im not sure what is it
public static void Add(){
System.out.println("ADDITION");
System.out.println("Enter two numbers: ");
System.out.println("1st number: ");
int add1=scan.nextInt();
System.out.println("2nd number: ");
int add2=scan.nextInt();
int addtotal=add1+add2;
if(addtotal>100){// In addition, if the sum is higher than 100, print the answer the word high. if equal and below 100, print low
System.out.println("Total is "+addtotal+" High");
}
else if(addtotal<100){
System.out.println("Total is "+addtotal+" Low");
}
}
public static void Sub(){//SUBTRACTION
System.out.println("SUBTRACTION");
System.out.println("Enter two numbers: ");
System.out.println("1st number: ");
int sub1=scan.nextInt();
System.out.println("2nd number: ");
int sub2=scan.nextInt();
int subtotal=sub1-sub2;
if(subtotal<0){// In subtraction, if the difference is negative, print invalid. If 0 or above, print the difference and the word valid.
System.out.println("Invalid ");
}
else if(subtotal>0){
System.out.println("Total is "+subtotal+" Valid");
}
}
public static void Mul(){//MULTIPLICATION
System.out.println("MULTIPLICATION");
System.out.println("Enter two numbers: ");
System.out.println("1st number: ");
double multi1=scan.nextDouble();//In multiplication, make it accepts decimal value
System.out.println("2nd number: ");
double multi2=scan.nextDouble();
double multitotal=multi1*multi2;
System.out.println("Total is "+multitotal);
}
public static void Div(){
System.out.println("DIVISION");
System.out.println("Enter two numbers: ");
System.out.println("1st number: ");
int div1=scan.nextInt();
System.out.println("2nd number: ");
int div2=scan.nextInt();
int divtotal= div1 / div2;
int divremainder= div1 % div2;//In division, if it has remainder, print the answer and the remainder.
System.out.println("Total is "+divtotal);
System.out.println("Remainder is "+divremainder);
}
public static void Com(){// If user choose 5, the user needs to choose again on a ,b or c. If other letter, print invalid and then go pack on choosing of process.
System.out.println("∘₊✧─────────────────────────────────────✧₊∘");
System.out.println("Input Choice of Process");
System.out.println("a - Rectangle");
System.out.println("b - Square");
System.out.println("c - Triangle");
System.out.println("Your choice: ");
Scanner Keyboard = new Scanner(System.in);
Scanner input = new Scanner(System.in);
char choice = Keyboard.nextLine().charAt(0);
System.out.println("∘₊✧─────────────────────────────────────✧₊∘");
if (choice == 'A' || choice == 'a')//rectangle
{
System.out.println("Enter length of rectangle's base: ");
double base = input.nextDouble();
System.out.println("Enter length of rectangle's height: ");
double height = input.nextDouble();
double rArea = base * height;
System.out.println("The area of a rectangle with a base length of " + base + " and a height of " + height + " is " + rArea + ".");
}
else if (choice == 'B' || choice == 'b') //square
{
System.out.println("Enter length of square's sides: ");
double sSide = input.nextDouble();
double sArea = sSide * sSide;
System.out.println("The area of a square with a side length of " + sSide + " is " + sArea + ".");
}
else if (choice == 'C' || choice == 'c') //traingle
{
System.out.println("Enter traingle's side length: ");
double tSide = input.nextDouble();
double tArea = tSide * tSide * tSide;
System.out.println("The area of a triangle with a side length of " + tSide + " is " + tArea + ".");
}
else //invalid
{
System.out.println("You've entered an invalid character.");
}
}
}
You haven't got a closing brace for your main method

while loop keeps ending without initiating the if-statement

I'm trying to create a simple calculator program on Java as a simple first project as I learn Java.
Problem: After I run the program and after doing my calculation, I wanted to give the user the option on whether they want to end the program or do some more calculations. for some reason the program is not using the (if) statements that I have placed in it, it seems to skip it and end my program without allowing the user to input his choice at the end.
I'm really sorry if my question is not clear, I couldn't find a solution for my problem online, and I do apologize if my code looks really messy.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double fnum, snum, answer;
String choice, name, in;
System.out.println("Hello, whats your name?");
name = input.nextLine();
System.out.println("");
System.out.println("Oh so your name is " + name + "!");
System.out.println("");
System.out.println("This program is a calculator that will do simple calculation of two numbers");
System.out.println("There are four different options to choose from:");
boolean running = true;
CAL:
while (running) {
System.out.println("type a for Addition, b for subtraction, c for multiplication and d for division");
System.out.println("Then press enter!");
choice = input.nextLine();
while (!choice.equals("a") &&
!choice.equals("A") &&
!choice.equals("b") &&
!choice.equals("B") &&
!choice.equals("c") &&
!choice.equals("C") &&
!choice.equals("d") &&
!choice.equals("D")) {
System.out.println("Wrong choice, Please try again");
System.out.println("type a for Addition, b for subtraction, c for multiplication and d for division");
choice = input.nextLine();
}
if (choice.equals("a") || choice.equals("A")) {
System.out.println(name +" You have chosen Addition");
System.out.println("Type the first number:");
fnum = input.nextDouble();
System.out.println("Type the second number:");
snum = input.nextDouble();
System.out.println("your answer is:");
Addition addy = new Addition(fnum,snum);
System.out.println(addy.getans());
}
if (choice.equals("b") || choice.equals("B")) {
System.out.println(name +" You have chosen Subtraction");
System.out.println("Type the first number:");
fnum = input.nextDouble();
System.out.println("Type the second number:");
snum = input.nextDouble();
answer = fnum - snum;
System.out.println("your answer is:"
+ answer);
}
if (choice.equals("c") || choice.equals("C")) {
System.out.println(name +" You have chosen Multiplication");
System.out.println("Type the first number:");
fnum = input.nextDouble();
System.out.println("Type the second number:");
snum = input.nextDouble();
answer = fnum * snum;
System.out.println("your answer is:"
+ answer);
}
if (choice.equals("d") || choice.equals("D")) {
System.out.println(name +" You have chosen Addition");
System.out.println("Type the first number:");
fnum = input.nextDouble();
while (fnum == 0) {
System.out.println("invalid try again!");
fnum = input.nextDouble();
}
System.out.println("Type the second number:");
snum = input.nextDouble();
answer = fnum / snum;
System.out.println("your answer is:"
+ answer);
}
System.out.println("");
System.out.println("Thank you " + name + " for using this simple calculator :)");
System.out.println("If you would like to try again press a the press Enter, if you wish to exit press any botton and then press enter");
in = input.nextLine();
if (in.equals("a")) {
System.out.println("");
System.out.println("Thank you, please choose again");
System.out.println("");
} else {
System.out.println("Thank you and goodbye");
break;
}
}
}
}
It's a simple problem caused by nextInt/Double/etc behaviour.
Those methods don't read the following new-line character so the next nextLine will always return an empty string (the rest of the current line).
Try to change those (e.g. the addition case) with Double.parseDouble(input.nextLine());
if (choice.equals("a") || choice.equals("A")) {
System.out.println(name + " You have chosen Addition");
System.out.println("Type the first number:");
fnum = Double.parseDouble(input.nextLine());
System.out.println("Type the second number:");
snum = Double.parseDouble(input.nextLine());
System.out.println("your answer is:");
Addition addy = new Addition(fnum, snum);
System.out.println(addy.getans());
}
you can notice debugging that the last in = input.nextLine(); called to ask for user input will always be empty string.

Adding loops to an existing java program?

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.

How to call a statement over and over again in Java

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.

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