简体   繁体   English

从文本文件中读取没有空格的数字(java)

[英]Reading numbers without spaces from a text file (java)

if we have a text file with the numbers arranged without spaces as follows: 如果我们有一个文本文件,其数字按无空格排列,如下所示:

1223443
1239866

how can each digit be read individually? 如何分别读取每个数字? since we can no longer use the hasNextInt() function. 因为我们不能再使用hasNextInt()函数。

Many ways to do this. 有很多方法可以做到这一点。 For example, read in a single line from the file, then store in in some String s. 例如,从文件中读取一行,然后存储在某些String中。 Then, you can do something simple like use the split() function. 然后,您可以做一些简单的事情,例如使用split()函数。

String s = "1223443 1239866";
String[] numberStrings = s.split(" ");
for (String num : numberStrings)
{
    int value = Integer.parseInt(num);
}

I suggest you read up on the split() method. 我建议您阅读split()方法。 It is very commonly used when parsing Strings. 在解析字符串时非常常用。

To read each digit individually... 要分别读取每个数字...

String s = "1234";
for (char c : s.toCharArray())
{
    int value = Integer.parseInt(String.valueOf(c));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM