简体   繁体   English

扫描器和多个if语句

[英]Scanners and multiple if statements

I am trying to get a Scanner to read through each line of data and only print out the lines that contain the word "model" followed by a year within the boundaries I set. 我试图让Scanner读取每行数据,然后仅打印出包含“模型”一词的行,然后在我设置的边界内打印一年。 I am not sure if there is a more efficient way to do this, but I made one Scanner for the whole set of data and then within that I declared another one that reads each line. 我不确定是否有更有效的方法来执行此操作,但是我为整个数据集创建了一个Scanner,然后在其中声明了另一个读取每行的数据。 I then tried to set it to look for a String comprised of the word "model" plus the year if the line contains the right year. 然后,我尝试将其设置为查找包含单词“ model”和年份(如果该行包含正确的年份)的字符串。 Since tokens in Scanners are divided by spaces, I thought the correct way to do it would to declare a different String, tokenToken, that combines the first token with a space and the year, if such a combination exists. 由于Scanners中的令牌是用空格分开的,所以我认为正确的方法是声明一个不同的String,TokenToken,该令牌将第一个令牌与一个空格和年份相结合(如果存在这样的组合)。

Currently when I run it, it just runs forever, but never completes 目前,当我运行它时,它会永远运行,但永远不会完成

public static void main(String[] args) {

    Scanner inStream = new Scanner(System.in);

    while (inStream.hasNext()) {

        String line = inStream.nextLine();
        Scanner lineStream = new Scanner(line);

        while (lineStream.hasNext()) {
            String token = lineStream.next();
            if (token.matches("model") && lineStream.hasNextInt()) {
                int year= lineStream.nextInt();
                if ((year>= 1976) && (year <= 2013)) {
                    String tokenToken = (token + " " + year);

                    if (lineStream.hasNext(tokenToken)) {
                        System.out.println(line);
                    } else {
                    }

                }


            }
        }
        lineStream.close();

    }
    inStream.close();
}

To start of, where do you get int from ?? 首先,您从哪里获得int的?

lineStream.hasNextInt()

?? ?? all i can see everywhere are Strings. 我到处只能看到Strings。

Edit: I think this is what you are looking for in terms of splitting the string and processing it correctly. 编辑:我认为这是您在寻找字符串分割和正确处理方面。

Scanner input = new Scanner(System.in);
    String name = input.nextLine();

    String[] parts = name.split(" ");
    String part1 = parts[0];
    String part2 = parts[1];

    int year = Integer.parseInt(part2);      
    if(part1.contains("model")){            
        if((year >= 1976) && (year <= 2013)){
            System.out.println(name);
        }else{
            System.out.println("wtf?");
        }
    }
}

Now what you have to do is just put it into a loop of desired time/size whatever is that you wish 现在,您要做的就是将其放入所需时间/大小的循环中,无论您想要什么

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

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