A
A
Andrey Lyubimenko2019-06-27 22:53:49
Java
Andrey Lyubimenko, 2019-06-27 22:53:49

How can I use Scanner and pass a string to it?

I pass a string to the Scanner, and I get parts from this string, but then using sc.close(); why is the Scanner not reset to the beginning of the line, what's the matter? splin does not need to be applied.

public static void main(String[] args) {
    
    StringBuilder strBuilder = new StringBuilder();
    String str = "My name is yndrew. I'm from Yelarus";
    Scanner sc = new Scanner(str);
    
    String minWord = null;
    int minLenght = 0;
    
    if(sc.hasNext()) {
      minWord = sc.next();
      minLenght = minWord.length();
    }
    
    while(sc.hasNext()) {
      String word = sc.next();
      
      //определяю самое короткое слово
      if(word.length()< minLenght) { 
        minLenght = word.length();
        minWord = word;
      }
    }
      
    //после я имею самое короткое слово minWord
    //и размер этого короткого слова minLenght
    
    char chEnd = minWord.charAt(minLenght - 1);
    System.out.println("Последняя буква самого короткого слова: " + chEnd);
    sc.reset();
    if(sc.hasNext()) {
      System.out.println("+!!!");
    }
    
    while(sc.hasNext()) {
      System.out.println("+");
      String n = sc.next();
      char value = n.charAt(0);
      if(value == chEnd) {
        strBuilder.append(n + " ");
      }
    }
    System.out.println(strBuilder);
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2019-06-28
@andrewlybimenko

The method close()simply closes the scanner's data source if it supports the close operation. In the case of a string, it does nothing. The method reset()resets the scanner settings, but does not affect the state of the data source. So you won't be able to reuse the scanner, you'll have to create a new one.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question