0

Still fairly new to Java and I am having trouble with this loop. the first issue is that I can only enter a single word for newName, if I try and enter more then one word, it uses the input for the newCode as well and skips through. I just can't figure out why I cant enter a name that has more then 1 word in a string. when I try and add a string with 3 words in it it skips the newCode then throws an error.

    int addAnother = 1;
    while (addAnother == 1) {
        
        System.out.print("Enter a new Subject Name: ");
        String newName = input.next();      //only accepting a single word...
        System.out.print("Enter a new Subject Code: ");
        String newCode = input.next();      // must be entered in CAPS
        Subject newSubject = new Subject(newName, newCode);//create object
        if (newSubject.isValidCode(newCode) == true){
            System.out.println("The code meets the requirements");
            if (newSubject.codeExist(newCode, subjectList) == false){
                subjectList.add(newSubject);
                System.out.println("Your Subject has been added");   
            }
            else 
                System.out.println("The code you entered already exists");    
        }
        else
            System.out.println("Your subject code does not "
                    + "meet the requirements i.e. ITC206");
      
        System.out.println ("\nEnter a new subject? 1=Yes 2=No");
        addAnother = input.nextInt();      
    }

I am just not sure what I am doing wrong....

Jandie
  • 17
  • 4
  • `input.next()` always returns just one next token. If you want to enter more words, you should use `input.nextLine()`. – DYZ Oct 11 '20 at 05:05

1 Answers1

0

Use nextLine() method instead of next().

private String read()
{
    Scanner scanner = new Scanner(System.in);
    return scanner.nextLine();
}

https://www.geeksforgeeks.org/difference-between-next-and-nextline-methods-in-java/

Numery
  • 402
  • 1
  • 6
  • 16