Reputation: 13
import java.util.Scanner;
public class Abcedarian {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a 6 letter word:");
String word = scan.nextLine();
scan.close(); //when would i use this?
int index = word.length() - 1;
for (int i = 0; i < index; i++) {
if (word.charAt(i) <= word.charAt(i + 1)) {
} else {
System.out.println("String is not Abecedarian ");
return;
}
}
System.out.println("String is Abecedarian ");
}
}
I am working on a code to find Abecedarian words and I was told to use scan.close()
but I am unsure of what it is and when to use it.
Upvotes: 1
Views: 443
Reputation: 11464
Learn to find the Javadoc for classes and methods. Your IDE should have some way of navigating to them.
The Javadoc for Scanner.close()
says:
Closes this scanner.
If this scanner has not yet been closed then if its underlying readable also implements the Closeable
interface then the readable's close method will be invoked. If this scanner is already closed then invoking this method will have no effect.
Attempting to perform search operations after a scanner has been closed will result in an IllegalStateException
.
So you can call close when you have finished using the Scanner
. But experiment -- try closing it before you've finished with it and see what happens. Try creating a new Scanner
on System.in
after you've closed one.
In the particular case of your program, calling close doesn't make a difference, but in general closing resources when you are no longer using them is a good idea.
Upvotes: 3