我必须添加文件中的数字并平均它们的总和,并计算单词的数量。到目前为止,我有这个,但我得到一个错误,我得到了这个。我试图让它区分单词和字母,但是在第一次运行时出现错误
import javax.swing.JOptionPane;
import java.util.Scanner;
import java.io.*;
public class ReadTextFile
{
public static void main (String[] args) throws IOException
{
String word, line, message, message2;
int number=0 , numword=0, numnum, numnum2, numnum3, av;
FileInputStream fis = new
FileInputStream("C:\\Users\\Douglas\\Desktop\\payroll.txt");
Scanner in = new Scanner (fis);
while (in.hasNext())
{
numword++;
word = in.next();
message2 = "The word is: "+word+"\n";
JOptionPane.showMessageDialog (null, message2);
}
in.close();
while(in.hasNextInt())
{
numnum = in.nextInt();
number++;
message = "The number is: "+numnum+"\n";
numnum2=numnum;
numnum3= numnum+numnum2;
JOptionPane.showMessageDialog (null, message);
av=numnum3/number;
}
in.close();
message = "The number of words processed was "+numword;
JOptionPane.showMessageDialog (null, message);
message2 = "The number of numbers processed was "+number+"and the average
was "+av;
}
}
答案 0 :(得分:0)
您在第一次循环后关闭扫描仪。然后在第二个循环中再次使用它。完成所有扫描后,删除第一个关闭并关闭扫描仪。
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Simple Collapsible</h2>
<button type="button" class="btn btn-info" data-toggle="collapse" data-target="#first">Simple collapsible</button>
<div id="first" class="collapse">
FIRST
</div>
<br>
<button type="button" class="btn btn-info" data-toggle="collapse" data-target="#second">Simple collapsible</button>
<div id="second" class="collapse">
SECOND
</div>
</div>
</body>
</html>
答案 1 :(得分:0)
我让代码更具可读性并且正在尝试。
import javax.swing.JOptionPane;
import java.util.Scanner;
import java.io.*;
public class ReadTextFile {
public static void main(String[] args) throws IOException {
String message, message2;
int number = 0, numnum =0, sum=0;
double av = 0.0;
FileInputStream fis = new FileInputStream("C:\\temp\\file.txt");
Scanner in = new Scanner(fis);
while (in.hasNext()) {
number++;
numnum = in.nextInt();
message = "The number is: " + numnum + "\n";
JOptionPane.showMessageDialog(null, message);
sum += numnum;
av = sum / number;
}
message = "The number of words processed was " + number + " total is " +sum;
JOptionPane.showMessageDialog(null, message);
message2 = "The number of numbers processed was " + number
+ " and the average was " + av;
JOptionPane.showMessageDialog(null, message2);
}
}