Converting Units using if statements? - java

I have to write a program to convert between linear units in, ft, mi, mm, cm, m, km. I know there are easier and better ways to do this. I think we'ere just trying to fully understand if else if statements. But this is what I have so far. I'm just trying to figure out if I am on the right track. I've tried to write out some pseudocode but it just seems like a lot going on so I find it a bit overwhelming. Next I'm going to add a method to convert form in or mm to whatever is selected by the user.
When I test the program i get this: UnitConversion#76c5a2f7 (EDIT: THIS ISSUE WAS FIXED)
Ok I made the suggested changes and that allowed the first part of the program to run properly. I have now added my second method to convert from in/mm to the other measurements.. I was having issues but I figured it out.
Here is my main method;
public class LinearConversion
{
public static void main(String[] args)
{
UnitConversion newConvert = new UnitConversion("km", "m", 100);
System.out.println(newConvert);
}
}
Any suggestions? What am I missing or not understanding about doing this sort of program?
public class UnitConversion
{
private String input;
private String output;
private double value;
private double temp;
private double in, ft, mi, mm, cm, m, km;
private final double inch_feet = 12;
private final double inch_miles = 63360;
private final double inch_millimeters = 25.4;
private final double inch_centimeters = 2.54;
private final double inch_meters = 0.0254;
private final double inch_kilometers = 0.0000254;
private final double millimeters_inch = 0.0393701;
private final double millimeters_feet = 0.00328084;
private final double millimeters_miles = 0.000000622;
private final double millimeter_centimeters = 10;
private final double millimeter_meters = 1000;
private final double millimeter_kilometers = 1000000;
public UnitConversion(String in, String out, double val)
{
input = in;
output = out;
value = val;
}
public String toString()
{
if (input.equals("mi"))
{
in = value * inch_miles;
input = "in";
}
else if (input.equals("ft"))
{
in = value * inch_feet;
input = "in";
}
else
{
in = value;
input = "in";
}
if (input.equals("km"))
{
mm = value * millimeter_kilometers;
input = "mm";
}
else if (input.equals("m"))
{
mm = value * millimeter_meters;
input = "mm";
}
else if (input.equals("cm"))
{
mm = value * millimeter_centimeters;
input = "mm";
}
else
{
mm = value;
input = "mm";
}
return value + input + " " + output;
}
public double getUnit()
{
if (input.equals("in"))
{
if (output.equals("ft"))
{
ft = in * inch_feet;
System.out.println(ft + "ft");
}
else if (output.equals("mi"))
{
mi = in * inch_miles;
System.out.println(mi + "mi");
}
else if (output.equals("mm"))
{
mm = in * inch_millimeters;
System.out.println(mm + "mm");
}
else if (output.equals("cm"))
{
cm = in * inch_centimeters;
System.out.println(cm + "cm");
}
else if (output.equals("m"))
{
m = in * inch_meters;
System.out.println(m + "m");
}
else if (output.equals("km"))
{
km = in * inch_kilometers;
System.out.println(km + "km");
}
else
{
System.out.println(in + "in");
}
}
else
{
if (output.equals("cm"))
{
cm = mm * millimeter_centimeters;
System.out.println(cm + "cm");
}
else if (output.equals("m"))
{
m = mm * millimeter_meters;
System.out.println(m + "m");
}
else if (output.equals("km"))
{
km = mm * millimeter_kilometers;
System.out.println(km + "km");
}
else if (output.equals("in"))
{
in = mm * millimeters_inch;
System.out.println(in + "in");
}
else if (output.equals("ft"))
{
ft = mm * millimeters_feet;
System.out.println(ft + "ft");
}
else if (output.equals("mi"))
{
mi = mm * millimeters_miles;
System.out.println(mi + "mi");
}
else
{
System.out.println(mm + "mm");
}
}
}

Basically, you need/want to give a String argument to System.out.println in order to display it.
Thus, when you use System.out.println with an Object (that is not a String) as the argument, Java actually outputs the result of the toString method on that object.
If you haven't overridden it, the Object class' implementation of toString is used: this is what gives you your current output: UnitConversion#76c5a2f7.
To learn more about how is this default toString implementation generating that String, you can refer to the javadoc entry for Object#toString.

Base on your output, and your provided code, yes! Rename String getInput() to String toString() and your current main() will work, or change your current main()
System.out.println(newConvert.getInput()); // <-- added .getInput()

Related

Java - read file into array of objects

I am in need of some guidance. I am not sure how to go about reading in the sample text file into an array of objects. I know that the work needs to be in the while loop I have in main. I just do not know what I need to accomplish this.
I understand that I need to read in the file line by line (that's what the while loop is doing), but I don't know how to parse that line into an object in my array.
I know all of you like to see what people have tried before you help, but I honestly don't know what to try. I don't need a hand out, just some guidance.
Sample Text File:
100 3
120 5
646 7
224 9
761 4
Main:
public static void main(String[] args) {
Weight[] arrWeights = new Weight[25];
int count = 0;
JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
int returnValue = jfc.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = jfc.getSelectedFile();
System.out.println(selectedFile.getAbsolutePath());
BufferedReader inputStream = null;
String fileLine;
inputStream = new BufferedReader(new FileReader(selectedFile.getAbsoluteFile()));
System.out.println("Weights:");
// Read one Line using BufferedReader
while ((fileLine = inputStream.readLine()) != null) {
count++;
System.out.println(fileLine);
}
System.out.println("Total entries: " + count);
}
}
Weight Class:
public class Weight {
private int pounds;
private double ounces;
private final int OUNCES_IN_POUNDS = 16;
public Weight(int pounds, double ounces) {
this.pounds = pounds;
this.ounces = ounces;
}
public boolean lessThan(Weight weight) {
return toOunces() < weight.toOunces();
}
public void addTo(Weight weight) {
this.ounces += weight.toOunces();
normalize();
}
public void divide(int divisor) {
if (divisor != 0) {
this.ounces = (this.toOunces() / divisor);
this.pounds = 0;
normalize();
}
}
public String toString() {
return this.pounds + " lbs " + String.format("%.3f", this.ounces) + " oz";
}
private double toOunces() {
return this.pounds * OUNCES_IN_POUNDS + this.ounces;
}
private void normalize() {
if (ounces >=16) {
this.pounds += (int) (this.ounces /OUNCES_IN_POUNDS);
this.ounces = this.ounces % OUNCES_IN_POUNDS;
}
}
}
I don't remember how to do that exactly in Java but I think this general guidance could help you:
In the while loop -
Parse the line you input from the read line using split function, you can use this as reference(first example can do the trick): http://pages.cs.wisc.edu/~hasti/cs302/examples/Parsing/parseString.html
Take the parsed line values, cast them to desired values per your class and create your object.
Append the created object to your list of objects: arrWeights

converting binary/decimal fraction to hexadecimal in java -unexpected output

I am trying to write a program that converts binary(with or without fraction) inputs into hex which is nearly done but unfortunately in the hex output the point (".")is missing.
Suppose my expected output is e7.6 , but i am getting e76 instead.
only the "." is missing.
here is my BinToHex class..
import java.io.*;
//tried to convert the binary into dec and then dec to hex
public class BinToHex {
double tempDec,fractionpart;
long longofintpart,templongDec;
String inpu ="11100111.011";
String hexOutput=null,tempDecString,hex = null;
static int i = 1;
public void convertbintohex() {
if (inpu.contains(".")) {
int placesAfterPoint = inpu.length() - inpu.indexOf(".") - 1;//every thing
long numerator = Long.parseLong(inpu.replace(".", ""), 2);//goes
double decimalOfInput = ((double) numerator) / (1L << placesAfterPoint);//alright till here
while (true) {
tempDec = decimalOfInput * 16;
if (tempDec == (int)tempDec) {
tempDecString = String.valueOf((long)tempDec);
templongDec = Long.parseLong(tempDecString, 10);
hexOutput = Long.toHexString(templongDec);
break;
} else {
longofintpart = (long)tempDec;
hex=Long.toHexString(longofintpart);
if(i==1){
hexOutput = hex + ".";
i=i+1;
}else{
hexOutput = hexOutput + hex;
}
fractionpart = tempDec-(int)tempDec;
decimalOfInput = fractionpart;
}
}
} else {
// this part is ok
tempDecString = String.valueOf(Integer.parseInt(inpu, 2));
templongDec = Long.parseLong(tempDecString, 10);
hexOutput = Long.toHexString(templongDec);
}
System.out.println(hexOutput);
}
}
my main Test class..
public class Test{
public static void main(String args[]){
BinToHex i = new BinToHex();
i.convertbintohex();
}
}
I am stuck!
plz help .
really, not i can't resist to write a solution... after having such long comments, it jst takes me some minutes ^^
final int CODEBASE = 16;
String input = "11100111.011";
//lets see if we have a '.' in our String
if (input.indexOf(".") > 0) {
//yes, we have one - so we can split the string by '.'
String splits = input.split(".");
//the part left of the dot
String beforeDot = splits[0];
//the part right of the dot
String afterDot = splits[1];
//it's a incomplete input, we must fill up with
//trailing zeros according to out code base
afterDot.fillTrailingZeros(afterDot, CODEBASE);
//now we can parse the input
int asIntBefore = Integer.parseInt(beforeDots, 2);
int asIntAfter = Integer.parseInt(afterDot , 2);
} else {
//use your working code for
//input wthoput dot HERE
}
//fills trailing zeros to input String
String fillTrailingZeros(String input, int base){
//as long as our String is shorter than the codebase...
while (input.length() < base){
//...we have to add trailing zeros
input = input +"0";
}
return input;
}
At last found a proper algorithm for converting decimal(with or without fraction) to hex.
besides, binary(with or without fraction) to decimal in Java is here
The algorithm for converting decimal(with or without fraction) into hex in Java
import java.math.*;
public class DecimalToHex{
public String decimalToHex(String decInpString){
StringBuilder hexOut = new StringBuilder();
double doubleOfDecInp = Double.parseDouble(decInpString);
if(doubleOfDecInp < 0){
hexOut = hexOut.append("-");
doubleOfDecInp = -doubleOfDecInp;
}
BigInteger beforedot = new BigDecimal(doubleOfDecInp).toBigInteger();
hexOut.append(beforedot.toString(16));
BigDecimal bfd =new BigDecimal(beforedot);
doubleOfDecInp = doubleOfDecInp - bfd.doubleValue();
if(doubleOfDecInp == 0){
return hexOut.toString();
}
hexOut.append(".");
for (int i = 0; i < 16; ++i) {
doubleOfDecInp = doubleOfDecInp * 16;
int digit = (int)doubleOfDecInp;
hexOut.append(Integer.toHexString(digit));
doubleOfDecInp = doubleOfDecInp - digit;
if (doubleOfDecInp == 0)
break;
}
return hexOut.toString();
}
public static void main(String args[]){
String decimalInp = "-0.767";
String out ;
DecimalToHex i = new DecimalToHex();
out = i.decimalToHex(decimalInp);
System.out.println(out);
}
}

Java - static constructor

Hey there Stackoverflowers,
I just started programming in Java and encountered a strange problem concerning printing an object. When a new object of type gast is created the user has to enter his or her birthday. This al works fine, however, if I try to print it out I returns 0-0-0. Why is that? By the way, if I create a new datum directly with the parameter constructor it works fine. Wherein lays the problem? I just can't figure it out. I hope you guys can help me out.
Thanks in advance!
public class Datum {
private static String patroon = "\\d{2}-\\d{2}-\\d{4}";
public int dag;
public int maand;
public int jaar;
Datum(int dag, int maand, int jaar) {
System.out.print("constructor: " + dag);
this.dag = dag;
System.out.println(", dag: " + this.dag);
this.maand = maand;
this.jaar = jaar;
}
Datum() {
newDatum();
}
/* */
public static Datum newDatum() {
String input = Opgave5.userInput("Geboortedatum gast");
boolean b = input.matches(patroon);
if (b) {
String[] str = input.split("-");
int dag = Integer.parseInt(str[0]);
int maand = Integer.parseInt(str[1]);
int jaar = Integer.parseInt(str[2]);
Datum datum = new Datum(dag, maand, jaar);
System.out.println(datum);
return datum;
}
else {
return new Datum();
}
}
public String toString() {
return this.dag + "-" + this.maand + "-" + this.jaar;
}
}
Second class:
Gast() {
this.firstName = Opgave5.userInput("Voornaam gast");
this.lastName = Opgave5.userInput("Achternaam gast");
this.geboortedatum = new Datum();
System.out.println("gast: " + this.geboortedatum); // <--- this prints out 0-0-0
}
public String toString() {
return this.firstName + " " + this.lastName + " " + this.geboortedatum;
}
I think you don't understand constructors in Java. You are merely ignoring the result of newDatum() in the constructor. Also, if it did have the expected effect, it might recurse infinitely in the constructor invocation inside newDatum(). Use something like this; allowing newDatum() to edit the instance will work:
Datum() {
newDatum(this);
}
public static void newDatum(Datum instance) {
String input = Opgave5.userInput("Geboortedatum gast");
boolean b = input.matches(patroon);
if (b) {
String[] str = input.split("-");
int dag = Integer.parseInt(str[0]);
int maand = Integer.parseInt(str[1]);
int jaar = Integer.parseInt(str[2]);
instance.dag = dag;
instance.maand = maand;
instance.jaar = jaar;
System.out.println(instance);
}
else {
new Datum();
}
// ^^ Above code may be buggy, see my answer above code
}
This line:
this.geboortedatum = new Datum();
Is using the default constructor. This will set no values. Try to pass the parameters in via constructor like this:
this.geboortedatum = new Datum(1, 2, 3);
If you want to take advantage of the static method you wrote (which is where you ask for user input), then do the following:
this.geboortedatum = Datum.newDatum();

Returning a double from a method

I am currently writing a program that will read through a designated text file that checks the transaction values of each buy/sell/summary and checks the arithmetic such that if the transactions from the buy and sell statements do not equal the total transaction amount that was given in the summary then it outputs an error and closes the program. But currently my method scanMoneyValue has an error that says it's not returning a double, when in fact it is. Is there a different way I should go about returning the values from my method? Here is my code for reference:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class RecurrsionFileChecker {
public static void main(String[] args) {
int result;
//File Chooser Window
JFileChooser chooser = new JFileChooser("/home/nick/workspace/CS 1410-001/src/assignment03");
chooser.setDialogTitle("Please choose a file to be checked");
result = chooser.showOpenDialog(null);
//User Cancelled the chooser
if (result == JFileChooser.CANCEL_OPTION)
return;
File inputfile = chooser.getSelectedFile();
try
{
Scanner in = new Scanner(inputfile);
//Call Method to look at next transaction
scanNextTransaction(in);
}
catch (IOException e)
{
System.out.println("Could not read file: " + inputfile);
}
}
/**
* Returns double if the parameter Scanner has an error that does,
* not match the summary before it.
*
* #param s Any scanner
* #return double if Summaries don't match.
*/
public static double scanNextTransaction(Scanner s)
{
String buy, sell, summary, date;
double amount = 0, referenceValue, total = 0;
summary = s.next();
date = s.next();
referenceValue = scanMoneyValue(s);
while (s.hasNext())
{
if (s.next() == "Buy")
{
date = s.next();
amount = scanMoneyValue(s);
}
if(s.next() == "Sell")
{
date = s.next();
amount = scanMoneyValue(s);
}
if(s.next() == "Summary")
{
amount = scanSubSummary(s);
}
//add the transactions
total = total + amount;
}
return total;
}
public static double scanMoneyValue(Scanner in)
{
String dollar = in.next();
if(dollar.charAt(0) == '$')
{ //convert string to a double
String amount = dollar.substring(1);
double complete = Double.parseDouble(amount);
complete = complete * 100;
return complete;
}
}
public static double scanSubSummary(Scanner sub)
{
String summaryDate, transDate, transType;
int summarySubEntries, count = 0;
double transValue, summaryValue = 0, totalValue = 0, summaryAmount;
summaryDate = sub.next();
summaryAmount = scanMoneyValue(sub);
summarySubEntries = sub.nextInt();
while (count != summarySubEntries)
{
transType = sub.next();
if (transType == "Summary")
{
summaryValue = scanSubSummary(sub);
}
transValue = scanMoneyValue(sub);
totalValue = transValue + totalValue + summaryValue;
count++;
}
if (totalValue != summaryAmount)
{
System.out.print("Summary error on " + summaryDate + ".");
System.out.println("Amount is $" + summaryAmount + ", " + "should be $" + totalValue + ".");
}
return totalValue;
}
}
public static double scanMoneyValue(Scanner in)
{
String dollar = in.next();
if(dollar.charAt(0) == '$')
{ //convert string to a double
String amount = dollar.substring(1);
double complete = Double.parseDouble(amount);
complete = complete * 100;
return complete;
}
}
If the if condition fails then there's no return statement. You have a return inside of the condition but not outside. You'll need to add a return statement at the end, or throw an exception if not having a dollar sign is an error.
Okay, looking at the only relevant part of your code:
public static double scanMoneyValue(Scanner in)
{
String dollar = in.next();
if(dollar.charAt(0) == '$')
{ //convert string to a double
String amount = dollar.substring(1);
double complete = Double.parseDouble(amount);
complete = complete * 100;
return complete;
}
}
You do return a value if dollar starts with a $... but what do you expect to happen if it doesn't start with $? Currently you reach the end of the method without returning anything, which isn't valid.
You should probably throw an exception, if this is unexpected data that you can't actually handle.
Additionally, you shouldn't really use double for currency values anyway, due to the nature of binary floating point types. Consider using BigDecimal instead.
public static double scanMoneyValue(Scanner in)
{
String dollar = in.next();
if(dollar.charAt(0) == '$')
{ //convert string to a double
String amount = dollar.substring(1);
double complete = Double.parseDouble(amount);
complete = complete * 100;
return complete;
}
//NEED RETURN STATEMENT HERE
}
The error you get is because when you write a function all branches of that function must return a value of the correct type. In your case, if the if-statement fails it hits the end of the function without returning anything.
Its better to change it on
public static double scanMoneyValue(Scanner in)
{
String dollar = in.next();
String amount = dollar.replaceAll("[^\\d.]+", "")
double complete = Double.parseDouble(amount);
complete = complete * 100;
return complete;
}
link on explain - Parsing a currency String in java

how can we auto generate ID on a button click that will contain the concatenation of date,month,year plus a counter?

public class CalendarUtil
{
private Calendar cal = null;
public String getRemId()
{
cal = Calendar.getInstance();
return "" + cal.get(Calendar.DATE) + (cal.get(Calendar.MONTH)+1) + cal.get(Calendar.YEAR);
}
}
How can we auto generate ID on a button click that will contain the concatenation of date,month,year and a 3 digit counter starting form 000 and display it in a textfield? for eg:- 28122012001, 28122012002, etc and so on. Code that i have been trying is as above
I think two static fieds can do it.
private static String lastUsedDatePrefix;
private static int counter;
If you want to nenerate a new ID, check if the dateprefix is the same as stored in lastUsedDatePrefix if yes, increment counter else set counter=0 and set lastUsedDatePrefixto actual date.
Untested implementation:
public class CalendarUtil{
private static String lastUsedDatePrefix = "";
private static int counter = 0;
public String getRemId(){
final String datePrefix = new SimpleDateFormat("ddMMyyy").format(new Date());
if (lastUsedDatePrefix.equals(datePrefix)) {
CalendarUtil.counter++;
}
else{
CalendarUtil.lastUsedDatePrefix = datePrefix;
CalendarUtil.counter = 0;
}
final String counterSuffix = ((100 <= CalendarUtil.counter) ? ""
: (10 <= CalendarUtil.counter) ? "0" : "00")
+ CalendarUtil.counter;
return datePrefix + counterSuffix;
}
}

Categories

Resources