gpt4 book ai didi

java - 字符串数组的 parseDouble 元素

转载 作者:行者123 更新时间:2023-11-30 07:58:26 24 4
gpt4 key购买 nike

我正在尝试编写一个 Java 程序来分析文本文件中字符串数组中的每个字符串,如果数字解析为 double ,则程序会打印它前面的单词和后面的单词。我似乎无法找出如何解析字符串数组的每个元素。目前它只会打印第一个数字和后面的单词,而不是前面的单词。希望有人能帮忙。

我的文本文件如下:

假设 49 个人正在切蛋糕,将其分给 5 个人。我给自己切了一大块,占 33.3%整个蛋糕。现在轮到你切一 block 蛋糕了。你也会削减 33.3% 的份额吗?或者你会把剩下的 66.6% 的蛋糕平分 4 份比较公平?你要切多大的片?

这是我的代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

import javax.swing.JOptionPane;


public class NumberSearch {

public static void main(String args[]) throws FileNotFoundException {

//creating File instance to reference text file in Java
// String filedirect = JOptionPane.showInputDialog(null, "Enter your file");
File text = new File("cakeQuestion2.txt");

//Creating Scanner instance to read File in Java

Scanner scnr = new Scanner(text);

//Reading each line of file using Scanner class
int lineNumber = 1;
while(scnr.hasNextLine())
{

String line = scnr.nextLine();
lineNumber++;

//Finding words


String[] sp = line.split(" +"); // "+" for multiple spaces

for (int i = 1; i < sp.length; i++)

{
{

double d = Double.parseDouble(sp[i]);
// System.out.println(+ d);

if (isDouble(sp[i]))

{
// have to check for ArrayIndexOutOfBoundsException
String surr = (i-2 > 0 ? " " + sp[i-2]+" " : "") +
sp[i] +
(i+1 < sp.length ? " "+sp[i+1] : "");


System.out.println(surr);
}

}}
}

}

public static boolean isDouble( String str )
{
try{
Double.parseDouble( str );
return true;
}
catch( Exception e ){
return false;
}}}

最佳答案

嗯……你的代码对于任务来说似乎过于冗长和复杂。

检查这个片段:

public static void main(String args[]) throws FileNotFoundException {
String line = "Suppose 49 are slicing a cake to divide it between 5 people. I cut myself a big slice, consisting of 33.3 percent of the whole cake. Now it is your turn to cut a slice of cake. Will you also cut a 33.3 percent slice? Or will you be fairer and divide the remaining 66.6 percent of the cake into 4 even parts? How big a slice will you cut?";
String[] sp = line.split(" +"); // "+" for multiple spaces
final String SPACE = " ";

// loop over the data
for (int i = 0; i < sp.length; i++) {
try {
// if exception is not raised, IS A DOUBLE!
Double.parseDouble(sp[i]);

// if is not first position print previous word (avoid negative index)
if (i > 0)
System.out.print(sp[i - 1] + SPACE);

// print number itself
System.out.print(sp[i] + SPACE);

// if is not last position print previous word (avoid IOOBE)
if (i < sp.length - 1)
System.out.print(sp[i + 1]);

// next line!
System.out.println();
} catch (NumberFormatException ex) {
// if is not a number, not our problem!
}
}
}

结果:

Suppose 49 are
between 5 people.
of 33.3 percent
a 33.3 percent
remaining 66.6 percent
into 4 even

关于java - 字符串数组的 parseDouble 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40468500/

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