使用分隔符从文件中读取以查找最大和最小,获取整数最大/最小而不是文件中的数字
我试图从文本文件中找到最大和最小的数字,并查看了 stackowerflow 上的其他示例。
但是当我尝试时,我最终得到的是整数最大值和最小值,而不是文件中的值。 由于文件中的数字应该用分号来分隔,因此我尝试使用分隔符。
import java.io.IOException;
import java.util.Scanner;
import java.io.File;
public class LargestAndSmallest
{
public static void main(String[] args) throws IOException
{
File file = new File("src/Number.txt");
if (!file.exists())
{
System.out.println("File not found.");
System.exit(0);
}
Scanner sc = new Scanner(new File("src/Number.txt"));
System.out.println("Writes out numbers from the file so the user can se them");
System.out.println(sc.nextLine());
sc.useDelimiter(";");
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
while (sc.hasNextInt())
{
int currentNumber = sc.nextInt();
if ( currentNumber > max)
{
max = currentNumber ;
}
if ( currentNumber < min)
{
min = currentNumber ;
}
}
sc.close();
System.out.println("Smallest number: " +min);
System.out.println("Largest number: " +max);
}
}
I´m trying to find the largest and smallest number from a textfile and has looked on other examples on stackowerflow.
But when I try I ends upp with Integer max and min value, not values from the file.
Since the numbers in the files are supposed to have semicolon to seperate them, I have tried to use delimiter.
import java.io.IOException;
import java.util.Scanner;
import java.io.File;
public class LargestAndSmallest
{
public static void main(String[] args) throws IOException
{
File file = new File("src/Number.txt");
if (!file.exists())
{
System.out.println("File not found.");
System.exit(0);
}
Scanner sc = new Scanner(new File("src/Number.txt"));
System.out.println("Writes out numbers from the file so the user can se them");
System.out.println(sc.nextLine());
sc.useDelimiter(";");
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
while (sc.hasNextInt())
{
int currentNumber = sc.nextInt();
if ( currentNumber > max)
{
max = currentNumber ;
}
if ( currentNumber < min)
{
min = currentNumber ;
}
}
sc.close();
System.out.println("Smallest number: " +min);
System.out.println("Largest number: " +max);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个
try this
来到您的问题上删除此行
system.out.println(sc.nextline());
在这样做的过程中,您是在将光标移动到null的下一行中,因此您的值将在
您的while liop中不执行,因为sc为null,您已经在执行
system时已经将光标转移到null。 out.println(sc.nextline());
访问此这
尝试此代码以更好地优化; -
时间复杂性 - ; o(n log(n))
Coming to your question remove this line
System.out.println(sc.nextLine());
as doing this you are making your cursor move in the next line of the file which is null so your values are getting initialize with
your while loop is not executing as sc is null you already move your cursor to null while doing
System.out.println(sc.nextLine());
visit this for more explanation
Try This Code for better optimization;-
Time Complexity -; O(n log(n))