Home > Software design >  How to solve NoSuchElement in java?
How to solve NoSuchElement in java?

Time:01-10

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

CodePudding user response:

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();
        }
    }
}
  • Related