如何扫描文本文件的第一行以查找两个整数,并忽略任何字符串?
我必须在文本文件的第一行中搜索两个 Int 值,这两个值将成为二维数组的维度。这是我到目前为止所拥有的...谢谢!
try {
Scanner scan = new Scanner(f);
int rows = scan.nextInt();
int columns = scan.nextInt();
String [][] maze = new String[rows][columns];
}
I have to search the first line of a text file for two Int values that will be the dimensions of a 2D array. Here is what I have so far...Thanks!
try {
Scanner scan = new Scanner(f);
int rows = scan.nextInt();
int columns = scan.nextInt();
String [][] maze = new String[rows][columns];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
另一种方式:
我将把异常处理留给你。如果您的文件不存在、无法读取或者第一行的第一部分和第二部分不是整数,则会出现异常。如果结果为阴性也没关系。
注意:您没有指定有关第一行的任何内容。我假设在这段代码中它们位于开头,用空格分隔。
如果不是,那么您也可以使用字符串拆分,但您必须检查每个拆分部分是否可以转换为整数。如果第一行有 3 个或更多整数,就会出现歧义。因此,我的假设。
One other way:
I'll leave the exception handling up to you. You will have exceptions if your file doesn't exist, can't be read, or if first and second parts of the first line aren't integers. It's ok if they are negative.
Note: you didn't specify anything about how the first line looks like. I assumed in this code they are at the beginning, separated with a whitespace.
If they're not, then you can also use string splitting, but you'll have to check if every splitted part can be converted to an Integer. If you have 3 or more integers in the first line, there will be ambiguities. Hence, my assumptions.