Home > Software design >  Is there a reason this runs with 3 inputs but not 2?
Is there a reason this runs with 3 inputs but not 2?

Time:12-04

When user gives input for name1, name2, and name3, the output is fine. However, when only name1 and name2 receive input, there is an error?

import java.util.Scanner; 

public class LabProgram {
   public static void main(String[] args) {
      /* Type your code here. */
      Scanner scnr = new Scanner(System.in);
      
      String name1, name2, name3;

        name1 = scnr.next();
        name2 = scnr.next();
        name3 = scnr.next();

        if (name3.equals("")){
            System.out.println(name2   ", "   name1.charAt(0)   ".");
        }
        else{
            name3 = name3.substring(0);
            System.out.println(name3   ", "   name1.charAt(0)   "."   name2.charAt(0)   ".");
        }
   }
}

The exception:

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 LabProgram.main(LabProgram.java:12)

CodePudding user response:

name3 = scnr.next();

is throwing the java.util.NoSuchElementException because there is no third input. You are trying read from System.in and there is nothing there to read.

  • Related