I am working on this code for a school to create a course, users, students, and teachers, but I encountered a problem while creating the course.
What I want to do (in the terminal) is to read an input stream such as "CSC 110 Into to java" and enter all of it into a string. I use Scanner for input. and tried hasNext () and nextLine () besides next (). I was thinking of writing a function to use a char array to get the whole string, and then convert the char array to a string.
At first I wanted to know if there was a simpler solution?
Edit: Sorry, I was not clean. Without going into all my code.
Current Code:
System.out.print("Enter the Course Title: "); title = keyboard.nextLine(); System.out.print("Enter a Brief Course Description: "); desc = keyboard.nextLine(); if (t != null) { do { System.out.println("\nPick a teacher\n"); for (int j = 0; j < t.size(); j++) { nTeacher = t.get(j); s += "\t(" + (j+1) + ") " + nTeacher + "\n"; } System.out.print(s + "\nEnter the Teacher ID: "); int tId = keyboard.nextInt();
Current error:
Enter the Course Title: CSC 110 Into to java Enter a Breif Course Description: Pick a teacher Enter the Teacher ID: Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:857) at java.util.Scanner.next(Scanner.java:1478) at java.util.Scanner.nextInt(Scanner.java:2108) at java.util.Scanner.nextInt(Scanner.java:2067) at Prototype.classCreator(Prototype.java:530) at Prototype.mainMenu(Prototype.java:181) at Prototype.login(Prototype.java:121) at Prototype.main(Prototype.java:48)
When I use nextLine ()
Create Class Enter the courseID: 27222 Enter the Course Title: Enter a Brief Course Description:
Expected Result:
Create Class Enter the courseID: 27299 Enter the Course Title: CSC 110 Into to Java Enter a Brief Course Description: Introduction to programming Pick a teacher (1) ID: 1111 Name: Bob Enter the Teacher ID: 1 Class Created
I understand that when I have three lines of "CSC 110 Intro", it gets input for nextInt (), but I don’t understand why nextLine () writes my println as follows.
source share