## 一道长度转换的题 原

小紅

``````length

1 mile = 1609.344 meters， 代表1英里等于1609.344米；

input.txt

``````1 mile = 1609.344 m
1 yard = 0.9144 m
1 inch = 0.00254 m
1 foot = 0.03048 m
1 fath = 1.8288 m
1 furlong = 201.17 m

1.2 miles
0.15 yard
32.7 inches
127.93 feet
22 faths
0.032 furlong
1 furlong + 2.5 feet
0.9 miles - 18 inches
1 fath - 1 foot + 12.5 inches
3.02 miles + 17.5 yards - 0 fath``````

``````package com.github.alaahong;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.github.alaahong.FormatSeparator.FormatException;

public class Format {

/**
* @author Ian Zhang
* @param args
* @throws FormatException
* @throws NumberFormatException
*/
public static void main(String[] args) throws NumberFormatException,
FormatException {
try {
// read file content from file
List<String[]> tempList = new ArrayList<String[]>();
List<Double> doubleList = new ArrayList<Double>();
Map<String, Double> tempMap = new HashMap<String, Double>();
+ File.separator + "input.txt");
String str = null;
int counter = 0;
while ((str = br.readLine()) != null) {
}
FormatSeparator fs = new FormatSeparator();
for (String[] s : tempList) {
if (counter < 6) {
tempMap.put(s[1], Double.parseDouble(s[3]));
counter++;
} else if (counter++ > 6 && counter < 18) {
Double tempDouble = 0d;
for (int i = 0; i < s.length; i++) {
if (i == 0) {
tempDouble += Double.parseDouble(s[i])* tempMap.get(fs.formatSeparator(s[i + 1]));
} else if (((i - 2) % 3) == 0) {
if (s[i].equals("+")) {
tempDouble += Double.parseDouble(s[i + 1])* tempMap.get(fs.formatSeparator(s[i + 2]));
} else if (s[i].equals("-")) {
tempDouble -= Double.parseDouble(s[i + 1])* tempMap.get(fs.formatSeparator(s[i + 2]));
}
}
}
}
}
br.close();

// write string to file
FileWriter writer = new FileWriter(System.getProperty("user.dir")
+ File.separator + "output.txt");
BufferedWriter bw = new BufferedWriter(writer);
DecimalFormat df = new DecimalFormat("0.00");
String crlf = System.getProperty("line.separator");
bw.write(crlf + "");
for (Double d : doubleList) {
bw.write(crlf + df.format(d) + " m");
}
bw.close();
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}``````
``````package com.github.alaahong;

public class FormatSeparator {
public String formatSeparator(String measure) throws FormatException {
switch (measure) {
case "mile":
measure = "mile";
break;
case "miles":
measure = "mile";
break;
case "yard":
measure = "yard";
break;
case "yards":
measure = "yard";
break;
case "inch":
measure = "inch";
break;
case "inches":
measure = "inch";
break;
case "foot":
measure = "foot";
break;
case "feet":
measure = "foot";
break;
case "fath":
measure = "fath";
break;
case "faths":
measure = "fath";
break;
case "furlong":
measure = "furlong";
break;
case "furlongs":
measure = "furlong";
break;
case "m":
measure = "m";
break;
case "meters":
measure = "m";
break;
default:
throw new FormatException(measure);
}
return measure;

}

public class FormatException extends Exception {
/**
* define my exception
*/
private static final long serialVersionUID = 1L;

public FormatException() {
super();
System.out.println("Formating Error!");
}

public FormatException(String msg) {
super(msg);
System.out.println("Formating Error!");
}
}
}``````

``````class Length
def initialize
@map = Hash.new
@result = Array.new(10,0)
@count = 0
end

def map
@map
end

def setFile(fn = "input.txt")
@file = fn
end

File.open(@file,"r") do |file|
while line=file.gets
if match = /\s*\d+\s*(\w+)\s*=\s*(\d+.\d*)\s*m\s*/.match(line)
@map[match[1]] = match[2].to_f
elsif line.lstrip!=""
calculate(toSingle(line),@count)
@count += 1
end
end
end
end

#把复数变成单数
def toSingle(str)
str = str.gsub(/miles/,"mile")
str = str.gsub(/inches/,"inch")
str = str.gsub(/feet/,"foot")
str = str.gsub(/yards/,"yard")
str = str.gsub(/faths/,"fath")
end

#转化成米为单位
def transfer(str)
if  match = /\s*(\d+(.\d+){0,1})\s*(\w+)/.match(str)
return match[1].to_f * @map[match[3]]
end
end

#计算表达式
def calculate(str,n)
if  match = /(\s*\d+(.\d+){0,1}\s*\w+)((\s*([+-])\s*\d+(.\d+){0,1}\s*\w+)*)/.match(str)
@result[n] += transfer(match[1])
end
if match[3].to_s.lstrip != ""
substr = match[3]
while subMatch = /(([+-])\s*\d+(.\d+){0,1}\s*\w+)(\s*[+-][\d\w\s.]+)*/.match(substr)
if subMatch[2] == "+"
@result[n] += transfer(subMatch[1])
elsif subMatch[2] == "-"
@result[n] -= transfer(subMatch[1])
end
if subMatch[4].to_s.lstrip != ""
substr = subMatch[4]
else
break
end
end

end
end

#保留两位小数
def doFormat
10.times do |i|
@result[i] = format("%.2f",@result[i])
end
end

#写入文件
def appendFile
f = File.new("output.txt","w") #覆盖---w 追加---a
f.puts
10.times do |i|
f.puts(@result[i].to_s + " m" )
end
f.close
end

end

f = Length.new
f.setFile
f.doFormat
f.appendFile``````

``````<?php
\$file = file_get_contents('input.txt');
\$out = explode("\n", \$file);
\$out_val = array();
\$file = fopen("output.txt","a");
fwrite(\$file,"\r\n");

foreach(\$out as \$key => \$value)
{
\$val = explode(' ', \$value);
if(count(\$val) == 1) continue;

if(in_array('=', \$val))
{
if(\$val[1] == 'mile')
{
\$out_val['miles'] = \$val[3];
\$out_val['mile'] = \$val[3];
}
else if(\$val[1] == 'yard')
{
\$out_val['yard'] = \$val[3];
\$out_val['yards'] = \$val[3];
}
else if(\$val[1] == 'inch')
{
\$out_val['inch'] = \$val[3];
\$out_val['inches'] = \$val[3];
}
else if(\$val[1] == 'foot')
{
\$out_val['foot'] = \$val[3];
\$out_val['feet'] = \$val[3];
}
else if(\$val[1] == 'fath')
{
\$out_val['fath'] = \$val[3];
\$out_val['faths'] = \$val[3];
}
else if(\$val[1] == 'furlong')
{
\$out_val['furlong'] = \$val[3];
}
}
else if(in_array('+', \$val) || in_array('-', \$val))
{
\$j = trim(\$val[1]);
\$sum = \$out_val[\$j]*\$val[0];
for(\$i = 1; \$i <= (count(\$val)-2)/3; \$i++)
{
\$j = \$val[\$i*3+1];
\$j = trim(\$j);
\$ret = \$out_val[\$j]*\$val[\$i*3];
if(\$val[\$i*3-1] == '+')
{
\$sum = \$sum+\$ret;
}
else
{
\$sum = \$sum-\$ret;
}
}
\$sum = sprintf("%.2f",\$sum);
fwrite(\$file,"\$sum m\r\n");

}
else
{
\$j = trim(\$val[1]);
\$sum = \$out_val[\$j]*\$val[0];
\$sum = sprintf("%.2f",\$sum);

fwrite(\$file,"\$sum m\r\n");
}
}
fclose(\$file);

?>``````

### 小紅

2015/04/22
150
0

cassiepython
2017/03/09
0
0
【Leetcode】413. Arithmetic Slices

Description A sequence of number is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. For examp......

xiagnming
2018/07/31
0
0

abcdd1234567890
2017/06/14
0
0
Leetcode【526、667、932】

06/18
0
0

12
0
【SpringBoot】产生背景及简介

zw965

4
0

dust8080

6
0
OSChina 周四乱弹 —— 当你简历注水但还是找到了工作

Osc乱弹歌单（2019）请戳（这里） 【今日歌曲】 @花间小酌 ：#今日歌曲推荐# 分享成龙的单曲《男儿当自强》。 《男儿当自强》- 成龙 手机党少年们想听歌，请使劲儿戳（这里） @hxg2016 ：刚在...

3.3K
22

9
0