gpt4 book ai didi

java - 输入文本文件上的正则表达式 float

转载 作者:行者123 更新时间:2023-12-02 04:10:30 25 4
gpt4 key购买 nike

我需要做一份工资报告。您必须键入包含文本信息的文件。程序检查文件是否存在。然后创建程序的输出文件。该程序在文本文件中打印 worker 的姓名、工作时间和工资。我的程序只运行最后一组数字。

 import java.text.NumberFormat;
import javax.swing.JTextArea;
import java.awt.Font;
import javax.swing.JOptionPane;
import java.util.Scanner;
import java.io.*;

public class Homework {

/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {

String answer, filename;


filename = JOptionPane.showInputDialog("Enter the Input File Path:");

File input = new File(filename);
if (!input.exists()) {
JOptionPane.showMessageDialog(null, "The input file:\n" + filename + "\ndoes not exist!");
System.exit(0);
}
filename = JOptionPane.showInputDialog("Enter the Output File Path:");

File output = new File(filename);
if (output.exists()) {
answer = JOptionPane.showInputDialog("The output file alaready exist!\nDo you want to overwrite it?");
if (!answer.toLowerCase().equals("yes")) {
System.exit(0);
}
}






PrintWriter outFile = new PrintWriter(filename);
Scanner in = new Scanner(input);

double numberWords = 0, countNumber = 0;


double value;

String num, words, message;
String amtStr, line = "";

String alphaRegex = ".*[A-Za-z].*";
String numRegex = ".*[0-9].*";



while (in.hasNext()) {
words = in.next();

if (words.matches(alphaRegex)) {

numberWords++;
message = "The name is "+words+"\n"; //The Line is but leave +line+

JOptionPane.showMessageDialog (null, message);



} else if (words.matches(numRegex)) {
countNumber++;
num = in.next();


message = "The number is "+num+"\n"; //The Line is but leave +line+

JOptionPane.showMessageDialog (null, message);

}



}
}

}

最佳答案

导致问题的不是您的正则表达式。这是 while 循环中的 if 语句。当单词与 numRegex 匹配时,您将 in.next() 分配给 num,导致扫描器跳过当前单词并选择下一个单词,在您的情况下,该单词恰好也是一个 num。

用这个替换 while 循环,它将起作用(我已经测试了代码):

while (in.hasNext()) {
words = in.next();

if (words.matches(alphaRegex)) {
numberWords++;
message = "The name is "+words+"\n";
JOptionPane.showMessageDialog (null, message);

} else if (words.matches(numRegex)) {
countNumber++;
num = words; // instead of num = in.next()
message = "The number is "+num+"\n";
JOptionPane.showMessageDialog (null, message);
}
}

关于java - 输入文本文件上的正则表达式 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33839943/

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