使用扫描仪的字符串数组列表 [英] String array list using Scanner

查看:74
本文介绍了使用扫描仪的字符串数组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

添加了大括号{}和Eclipse屏幕快照

added the braces {} and an Eclipse screenshot

我有一个简单的分配问题,即创建一个具有数组列表的类,该列表用于存储命令行中的单词,每个单词都附加到数组列表的末尾,然后在列表中搜索特定单词("the"),并打印出单词出现的位置,以及另一种方法来返回一个新数组列表,该列表的单词位于数字指定的位置.

I have a problem with a simple assignment to create a class that has an array list to store words from the command-line, with each word appended to the end of the array list, then search the list for a specific word ("the") and prints location of the word's occurences, plus another method to return a new array list with the words at the positions specified by a number.

我写了下面的代码.在Eclipse IDE中,它没有显示任何错误,但是当我尝试通过运行配置"运行代码并输入以下虚拟文本时:快速的棕色狐狸跳过了懒狗.快速的棕色狐狸跳过了懒狗.敏捷的棕狐狸跳过了那只懒狗.",这是行不通的.我不确定为什么,您能给我建议吗?谢谢!

I wrote the code below. In Eclipse IDE, it doesn't show any errors, but when I tried to run the code by Run Configurations and enter this dummy text: "The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.", it doesn't work. I'm not sure why, could you give me advice? Thank you!

import java.util.ArrayList;
import java.util.Scanner;
class Search {
    ArrayList<String> list;

    public Search(){
        list = new ArrayList<String>();
    }

    public void read(){
        Scanner scanner = new Scanner(System.in);
        while(scanner.hasNext()) {
            list.add(scanner.next());
        }
        scanner.close();
    }

    public void find(String word){
        for(int i = 0; i < list.size(); i++) {
            if(list.get(i).equalsIgnoreCase(word)) {
                System.out.println(i);
            }
        }
    }

    public ArrayList<String> subsequence(int[] positions){
        ArrayList<String> result = new ArrayList<String>();
        for(int i = 0; i < positions.length; i++) {
            if(positions[i] >= 0 && positions[i] < list.size()) {
                result.add(list.get(positions[i]));
            }   
        }
        return result;
    }

    // Testing method within class again
    public static void main(String[] args){
        Search search = new Search();
        search.read();
        search.find("the");
        for(String s : search.subsequence(new int[]{0, 3, 4}))
            System.out.println(s);

    }
}  

推荐答案

  • 正如亲爱的 @Chris 所说,请在编码时使用花括号.我用两种不同的方式运行您的代码,并得到了输出.

    • As dear @Chris commented kindly use the braces while coding. I run your code in two different ways and I got the output.

      第一种方式

      如果要与while一起使用 scanner.hashNext(),则应更改 main() read()像这样

      If you want to use scanner.hashNext() with while then you should change your main() and read() like this

      public static void main(String[] args) {
          Search search = new Search();
          Scanner sc = new Scanner(System.in);
          String line = sc.nextLine();
          sc.close();
          search.read(line);
          search.find("the");
          for (String s : search.subsequence(new int[] { 0, 3, 4 })) {
              System.out.println(s);
          }
      }
      
      public void read(String line) {
              Scanner scanner = new Scanner(line).useDelimiter("\\s");
              while (scanner.hasNext()) {
                  list.add(scanner.next());
              }
              scanner.close();
      }
      
      

    • 一个简单的文本扫描程序,可以使用正则表达式解析原始类型和字符串.
    • Scanner 使用定界符模式将其输入分为令牌,默认情况下,该模式与空格匹配.然后,可以使用各种下一种方法将生成的令牌转换为不同类型的值.

    • A simple text scanner which can parse primitive types and strings using regular expressions.
    • A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

      next() hasNext()方法及其原始类型的伴随方法首先跳过与定界符模式匹配的所有输入,然后尝试返回下一个令牌. hasNext() next()都可能阻止等待进一步的输入. hasNext()块是否与其关联的next方法是否将发生阻塞没有联系.

      The next() and hasNext() methods and their primitive-type companion methods first skip any input that matches the delimiter pattern, and then attempt to return the next token. Both hasNext() and next() may block waiting for further input. Whether a hasNext() block has no connection to whether or not its associated next method will block.

      第二种方式

      如果要使用 StringTokenizer ,则只需将 read()更改为现有代码.

      If you want to use StringTokenizer then you should have to change just read() to your existing code.

      public void read(String line) {
          Scanner scanner = new Scanner(System.in);
          StringTokenizer st = new StringTokenizer(scanner.nextLine(), " ");
          while (st.hasMoreElements()) {
              list.add(st.nextElement().toString());
          }
          scanner.close();
      }
      

    • 对于字符串,最好使用 StringTokenizer . StringTokenizer 类允许应用程序将字符串分成令牌.

    • It is always better to use StringTokenizer for the string. The StringTokenizer class allows an application to break a string into tokens.

      StringTokenizer对象在内部维护要标记化的字符串中的当前位置.某些操作会将当前位置提前经过处理的字符.通过获取用于创建StringTokenizer对象的字符串的子字符串来返回令牌.

      A StringTokenizer object internally maintains a current position within the string to be tokenized. Some operations advance this current position past the characters processed. A token is returned by taking a substring of the string that was used to create the StringTokenizer object.

      参考:扫描器 StringTokenizer

      这篇关于使用扫描仪的字符串数组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆