Java Merchant‘s Guide to the Galaxy

Problem Three: Merchant’s Guide to the Galaxy

You decided to give up on earth after the latest financial collapse left 99.99% of the earth’s population with 0.01% of the wealth. Luckily, with the scant sum of money that is left in your account, you are able to afford to rent a spaceship, leave earth, and fly all over the galaxy to sell common metals and dirt (which apparently is worth a lot).

Buying and selling over the galaxy requires you to convert numbers and units, and you decided to write a program to help you.

The numbers used for intergalactic transactions follows similar convention to the roman numerals and you have painstakingly collected the appropriate translation between them.

Roman numerals are based on seven symbols:

Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1,000

Numbers are formed by combining symbols together and adding the values. For example, MMVI is 1000 + 1000 + 5 + 1 = 2006. Generally, symbols are placed in order of value, starting with the largest values. When smaller values precede larger values, the smaller values are subtracted from the larger values, and the result is added to the total. For example MCMXLIV = 1000 + (1000 − 100) + (50 − 10) + (5 − 1) = 1944.

• The symbols “I”, “X”, “C”, and “M” can be repeated three times in succession, but no more. (They may appear four times if the third and fourth are separated by a smaller value, such as XXXIX.) “D”, “L”, and “V” can never be repeated.
• “I” can be subtracted from “V” and “X” only. “X” can be subtracted from “L” and “C” only. “C” can be subtracted from “D” and “M” only. “V”, “L”, and “D” can never be subtracted.
• Only one small-value symbol may be subtracted from any large-value symbol.
• A number written in [16]Arabic numerals can be broken into digits. For example, 1903 is composed of 1, 9, 0, and 3. To write the Roman numeral, each of the non-zero digits should be treated separately. Inthe above example, 1,000 = M, 900 = CM, and 3 = III. Therefore, 1903 = MCMIII.
(Source: Wikipedia ( [17]http://en.wikipedia.org/wiki/Roman_numerals)

Input to your program consists of lines of text detailing your notes on the conversion between intergalactic units and roman numerals.

You are expected to handle invalid queries appropriately.

Test input:
glob is I
prok is V
pish is X
tegj is L
glob glob Silver is 34 Credits
glob prok Gold is 57800 Credits
pish pish Iron is 3910 Credits
how much is pish tegj glob glob ?
how many Credits is glob prok Silver ?
how many Credits is glob prok Gold ?
how many Credits is glob prok Iron ?
how much wood could a woodchuck chuck if a woodchuck could chuck wood ?

Test Output:
pish tegj glob glob is 42
glob prok Silver is 68 Credits
glob prok Gold is 57800 Credits
glob prok Iron is 782 Credits
I have no idea what you are talking about

import java.util.*;
public class MyTest {

    /**
     * 初始化罗马符号和数值的对应关系
     */
    HashMap<Character,Integer> initMap = new HashMap<>();
    {
        initMap.put('I',1);
        initMap.put('V',5);
        initMap.put('X',10);
        initMap.put('L',50);
        initMap.put('C',100);
        initMap.put('D',500);
        initMap.put('M',1000);
    }

    /**
     * 计算方法
     * @param inputRomanValue
     * @return
     * @throws Exception
     */
    public int calculate(String inputRomanValue) throws Exception {
        // 判断是否是空串
        if (inputRomanValue.equals("")){
            return 0;
        }
        char[] romans = inputRomanValue.toCharArray();
        int result = 0;
        int repeatI = 0,repeatX = 0,repeatC = 0,repeatM = 0,repeatD = 0,repeatL = 0,repeatV = 0;

        for (int i = 0; i <= romans.length - 1; i++) {
            Character currentKey = null;
            int currentValue = 0;
            Character nextKey = null;
            int nextValue = 0;
            for(Character key:initMap.keySet()){
                if(key == romans[i]){
                    currentKey = key;
                    currentValue = initMap.get(key);
                }
            }

            // The symbols "I", "X", "C", and "M" can be repeated three times in succession
            if('I' == romans[i]){
                repeatI++;
            }else if('X' == romans[i]){
                repeatX++;
            }else if('C' == romans[i]){
                repeatC++;
            }else if('M' == romans[i]){
                repeatM++;
            }else if('D' == romans[i]){
                repeatD++;
            }else if('L' == romans[i]){
                repeatL++;
            }else if('V' == romans[i]){
                repeatV++;
            }
            if(repeatI > 3 || repeatX > 3 ||repeatC > 3 ||repeatM > 3){
                throw new Exception("Not allow " + currentKey + " repeated more than 3 times");
            }
            //  "D", "L", and "V" can never be repeated.
            if(repeatD > 1 || repeatL > 1 ||repeatV > 1){
                throw new Exception("Not allow " + currentKey + " repeated more than 1 times");
            }

            //如果是最后一个则退出循环
            if (i >= romans.length - 1) {
                result += currentValue;
                break;
            }
            // 获取当前位置的下一个值
            for(Character key:initMap.keySet()){
                if(key == romans[i+1]){
                    nextKey = key;
                    nextValue = initMap.get(key);
                }
            }
            if (currentValue == 0) {
                throw new Exception("unexpected roman char:"+romans[i]);
            }
            if (nextValue == 0) {
                throw new Exception("unexpected roman char:"+romans[i + 1]);
            }
            //判断当前值和下一个值的大小
            if (currentValue >= nextValue) {
                result += currentValue;
            }else {
                // "I" can be subtracted from "V" and "X" only.
                if(currentKey == 'I' && nextKey != 'V' && nextKey != 'X'){
                    throw new Exception("Not allow " + nextKey + " subtract" + currentKey);
                }
                // "X" can be subtracted from "L" and "C" only.
                if(currentKey == 'X' && nextKey != 'L' && nextKey != 'C'){
                    throw new Exception("Not allow " + nextKey + " subtract" + currentKey);
                }
                //  "C" can be subtracted from "D" and "M" only.
                if(currentKey == 'C' && nextKey != 'D' && nextKey != 'M'){
                    throw new Exception("Not allow " + nextKey + " subtract" + currentKey);
                }
                //  "V", "L", and "D" can never be subtracted.
                if('V' == romans[i] || 'L' == romans[i] || 'D' == romans[i]){
                    throw new Exception("Not allow " + currentKey + " subtracted");
                }
                result += nextValue - currentValue;
                i++;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        // 从键盘接收数据

        // 判断是否还有输入
        MyTest test = new MyTest();
        while (true){
            if (scan.hasNextLine()) {
                String inputRomanValue = scan.nextLine();
                try {
                    System.out.println("Their money is " + inputRomanValue + ".");
                    System.out.println("My money is  " + test.calculate(inputRomanValue) + ".");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
galaxy 起源于07年的一个数据库导库项目,做一个增删改查的功能,只要几行代码就可以了,只要你会简单的sql语句,就能快速完成一个 功能,相比struts2和spring,着实方便多了. 如果觉得好用,就放弃ssh吧,加入到galaxy的阵营。 1. 完成一个用户管理功能? user.jsp ,这个页面用于新增,修改一个用户 <html> <head></head> <body> <% MyHashMap req = RequestUtil.getRequest(request); MyHashMap obj = new Query("select * from user where id ="+req.getInt("id")); %> <form action="regesiterAction.jsp" method="post"> 用户名<input name="username" value="<%=obj.getString("username")%>" /> 密码<input type="password" value="<%=obj.getString("password")%>" name="password" /> 手机号: <input name="telphone" value="<%=obj.getString("username")%>" /> <input type="hidden" name="action" value="saveorupdate" /> <input type="submit" value="提交" /> </form> </body> </html> userAction.jsp <% MyHashMap req = RequestUtil.getRequest(request); if(req.getString("action").equals("saveorupdate")){ new Imp().saveOrUpdate(req); }else if(req.getString("action").equals("del")){ new Query().update("delete from user where id="+req.getString("id")); } response.sendRededict("user.jsp"); %> 用户列表页面 <html> <body> <form> <table> <tr><td>用户名</td><td>密码</td><td>手机号</td> <% MyHashMap req = RequestUtil.getReq(request); int pagesize = req.getInt("pagesize",10); int pageindex = req.getInt("pageindex",1); List<MyHashMap> list = new Query().getByPaging("select * from user where "+condition,pagesize,pageindex); MyHashMap pageinfo = list.get(0); for(MyHashMap map:list){ %> <tr> <td><%=map.getString("username")%></td> <td><%=map.getString("password")%></td> <td><%=map.getString("telphone")%></td> </tr> <%}%> </table> <%=com.zxhy.fxpt.common.util.StringUtil.getdaohang(pageinfo.getInt("pagecount"),pageinfo.getInt("pagenum"))%> </form> </body> </html> 有兴趣的话,跟我联系qq: 376860997
galaxy 起源于07年的一个数据库导库项目,做一个增删改查的功能,只要几行代码就可以了,只要你会简单的sql语句,就能快速完成一个 功能,相比struts2和spring,着实方便多了. 如果觉得好用,就放弃ssh吧,加入到galaxy的阵营。 1. 完成一个用户管理功能? user.jsp ,这个页面用于新增,修改一个用户 <html> <head></head> <body> <% MyHashMap req = RequestUtil.getRequest(request); MyHashMap obj = new Query("select * from user where id ="+req.getInt("id")); %> <form action="regesiterAction.jsp" method="post"> 用户名<input name="username" value="<%=obj.getString("username")%>" /> 密码<input type="password" value="<%=obj.getString("password")%>" name="password" /> 手机号: <input name="telphone" value="<%=obj.getString("username")%>" /> <input type="hidden" name="action" value="saveorupdate" /> <input type="submit" value="提交" /> </form> </body> </html> userAction.jsp <% MyHashMap req = RequestUtil.getRequest(request); if(req.getString("action").equals("saveorupdate")){ new Imp().saveOrUpdate(req); }else if(req.getString("action").equals("del")){ new Query().update("delete from user where id="+req.getString("id")); } response.sendRededict("user.jsp"); %> 用户列表页面 <html> <body> <form> <table> <tr><td>用户名</td><td>密码</td><td>手机号</td> <% MyHashMap req = RequestUtil.getReq(request); int pagesize = req.getInt("pagesize",10); int pageindex = req.getInt("pageindex",1); List<MyHashMap> list = new Query().getByPaging("select * from user where "+condition,pagesize,pageindex); MyHashMap pageinfo = list.get(0); for(MyHashMap map:list){ %> <tr> <td><%=map.getString("username")%></td> <td><%=map.getString("password")%></td> <td><%=map.getString("telphone")%></td> </tr> <%}%> </table> <%=com.zxhy.fxpt.common.util.StringUtil.getdaohang(pageinfo.getInt("pagecount"),pageinfo.getInt("pagenum"))%> </form> </body> </html> 有兴趣的话,跟我联系qq: 376860997
药店药品信息管理系统是一种基于Java语言开发的管理系统,旨在更好地管理和维护药店药品信息管理工作。该系统可以通过录入、增加、删除、修改、查询、浏览药品信息等操作,来实现对药品信息的管理。系统分为管理员、商家和用户三种角色,管理员可以管理商家,商家可以管理药品信息,用户可以查询药品信息和下单购买药品。 以下是药店药品信息管理系统Java的实现步骤: 1. 首先,需要设计数据库,包括药品信息表、商家信息表、用户信息表等。 2. 然后,需要编写Java代码实现对数据库的连接和操作,包括增加、删除、修改、查询等操作。 3. 接着,需要编写前端页面,包括登录页面、注册页面、药品信息管理页面、商家信息管理页面等。 4. 最后,将前端页面和Java代码进行整合,实现一个完整的药店药品信息管理系统。 以下是一个简单的药店药品信息管理系统Java代码示例: ```java // 数据库连接类 public class DBUtil { private static final String URL = "jdbc:mysql://localhost:3306/medicine"; private static final String USER = "root"; private static final String PASSWORD = "123456"; public static Connection getConnection() throws SQLException { return DriverManager.getConnection(URL, USER, PASSWORD); } } // 药品信息类 public class Medicine { private int id; private String name; private String type; private double price; // 构造函数、getter和setter方法 } // 药品信息DAO类 public class MedicineDAO { public void addMedicine(Medicine medicine) { // 实现添加药品信息的代码 } public void deleteMedicine(int id) { // 实现删除药品信息的代码 } public void updateMedicine(Medicine medicine) { // 实现修改药品信息的代码 } public Medicine getMedicineById(int id) { // 实现根据ID查询药品信息的代码 } public List<Medicine> getAllMedicines() { // 实现查询所有药品信息的代码 } } // 商家信息类 public class Merchant { private int id; private String name; private String address; private String tel; // 构造函数、getter和setter方法 } // 商家信息DAO类 public class MerchantDAO { public void addMerchant(Merchant merchant) { // 实现添加商家信息的代码 } public void deleteMerchant(int id) { // 实现删除商家信息的代码 } public void updateMerchant(Merchant merchant) { // 实现修改商家信息的代码 } public Merchant getMerchantById(int id) { // 实现根据ID查询商家信息的代码 } public List<Merchant> getAllMerchants() { // 实现查询所有商家信息的代码 } } // 用户信息类 public class User { private int id; private String name; private String address; private String tel; // 构造函数、getter和setter方法 } // 用户信息DAO类 public class UserDAO { public void addUser(User user) { // 实现添加用户信息的代码 } public void deleteUser(int id) { // 实现删除用户信息的代码 } public void updateUser(User user) { // 实现修改用户信息的代码 } public User getUserById(int id) { // 实现根据ID查询用户信息的代码 } public List<User> getAllUsers() { // 实现查询所有用户信息的代码 } } // 主函数类 public class Main { public static void main(String[] args) { // 实现主函数的代码 } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值