gpt4 book ai didi

java - 罗马数字到阿拉伯数字的转换器

转载 作者:行者123 更新时间:2023-12-01 13:51:53 25 4
gpt4 key购买 nike

您好,我正在尝试编写将罗马数字(如 MCLII)转换为阿拉伯数字的程序。在电脑和教科书前度过几个小时后,我有一个未完成的代码。请帮我找出为什么程序出错并且最后不打印任何内容。谢谢

public class Main {
public static void romanToDecimal(java.lang.String romanNumber) {
int decimal = 0;
int lastNumber = 0;
String romanNumeral = romanNumber.toUpperCase();

for (int x = romanNumeral.length() - 1; x >= 0 ; x--)
{
char convertToDecimal = romanNumeral.charAt(x);

switch (convertToDecimal)
{
case 'M':
decimal = processDecimal(1000, lastNumber, decimal);
lastNumber = 1000;
break;

case 'D':
decimal = processDecimal(500, lastNumber, decimal);
lastNumber = 500;
break;

case 'C':
decimal = processDecimal(100, lastNumber, decimal);
lastNumber = 100;
break;

case 'L':
decimal = processDecimal(50, lastNumber, decimal);
lastNumber = 50;
break;

case 'X':
decimal = processDecimal(10, lastNumber, decimal);
lastNumber = 10;
break;

case 'V':
decimal = processDecimal(5, lastNumber, decimal);
lastNumber = 5;
break;

case 'I':
decimal = processDecimal(1, lastNumber, decimal);
lastNumber = 1;
break;
}
}
System.out.println(decimal);
}

public static int processDecimal(int decimal, int lastNumber, int lastDecimal)
{
if (lastNumber > decimal)
{
return lastDecimal - decimal;
} else {
return lastDecimal + decimal;
}
}

public static void main(java.lang.String args[]) {
System.out.println("PLEASE ENTER ANY NUMBER IN ROMAN NUMERIC FORMAT:");
Scanner input = new Scanner(System.in);
int romanToDecimal;
romanToDecimal = input.nextInt();
}
}

最佳答案

您没有调用任何方法,因此它不会执行任何操作。只会打印此内容

 System.out.println("PLEASE ENTER ANY NUMBER IN ROMAN NUMERIC FORMAT:");

调用如下方法

romanToDecimal("some tring");

因此您正在从控制台获取用户的输入

就这样吧

 Scanner input = new Scanner(System.in);
romanToDecimal(input);

关于java - 罗马数字到阿拉伯数字的转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19899433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com