Java Discussion Forums

There's no such thing as a stupid question. Ask. Discuss. Learn.

(Beginner) NoSuchElementException when splitting string

Hello! I am trying to display an error message if at least three names have not been entered.
package ;

import javax.swing.JOptionPane;
import java.util.Scanner;

public class Order3Strings {

public static void main(String[] args) {

String title = "String Comparison Project",
title2 = "Welcome to the name ordering program",
name01 = "",
name02 = "",
name03 = "",
names;

int answer = JOptionPane.showConfirmDialog(null, "Do you want to compare strings?", title, JOptionPane.YES_NO_OPTION);

if (answer == JOptionPane.NO_OPTION) {

JOptionPane.showMessageDialog(null, "The program terminates!\nEnd of this program.", title, JOptionPane.WARNING_MESSAGE);
System.exit(0);
}



names = JOptionPane.showInputDialog(null, "Enter the names:", title2, JOptionPane.QUESTION_MESSAGE);

if (names.equals("")|| names.equals("null")) {

JOptionPane.showMessageDialog(null, "This program terminates for invalid input.", title2, JOptionPane.WARNING_MESSAGE);
System.exit(0);
}

Scanner splitter = new Scanner(names);

name01 = splitter.next();
name02 = splitter.next();
name03 = splitter.next();

if (splitter.hasNext() == true); {
JOptionPane.showMessageDialog(null, "Awesome!");
}

if (splitter.hasNext() == false) {
JOptionPane.showMessageDialog(null, "This program terminates for invalid input.", title2, JOptionPane.WARNING_MESSAGE);
}


System.exit(0);

}

}

//After compiling and entering less than three names, I am given this error in the console:
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at lab05.Order3Strings.main(Order3Strings.java:45)

Babae Baeb 7 months ago
  • Whitelisted Links