0

What would the code to be to allow a user to input text and integers. I am creating a GPA Calculator and the program asks for what course the user is taking, which then is stored as a variable. For example. "Calculus 12." I was able to fix this issue by making the string and the integer two separate variables. How would I make it so that the user can type in "Calculus 12" and have the entire thing be stored as a variable with no issues?

    System.out.println("For the next set of questions, please answer without typing in a number. ");
    System.out.println("For example, 'Pre-Calculus'. ");

    System.out.print( name + ", What is the 1st course are you taking? ");
    course1 = keyboard.next();

    System.out.print("What level is it? Type in a value: ");
    num1 = keyboard.nextInt();
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
  • `String newVariable = course1 + " " + num1;`? – azurefrog Dec 05 '19 at 20:29
  • 3
    [`keyboard.nextLine()`](https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine())? – 001 Dec 05 '19 at 20:30
  • read in the whole line as a single string (see @Johnny's comment), then use string.split to separate out the various fields: `String[] splits = input.split("\\s+");` You can then, if you need the second and/or following fields to be numbers, you can then parse them into numbers with `Integer.parseInt()` – Gus Dec 05 '19 at 20:35

1 Answers1

1

Use keyboard.nextLine() instead of keyboard.next().

Abhijay
  • 278
  • 1
  • 8