简体   繁体   中英

How to solve NoSuchElement in java?

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 .netni 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 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();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM