java - 如何分别获得尾数和指数值
问题描述
我已经看到了类似的问题,但仍然没有找到我的问题的答案。我需要做的是,我有一个字符串数组:
private String[] scientificNumberData = "2e3, 2e4, 6e3".split(", "); //[2e3, 2e4, 6e3]
我需要将尾数和指数分开才能返回List<ScientificNumber>
。至于那个,我尝试创建键表示尾数和值指数列表的 Map,因为我可能有重复的键并且无法以其他方式将它们分开。
从这段代码中,我的地图看起来像这样:{2=[3, 4, 3], 6=[3, 4, 3]}
,但应该是2=[3, 4], 6=[3]}
。
有没有更好的解决方案,或者我可以以某种方式修复我的代码以获得正确的输出来使用List<ScientificNumber>
?
public List<ScientificNumber> getScientificNumbers() {
List<ScientificNumber> result = new LinkedList<>();
Map<Integer, List<Integer>> separateExponent = new LinkedHashMap<>();
List<Integer> exs = new LinkedList<>();
int mantissa = 0;
int exponent = 0;
for(String str: scientificNumberData){
for (int i = 0; i < str.length(); i++){
if(str.charAt(i) != 'e'){
if(matiss == 0){
if(!(separateExponent.containsKey(str.charAt(i)))){
mantissa = Integer.parseInt(String.valueOf(str.charAt(i)));
separateExponent.put(mantissa, exs);
}else{
mantissa = Integer.parseInt(String.valueOf(str.charAt(i)));
}
}else{
exponent = Integer.parseInt(String.valueOf(str.charAt(i)));
}
}
}
// if there is a duplicate key already
if(separateExponent.containsKey(mantissa)){
separateExponent.get(mantissa).add(exponent);
}else {
// if not duplicate key
separateExponent.put(mantissa, Collections.singletonList(exponent));
}
// change back to default values
mantissa = 0;
exponent = 0;
}
// works, but since wrong output the total will be wrong
for(Map.Entry<Integer, List<Integer>> entry : separateExponent.entrySet()){
for(int i = 0; i < entry.getValue().size(); i++){
result.add(new ScientificNumber(entry.getKey(), entry.getValue().get(i)));
}
}
return result;
}
ScientificNumber.java 文件如下所示:
public class ScientificNumber {
private int mantissa;
private int exponent;
public ScientificNumber(int mantissa, int exponent) {
this.mantissa = mantissa;
this.exponent = exponent;
}
public int intValue() {
return mantissa * Double.valueOf(Math.pow(10, exponent)).intValue();
}
}
解决方案
将以下方法添加到ScientificNumber
类中:
public static ScientificNumber parse(String str) {
int idx = str.indexOf('e');
if (idx == -1)
return new ScientificNumber(Integer.parseInt(str), 0);
return new ScientificNumber(Integer.parseInt(str.substring(0, idx)),
Integer.parseInt(str.substring(idx + 1)));
}
反过来当然是:
@Override
public String toString() {
return this.mantissa + "e" + this.exponent;
}
推荐阅读
- c# - 无法从 ASP.NET Core 2.1 控制器获取 IdentityUser 数据
- git - 使用 TortoiseGit 清除旧的提交
- ios - 角度 6 - 最新 ios 上的 3d touch 问题
- tensorflow - TensorFlow 中的“Flex Op”是什么意思?
- bash - 使用 AppleScript 或 Automator 从文本文件中查找和复制带有文本字符串的图像,并将图像复制到另一个文件夹
- ios - Xcode - 更改框架的搜索路径
- sql-server - 为什么我们需要删除表来重新链接它们?
- android - 如何将 Glide 与 onBindViewHolder 集成?
- javascript - .then() 在前一个 .then() 返回之前触发
- swift - 从 iOS MPMediaLibrary 中删除播放列表