Java 如何读取文本文件中的第一行整数,使用这些数字,然后转到第二行并重复,直到文件结束
这是我的主要方法。我试图从文本文件中读取第一行整数(543784313)。然后我想通过我在main方法中调用的方法运行这些数字。然后我想转到文本文件中的下一行(15160143243),并通过我调用的方法运行这些数字,依此类推,直到到达文本文件的末尾。实现这样的东西的最佳方式是什么?我现在的代码将通过文本文件中的所有整数运行,然后通过方法运行它们Java 如何读取文本文件中的第一行整数,使用这些数字,然后转到第二行并重复,直到文件结束,java,tree,int,text-files,Java,Tree,Int,Text Files,这是我的主要方法。我试图从文本文件中读取第一行整数(543784313)。然后我想通过我在main方法中调用的方法运行这些数字。然后我想转到文本文件中的下一行(15160143243),并通过我调用的方法运行这些数字,依此类推,直到到达文本文件的末尾。实现这样的东西的最佳方式是什么?我现在的代码将通过文本文件中的所有整数运行,然后通过方法运行它们 public static void main(String[] args) { BinaryTree tree = new BinaryT
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
try
{
int num;
Scanner reader = new Scanner(new File("numbers.txt"));
while(reader.hasNextInt())
{
num = reader.nextInt();
if(tree.contains(num))
{
tree.remove(num);
}
else
{
tree.add(num);
}
}
reader.close();
tree.preorder(root);
System.out.println();
tree.inorder(root);
System.out.println();
tree.postorder(root);
System.out.println("\nTotal: " + tree.size(root));
System.out.println("Height: " + tree.height(root));
System.out.println("Max: " + tree.getMax(root));
System.out.println("Min: " + tree.getMin(root));
}
catch(IOException e)
{
e.printStackTrace();
System.exit(1);
}
}
这是我想要使用的名为numbers.txt的文本文件
54378413
15160143243
25 28 71 18 48 35 97
64124040852928659740
76 19 23 40 84 6 67 41 34 66 79 11 38 5 61 60 64 5
81 8 30 80 88 38 90 55 37 45 70 32 41 26我会尝试类似的方法:
public static void main(String[] args) throws Exception {
Scanner reader = new Scanner(new File("numbers.txt"));
while (reader.hasNextLine()) {
String[] temp = reader.nextLine().split("\\s+"); // Regex for any and all whitespace used as a delimiter
for (int x = 0; x < temp.length; x++) {
// Iterate through each element in the string array temp
}
// Resume while loop.
}
}
publicstaticvoidmain(字符串[]args)引发异常{
扫描仪阅读器=新扫描仪(新文件(“numbers.txt”);
while(reader.hasNextLine()){
String[]temp=reader.nextLine().split(\\s+);//用作分隔符的任何和所有空格的正则表达式
对于(int x=0;x
您已经发布了需求和代码,但没有提出具体问题。请修复此问题,以便我们知道如何帮助您。首先使用Scanner#nextLine
读取一行文本,然后使用另一个Scanner
,使用您的hasNextInt
循环来解析它。使用Scanner读取一行文本,然后使用split拆分为单个数字。