I am working on a simple project, I took it from a website that gives some challenge to improve my coding skill in java.
import java.util.Scanner;
public class Test1 {
public void test() {
Scanner in = new Scanner(System.in);
System.out.println("enter something :");
String str = in.nextLine();
StringBuilder sb = new StringBuilder(str);
if (str.isEmpty()) {
System.out.println("you should write something");
}
if(str.length()<=30){
System.out.println("reverse : "+sb.reverse());
}else {
System.out.println("Error");
}
System.out.println("----------------------");
}
public static void main(String[] args) {
Test1 c = new Test1 ();
for (int i = 1; i <= 10 ; i++) {
System.out.println("case number : " +i);
c.test();
}
}
}
case number : 1
enter something : ayoub
reverse : buoya
----------------------
...loop continue ..
My code works like I want in terminal of eclipse, but when I put it into the "code editor" of the web site, this last one gives me a runtime error that says:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at Test1.test(Test1.java:10)
at Test1.main(Test1.java:31)
I tried to search on StackOverflow for some solutions but I didn't find it.
You are probably using an online java code editor/compiler which does not have an stdin input.
As stated by arcy, you are probably using an IDE with a built-in console window which allows you to pass standard inputs to your program.
The following online editor will allow you to add inputs.
You should take care of the way you are using the nextLine method of Scanner:
The exception you are getting is the result of the scanner not getting any inputs, as can be seen here. I suggest you refactor your loop on the scanner using the method hasNextLine of Scanner.
Related
It works well on Intellij.
However, NoSuchElement appears on the algorithmic solution site.
I know that NoSuchElement is a problem caused by trying to receive it even though there is no value entered.
But I wrote it so that the problem of NoSuchElement doesn't occur.
Because given str, the for statement executes. Given "END", the if statement is executed. And because it ends with "break;".
I don't know what the problem is.
Algorithm problem: Arrange the reverse sentence correctly.
My code for algorithmic problems
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
while(true) {
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
if(str.equals("END")){
break;
}
for (int i = str.length()-1; i >=0; i--) {
System.out.print(str.charAt(i));
}
System.out.println();
}
}
}
Output
!edoc doog a tahW
erafraw enirambus detcirtsernu yraurbeF fo tsrif eht no nigeb ot dnetni eW
END
Expected
What a good code!
We intend to begin on the first of February unrestricted submarine warfare
This happens when there is no input at all, for example when you hit Ctrl + d or run your code like echo "" | java Main.java.
To avoid this, check that the Scanner actually has input before trying to grab the next line. Pull scan out of the loop, there is no point to create a new Scanner for each line anyway. Then use hasNext to see if there is input.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
String str = scan.nextLine();
if(str.equals("END")){
break;
}
for (int i = str.length()-1; i >=0; i--) {
System.out.print(str.charAt(i));
}
System.out.println();
}
}
}
I'm using Java Eclipse 2019.3, and no matter what I try I can't get this program to run. It's giving me the 'Selection does not contain a main type' error message.
Things I've tried:
using the formatting 'clean up' option
changing the class name to match that of the file
changing the class name to match that of the file and the folder (file is currently named Main.java, class on code is Main)
updating and restarting Eclipse as a whole
capitalizing and uncapitalizing 'main'
running from the 'Run as' option and clicking 'Java application' manually
creating an entirely new project, copy-and-pasting the code into a new class, and attempting to run it again
Please help, I have no idea what's happening even after checking all the other answers on this forum and others. This is the code:
package australianvoting295;
import java.util.Scanner;
public class Main {
static void australianvoting295 (int[][] args) {
Scanner in = new Scanner(System.in);
System.out.println("Number of cases: ");
int numberofcases = in.nextInt();
System.out.println("");
System.out.println("Number of candidates");
int numberofcandidates = in.nextInt();
if (numberofcandidates <= 20) {
int numberofballotoptions = in.nextInt();
if (numberofballotoptions <= 1000) {
enterCandidateNames(numberofcandidates);
}
}
}
static void enterCandidateNames(int numberofcandidates) {
Scanner in = new Scanner(System.in);
String[] numberofcandidatesarray = new String[numberofcandidates];
int counter = 0;
while (in.hasNext()) {
while (counter < numberofcandidates) {
System.out.println("Enter candidate name:");
String candidatename = in.next();
numberofcandidatesarray[numberofcandidates] = candidatename;
counter++;
}
}
}
}
You are trying too many things to resolve a rather simple error. As Eclipse tells you, if you try to run a class, it should contain a method with the signature
public static void main(String[] args) {
}
Go through this Hello world tutorial for more understanding.
I got an run time exception in my program while I am reading a file through a Scanner.
java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at Day1.ReadFile.read(ReadFile.java:49)
at Day1.ParseTree.main(ParseTree.java:17)
My code is:
while((str=sc.nextLine())!=null){
i=0;
if(str.equals("Locations"))
{
size=4;
t=3;
str=sc.nextLine();
str=sc.nextLine();
}
if(str.equals("Professions"))
{
size=3;
t=2;
str=sc.nextLine();
str=sc.nextLine();
}
if(str.equals("Individuals"))
{
size=4;
t=4;
str=sc.nextLine();
str=sc.nextLine();
}
int j=0;
String loc[]=new String[size];
while(j<size){
beg=0;
end=str.indexOf(',');
if(end!=-1){
tmp=str.substring(beg, end);
beg=end+2;
}
if(end==-1)
{
tmp=str.substring(beg);
}
if(beg<str.length())
str=str.substring(beg);
loc[i]=tmp;
i++;
if(i==size ){
if(t==3)
{
location.add(loc);
}
if(t==2)
{
profession.add(loc);
}
if(t==4)
{
individual.add(loc);
}
i=0;
}
j++;
System.out.print("\n");
}
with Scanner you need to check if there is a next line with hasNextLine()
so the loop becomes
while(sc.hasNextLine()){
str=sc.nextLine();
//...
}
it's readers that return null on EOF
ofcourse in this piece of code this is dependent on whether the input is properly formatted
I also encounter with that problem.
In my case the problem was that i closed the scanner inside one of the funcs..
public class Main
{
public static void main(String[] args)
{
Scanner menu = new Scanner(System.in);
boolean exit = new Boolean(false);
while(!exit){
String choose = menu.nextLine();
Part1 t=new Part1()
t.start();
System.out.println("Noooooo Come back!!!"+choose);
}
menu.close();
}
}
public class Part1 extends Thread
{
public void run()
{
Scanner s = new Scanner(System.in);
String st = s.nextLine();
System.out.print("bllaaaaaaa\n"+st);
s.close();
}
}
The code above made the same exaption, the solution was to close the scanner only once at the main.
You're calling nextLine() and it's throwing an exception when there's no line, exactly as the javadoc describes. It will never return null
https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html
For whatever reason, the Scanner class also issues this same exception if it encounters special characters it cannot read. Beyond using the hasNextLine() method before each call to nextLine(), make sure the correct encoding is passed to the Scanner constructor, e.g.:
Scanner scanner = new Scanner(new FileInputStream(filePath), "UTF-8");
Your real problem is that you are calling "sc.nextLine()" MORE TIMES than the number of lines.
For example, if you have only TEN input lines, then you can ONLY call "sc.nextLine()" TEN times.
Every time you call "sc.nextLine()", one input line will be consumed. If you call "sc.nextLine()" MORE TIMES than the number of lines, you will have an exception called
"java.util.NoSuchElementException: No line found".
If you have to call "sc.nextLine()" n times, then you have to have at least n lines.
Try to change your code to match the number of times you call "sc.nextLine()" with the number of lines, and I guarantee that your problem will be solved.
Need to use top comment but also pay attention to nextLine(). To eliminate this error only call
sc.nextLine()
Once from inside your while loop
while (sc.hasNextLine()) {sc.nextLine()...}
You are using while to look ahead only 1 line. Then using sc.nextLine() to read 2 lines ahead of the single line you asked the while loop to look ahead.
Also change the multiple IF statements to IF, ELSE to avoid reading more than one line also.
I ran into this problem, my structure was:
1 - System
2 - Registration <-> 3 - validate
I was closing Scanner on each of the 3 steps. I started to close the Scanner only in system and it solved.
This question already has answers here:
NoSuchElementException with Java.Util.Scanner
(10 answers)
Closed 6 years ago.
I am trying to build a very basic program in java to print all the unique characters from the string but I am getting runtime error.
Input - amanda
output -amnd
import java.util.*;
class uniquechars {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
System.out.print("Enter a string:");
String str = inp.nextLine(); // input from user
String res="";
for (int i=0;i<str.length();i++){
int count=0;
for(int j=0;j<res.length();j++){
if(str.charAt(i)==res.charAt(j)){
count++;
}
}
if(count==0){
res = res+str.charAt(i);
}
}
System.out.println("Output string with only unique characters:"+res);
}
}
Error
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at uniquechars.main(Main.java:6)
If you are using any online tool to test your code, be sure to provide input to the program.
My guess is you are forgetting to give the input to the program while running it on an online tool.
It works on codechef.com/ide, you just have to select your programming language from the dropdown list. as shown here.
I encountered an error when executing my program.
I execute my program and fed data in an input file.
Contents of the input file
LIMIT
2
ADD 30 60
MUL -60 60
I got an exception error as follows.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Test.doLimit(Test.java:41)
at Test.checkResult(Test.java:24)
at Test.main(Test.java:15)
I googled and I believed that String input = sc.next(); inside the for loop should be causing the error.
May I know how to resolve this error?
My code is as attached below.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
checkResult(input);
}
public static void checkResult(String input)
{
if(input.equals("LIMIT"))
{
//do stuff
doLimit();
}
else if(input.equals("SENT"))
{
//do stuff
}
else
{
//do stuff
}
}
public static void doLimit()
{
Scanner sc = new Scanner(System.in);
int numOfInput = sc.nextInt();
int x,y;
for(int i = 0; i < numOfInput; i++)
{
String input = sc.next();
x = sc.nextInt();
y = sc.nextInt();
if(input.equals("ADD"))
{
//add
}
else if(input.equals("SUB"))
{
//sub
}
else
{
//multiple
}
}
}
You should check if there is more input. You can see in the stack trace that nextInt is involved and if you look at the SDK you would see that this exception is thrown when
input is exausted.
anyway you problem is here :
int numOfInput = sc.nextInt();
so make sure you have valid input before asking for it :
if (sc.hasNextInt()) {
.
.
.
}
The default delimiter of the scanner is the whitespace. However, you plan to use as input for the first 2 lines the new line as delimiter and then either whitespace and new line, as it comes first. Maybe that is the problem. Try writing everything on one line, whitespace separated.
If you are sending the data through the input file, you have to provide that file in the Scanner() constructor.
What you have currently done is provided System.in.
EDIT :
Also, you have to open the Scanner on the file just once and use it throughout. In this case,
1) You are opening the scanner and reading the first line.
2) Then in the doLimit function, you again open the scanner and read the first line of the input file which is not an integer.
Hence, the error.