请提供将GB值转换为MB值的Groovy代码
GB转MB的Groovy实现代码
下面是对应你提供的Java实现的Groovy版本,Groovy简化了Java里的冗余代码,实现起来更简洁:
// 定义GB到MB的转换系数,这里用十进制的1000,若需二进制转换可改为1024 final double GB_IN_MB = 1000 // 获取用户输入 print "Enter the number of GB(s): " def numberOfGBs = System.in.newReader().readLine().toDouble() // 计算转换结果 def numberOfMBs = numberOfGBs * GB_IN_MB // 格式化输出结果 printf "%f GB equals %f MB%n", numberOfGBs, numberOfMBs
代码说明:
- Groovy无需显式导入
Scanner或PrintStream,直接通过System.in.newReader()获取输入,比Java的Scanner用法更简洁 - 不需要编写类和main方法,直接以脚本形式运行即可
- 保留了原Java代码的核心逻辑:输入GB数值、乘以转换系数、格式化输出结果
- 如果需要二进制转换(1GB=1024MB),只需修改
GB_IN_MB的值为1024即可
参考的Java实现:
package P; import java.io.PrintStream; import java.util.Scanner; public class C { static final double GB_IN_MB = 1000; PrintStream out; Scanner in; C() { out = new PrintStream(System.out); in = new Scanner(System.in); } void start() { out.printf("Enter the number of GB(s): "); double numberOfGBs = in.nextDouble(); in.close(); double numberOfMBs = numberOfGBs * GB_IN_MB; out.printf("%f GB equals %f MB\n", numberOfGBs, numberOfMBs); } public static void main(String[] args) { new C().start(); } }
内容的提问来源于stack exchange,提问作者Sumedh Mahajan
相关产品推荐
相关产品推荐

