I'm having trouble understanding an assignment problem, specifically the problem asks me to create five integers... but I'd like to implement a way to make it 5 or less, if the user chooses. How can I do this? I apologize, I'm new to Java.
package realestatepropvalue;
import java.util.Scanner;
public class RealEstatePropertyValue
{
public static void main(String[] args)
{
Scanner sc = new Scanner ( System.in );
System.out.println ( "Hello friend, you will enter a series "
+ "of fields that'll calculate your Real Estate Property Value.");
System.out.print ("Please enter a Street Number ");
String streetnum = sc.next();
sc.nextLine();
System.out.println ("You entered the Street Number, " +streetnum );
System.out.print ( "Please enter a Street Name ");
String streetnam = sc.nextLine();
System.out.println ("You entered the Street Name, " + streetnam + " " );
System.out.print ("Please enter the number of rooms! (Up to 5!) ");
int roomcount = sc.nextInt();
String[] places = new String[5];
for(int i = 0; i < places.length; i++) {
places[i] = "Place Number: " + i;
}
sc.nextLine();
System.out.println("You said that there were " + roomcount + " rooms!");
System.out.print ("Please enter the types of rooms (up to " +roomcount+ ") that fill up the " + roomcount + " rooms!\n"
+ "(Rooms like Living, Dining, Bedroom1-2, Kitchen, Bathroom, etc!) \n ") ;
Thank you for any assistance!
You could put the input in a loop until you meet the requirements you are looking for and then set the size of your array to the input:
System.out.print ("Please enter the number of rooms! (Up to 5!) ");
while(true){
roomCount = sc.nextInt();
if(roomCount <= 5 && roomCount > 0){
break;
}else{
System.out.println("Invalid amount of rooms");
}
}
String[] places = new String[roomCount];
Tester is called and executed if the player inputs a certain name.
Variable testerWrong doesnt add one when testerWrong++ is executed
private void Tester(){
int testerTotal;
int testerScore;
int testerWrong;
testerTotal = 0;
testerScore = 0;
testerWrong = 0;
System.out.println("");
System.out.println("Hello tester, you're the designated tester. Would you like to take the quiz? Y/N");
Scanner yesno = new Scanner(System.in);
String YesNo = yesno.next();
if(YesNo.equals("Y") || YesNo.equals("y")){ //This type of code will appear very often
System.out.println("Okay, let's being!"); //if the user input (YesNo) is Y or y then...
}else{
if(YesNo.equals("N") || YesNo.equals("n")){
System.out.println("Okay, maybe some other time");
}else{ //else...
System.out.println("Sorry, i do not recognise what you entered. Please restart the program.");
}
}
System.out.println("");
QUIZ enter = new QUIZ();
enter.e2c();
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("Question #1");
System.out.println("");
System.out.println("The answer is A");
System.out.println("");
System.out.println(" - A. ");
System.out.println(" - B. ");
System.out.println(" - C. ");
System.out.println(" - D. ");
Scanner testerQ1 = new Scanner(System.in);
String TesterQ1 = testerQ1.next();
if(TesterQ1.equals("A") || TesterQ1.equals("a")){
testerScore++;
System.out.println("Correct! You have answered " + testerScore + " correct and " + testerWrong + " incorrect!");
System.out.println("");
System.out.println("Next Question.");
System.out.println("");
}else{
testerWrong++;
System.out.println("Incorrect! You have answered " + testerScore + " correct and " + testerWrong + " incorrect!");
System.out.println("");
}
Is there a way to make the variable execute without having to add a system output before it?
Thanks
This is not a minimal (way too many print statements) or even complete example (the QUIZ class is not included).
Narrowing your code down to a minimum example:
import java.util.Scanner;
public class Tester {
public static void main(String args[]) {
int testerScore = 0;
int testerWrong = 0;
System.out.println("The answer is A");
Scanner scanner = new Scanner(System.in);
String answer = scanner.next();
if (answer.equals("A") || answer.equals("a")) {
testerScore++;
System.out.print("Correct!");
}
else {
testerWrong++;
System.out.println("Incorrect! ");
}
System.out.println(" You hve answered " + testerScore +
" correct and " + testerWrong + " incorrect!");
}
}
This works for me. Compare your code against this and see what you are doing differently.
If you cannot find the problem that way, run your code in a debugger. Step through the program to see what it does when.
You may also want to follow Java naming conventions (variables start with lower case letters, classes start with upper case letters but aren't all upper case), to make it easier for others to read your code.
I'm writing this program where the user takes a math test. The problem Im now facing and have been trying to fix is how to display the final score at the end of the test.
I have a counter and the score increments for every correct answer, but how do I (at the end) display the final/total score? Any help is appreciated.
This is one of three classes btw.
import java.util.Scanner;
public class Questions {
Scanner scan = new Scanner(System.in);
int answer = 0;
int point = 0;
String correct = "Correct";
public void pointers(){
point++;
System.out.println(point + " point added to total score");
}
public void totalPoints(){
pointers();
}
public void showQuestions(){
System.out.println("\n--------------\nQuestion #1: 1+1 = ? ");
answer = scan.nextInt();
if(answer == 2){
System.out.println(correct);
pointers();
}else{
System.out.println("Wrong!");
}
System.out.println("\nQuestion #2: 340-23 = ? ");
answer = scan.nextInt();
if(answer == 317){
System.out.println("Correct!");
pointers();
}else{
System.out.println("Wrong!");
}
System.out.println("\nQuestion #3: 900/3 = ? ");
answer = scan.nextInt();
if(answer == 300){
System.out.println("Correct!");
pointers();
}else{
System.out.println("Wrong!");
}
System.out.println("\nQuestion #4: 23*2 = ? ");
answer = scan.nextInt();
if(answer == 46){
System.out.println("Correct!");
pointers();
}else{
System.out.println("Wrong!");
}
System.out.println("\nQuestion #5: -4+6 = ? ");
answer = scan.nextInt();
if(answer == 2){
System.out.println("Correct!");
pointers();
}else{
System.out.println("Wrong!");
}
}
}
The problem is that you're trying to get the input first and then you're asking for the age. When you type keyboard.nextInt() it is expecting an input immediately. So the problem is here:
*int age = keyboard.nextInt();
* System.out.println("Age: " + age);
*age = keyboard.nextInt();
My suggestion is to just remove the first keyboard.nextInt():
Example:
System.out.println("\nName: " + name);
name = keyboard.nextLine();
System.out.println("Age: " + age);
final int age = keyboard.nextInt();
and that's about it. Just be careful where you place your method calls, e.g. they should be after your println()'s.
No idea what you try to achieve, but
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
final Scanner keyboard = new Scanner(System.in);
System.out.println("Hello, it is time to take a math test.\nFirst we need you to enter some information about yourself.");
System.out.print("\nEnter name: ");
final String name = keyboard.nextLine();
System.out.print("Enter Age: ");
final int age = keyboard.nextInt();
keyboard.close();
System.out.println("Your personal information: " + name + " of " + age + " years old.");
}
}
output:
C:\Temp\123431>java -classpath .;Main.class Main
Hello, it is time to take a math test.
First we need you to enter some information about yourself.
Enter name: ttt
Enter Age: 321
Your personal information: ttt of 321 years old.
C:\Temp\123431>java -classpath .;Main.class Main
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
This java code is not printing what I want it to print.It is printing the last line "The above command is only acceptable "
import java.util.Scanner;
public class Recap1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Hi ! I am your dumb assistant, Dumbo");
System.out.println("Tell me your name");
String YourName = input.nextLine();
System.out.println("these are a list of commands which can tell me what to do :-");
String CurrentAffairs = "Tell me the current affairs";
String Dinner = "Cook my dinner" ;
String Marriage ="Will you marry me ?";
String Name = "What is my name ?";
String gift = "Buy me a gift";
System.out.println("Tell me the current affairs ");
System.out.println("Cook my dinner ");
System.out.println("Will you marry me ?");
System.out.println("What is my name ?");
System.out.println("Buy me a gift");
System.out.println("now write a command !!!");
String FirstCommand = input.nextLine();
if (FirstCommand == CurrentAffairs)
System.out.println("The Year is 2016" + "You are reading this" + "You are smiling " + "You are stupid");
else if
(FirstCommand == Dinner)
System.out.println("I can only cook roasted human brain covered with melted intestines sprinkled with blood sauce.I need the nearest human availible to me.Will you volunter? ");
else if
(FirstCommand == Marriage)
System.out.println("You are fine but I am afraid you are not of my type");
else if
(FirstCommand == Name)
System.out.println("Your name must be " + " " + YourName);
else if
(FirstCommand == gift)
System.out.println(" Give me some money and I will buy a gift for you.Deal ?");
else
System.out.println("Only the above commands are acceptable !!!!!!!!!!!!!!");
}
}
Yeah, you've got to compare strings using .equals()
if (FirstCommand.equals(CurrentAffairs))
{
System.out.println( "The Year is 2016" + "You are reading this" + "You are smiling " + "You are stupid" );
}
and you're probably better off having this entire if statement as a switch statement.
switch ( FirstCommand )
{
case "Tell me the current affairs":
System.out.println(The Year is 2016" + "You are reading this" + "You are smiling " + "You are stupid);
break;
default:
System.out.println( "Only the above commands are acceptable !!!!!!!!!!!!!!" );
break;
}
You should use
if (FirstCommand.equals( CurrentAffairs))
NOTE: for compare two string value need to use equals() instead of == because == compare reference value not a content
Try this its working fine.
public class Recap1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Hi ! I am your dumb assistant, Dumbo");
System.out.println("Tell me your name");
String YourName = input.nextLine();
System.out.println("these are a list of commands which can tell me what to do :-");
String CurrentAffairs = "Tell me the current affairs";
String Dinner = "Cook my dinner" ;
String Marriage ="Will you marry me ?";
String Name = "What is my name ?";
String gift = "Buy me a gift";
System.out.println("Tell me the current affairs ");
System.out.println("Cook my dinner ");
System.out.println("Will you marry me ?");
System.out.println("What is my name ?");
System.out.println("Buy me a gift");
System.out.println("now write a command !!!");
String FirstCommand = input.nextLine();
if (FirstCommand.equalsIgnoreCase(CurrentAffairs))
System.out.println("The Year is 2016" + "You are reading this" + "You are smiling " + "You are stupid");
else if (FirstCommand.equalsIgnoreCase(Dinner))
System.out.println("I can only cook roasted human brain covered with melted intestines sprinkled with blood sauce.I need the nearest human availible to me.Will you volunter? ");
else if (FirstCommand.equalsIgnoreCase(Marriage))
System.out.println("You are fine but I am afraid you are not of my type");
else if(FirstCommand.equalsIgnoreCase(Name))
System.out.println("Your name must be " + " " + YourName);
else if (FirstCommand.equalsIgnoreCase(gift))
System.out.println(" Give me some money and I will buy a gift for you.Deal ?");
else
System.out.println("Only the above commands are acceptable !!!!!!!!!!!!!!");
}
}
This is an efficient way to accomplish what you are trying to do. Instead of taking the string as an input, you take integer. Makes this simple and error free.
import java.util.Scanner;
public class Recap1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Hi ! I am your dumb assistant, Dumbo");
System.out.println("Tell me your name");
String YourName = input.nextLine();
System.out.println("these are a list of commands which can tell me what to do :-");
String[] replies = {"The Year is 2016" + "You are reading this" + "You are smiling " + "You are stupid"
,"I can only cook roasted human brain covered with melted intestines sprinkled with blood sauce.I need the nearest human availible to me.Will you volunter? ",
"You are fine but I am afraid you are not of my type","Your name must be ",
" Give me some money and I will buy a gift for you.Deal ?"};
System.out.println("1.Tell me the current affairs ");
System.out.println("2.Cook my dinner ");
System.out.println("3.Will you marry me ?");
System.out.println("4.What is my name ?");
System.out.println("5.Buy me a gift");
System.out.println("now write a command !!!");
int FirstCommand = input.nextInt();
switch(FirstCommand)
{
case 1:
case 2:
case 3:
case 5: System.out.println(replies[FirstCommand-1]);
break;
case 4 : System.out.println(replies[FirstCommand-1]+" "+YourName);
break;
default:
System.out.println("Only the above commands are acceptable !!!!!!!!!!!!!!");
break;
}
}
}
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.