我试图编写一个Java程序来分析文本文件中字符串数组中的每个字符串,如果数字解析为double,程序会打印前面的单词和后面的单词。我似乎无法找到如何解析字符串数组的每个元素。目前它只会打印第一个数字和后面的单词而不是前一个单词。希望有人可以提供帮助。
我的文字文件如下:
假设49人正在切蛋糕,将其分成5人。我削减了一大块,占33.3% 整个蛋糕。现在轮到你切一块蛋糕了。你还会削减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;
}}}
答案 0 :(得分:3)
检查此代码段:
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