简体   繁体   English

扫描字符串时如何使用扫描器方法?

[英]How to use Scanner methods when scanning a String?

I have a text file that consists of a few lines of a small list of integers separated by spaces. 我有一个文本文件,其中包含几行以整数分隔的小整数列表。 I was to scan the first line, and do something for each integer that is in the first line. 我要扫描第一行,并对第一行中的每个整数进行操作。

    String lineString = textScan.nextLine(); //scans the first line of the text file.
    Scanner Line = new Scanner(lineString); //scans the String retrieved from the text file.

    while (Line.hasNextInt())
    { //do stuff 
    }

So I have a scanner (textScan) that scans the first line of the text file and then saves it as a String. 因此,我有一个扫描仪(textScan),它扫描文本文件的第一行,然后将其另存为字符串。 Then I have a second scanner that scans through the String to check if the values in it are integers. 然后,我有第二个扫描器,它扫描字符串以检查其中的值是否为整数。

But the while statement doesn't allow me to use "Line.hasNextInt" to scan through the String! 但是while语句不允许我使用“ Line.hasNextInt”扫描字符串! So how do I scan through the String line to figure out if it has integers or not? 那么,如何在字符串行中进行扫描以确定是否有整数?

EDIT: Sorry, my mistake in wording. 编辑:对不起,我的措辞错误。 The loop will infinitely run, and so I tried creating a print statement before the loop: System.out.println(Line); 该循环将无限运行,因此我尝试在循环之前创建一个打印语句: System.out.println(Line); , and it prints out this error: ,它会打印出此错误:

java.util.Scanner[delimiters=\\p{javaWhitespace}+][position=0][match valid=false] [need input=false][source closed=false][skipped=false][group separator=\\,][decim al separator=.][positive prefix=][negative prefix=\\Q-\\E][positive suffix=][nega tive suffix=][NaN string=\\Q?\\E][infinity string=\\Q∞\\E] java.util.Scanner [delimiters = \\ p {javaWhitespace} +] [position = 0] [match valid = false] [需要输入= false] [源关闭= false] [跳过= false] [组分隔符= \\,] [小数分隔符=。] [正前缀=] [负前缀= \\ Q- \\ E] [正后缀=] [负后缀=] [NaN字符串= \\ Q?\\ E] [无穷大字符串= \\Q∞ \\ E]

The odd thing is that it compiles fine? 奇怪的是它可以编译吗?

The input file: 输入文件:

5 4 4 3 5 
4 2 2 5 3 
5 2 5 2 3 
5 4 3 2 3 
5 4 2 2 5 
4 4 2 4 2 
3 3 5 3 5 
5 2 4 5 2 
4 4 5 4 2 
2 4 3 5 2 
3 3 3 5 3 
2 4 5 3 4 
3 5 5 4 3 
3 4 2 2 4 
5 5 5 4 4 
3 4 4 4 5 
3 2 4 2 4 
5 4 4 2 4 
5 3 5 2 3 

I see the issue. 我看到了问题。 You need to use Line.nextInt() inside the loop to move the cursor. 您需要在循环内使用Line.nextInt()移动光标。

If not, the Line always points to the beginning and the loop never ends. 如果不是,则行始终指向起点,循环永远不会结束。

To use it correctly, call nextInt() so it picks up the next token: 要正确使用它,请调用nextInt(),以获取下一个标记:

while (Line.hasNextInt())
{ 
     System.out.println(Line.nextInt());
}

Infinite Loop: 无限循环:

while (Line.hasNextInt())
{ 
     System.out.println("Infinity");
}

You don't necessary need to solve that problem using scanner. 您无需使用扫描仪解决该问题。

public static void main(String[] args) {

    String myString = "This is not int";
    String myInt = "123456";
    int copyOfInt = 0;
    try {
        copyOfInt = Integer.parseInt(myInt);
        System.out.println(copyOfInt);
        copyOfInt = Integer.parseInt(myString);
        System.out.println(myString);
    } catch (Exception e) {
        System.out.println("Not int");
    }
    // Put this in a loop and you can keep doing stuff
}

Or you can use FileInputStream, which I think is better. 或者您可以使用FileInputStream,我认为这更好。 Here is an example: 这是一个例子:

    try (FileInputStream readFile = new FileInputStream(refFile);
            InputStreamReader readIn = new InputStreamReader(readFile, "UTF8")) {
        BufferedReader ReadBuffer = new BufferedReader(readIn);
        String line = "";
        while ((line = ReadBuffer.readLine()) != null) {
            // Search my string of interest 
            if (line.equals("Potential/V, Current/A")) {
                while ((line = ReadBuffer.readLine()) != null) {
                    // Get data after string of interest 
                    // Use createDataType_1_Object() to get my data
                    myDataArray.add(createDataType_1_Object(line));
                }
            }
        }
    } catch (Exception e) {
        System.out.println(e);
    }

Sorry misunderstood your question earlier in the case you have multiple integers in the same line you can split them using a delimiter and still use a single scanner: 如果您在同一行中有多个整数,可以使用定界符拆分它们,但仍然使用单个扫描仪,那么对不起,您之前的问题会误解您的问题:

String yourFilename = "filename.txt";

File file = new File(yourFilename).useDelimiter(" ");
Scanner sn = new Scanner(file);

while(sn.hasNextInt()){
// Do your work here
}

In while loop you need to put boolean expression: 在while循环中,您需要放入布尔表达式:

while(Boolean_expression)
{
   //Statements
}

You don't input String into Scanner class as a parameter. 您无需将String作为参数输入到Scanner类。 Scanner class takes InputStream source . 扫描程序类采用InputStream source ->Thank you for your comments, my mistake. ->谢谢您的评论,我的错。

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

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