问题
I really don't see what the problem could be. This is the error I'm getting:
$javac Palindrome.java
$java -Xmx128M -Xms16M Palindrome
Enter your word
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Palindrome.main(Palindrome.java:28)
This is the code:
import java.io.*;
import java.util.Scanner;
import java.util.*;
import java.lang.StringBuffer;
// Java program to illustrate checking of a string
// if its palindrome or not using reverse function
public class Palindrome
{
public static void checkPalindrome(String s)
{
// reverse the given String
String reverse = new StringBuffer(s).reverse().toString();
// check whether the string is palindrome or not
if (s.equals(reverse))
System.out.println("Yes");
else
System.out.println("No");
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your word");
String output = scanner.next();
}
}
I ask for the word and then get the input to check if it is a palindrome
回答1:
I cannot post comments, since I dont have enough reputation. But the solution is that you have no input source.
The line your stacktrace refers to is:
private void throwFor() {
skipped = false;
//since you are using an online tool, you dont actually have an
//input unless you click on the stdin tab and provide an input.
if ( (sourceClosed) && (position == buf.limit()))
throw new NoSuchElementException();
else
throw new InputMismatchException();
}
Just press on the stdin tab and type something in it before executing your code in your online ide and you should not receive an exception anymore. But you should provide some sort of output that reflects your result wheather it is a palindrom :).
回答2:
In online editor this problem occurs in input. Try writing before getting inputs:
if(sc.hasNext())
The code can be written as:
public class Palindrome
{
public static void checkPalindrome(String s)
{
// reverse the given String
String reverse = new StringBuffer(s).reverse().toString();
// check whether the string is palindrome or not
if (s.equals(reverse))
System.out.println("Yes");
else
System.out.println("No");
}
public static void main (String[] args) throws java.lang.Exception
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your word");
if(sc.hasNext())
String output = scanner.next();
}
}
来源:https://stackoverflow.com/questions/50748075/exception-in-thread-main-java-util-nosuchelementexception-at-java-util-scanner