Hello friends,
Started learning Java last week. I have experience with C++ and the similarities between both are making it easier for me to understand Java.
A quick subquestion: Is the scanner class and scanner object the basic equivalent for console input (cin >> ) for C++? And is the + used as the insertion operator (>> and <<) when printing variables/etc? Please forgive my newbiness. I just want to catch and throw out any incorrect assumptions early.
Anyways, here is my code. My problem is that if I ask the user to input a string and then an integer, I get the expected output. If, however, I ask the user to input an int and then a string, after inputting the int, it terminates the program, not allowing me to input a string value in name.
import java.util.Scanner; //Needed for console input object public class FirstClass { public static void main (String [] args) { //User input with different data types Scanner scan = new Scanner(System.in); System.out.println("Enter your name: "); String name = scan.nextLine(); System.out.println("Enter your age: "); int age = scan.nextInt(); System.out.println("Your name is " + name + " and you are " + age + " years old.\n"); } } //OUTPUT: Your name is John Smith and you are 25 years old.
import java.util.Scanner; //Needed for console input object public class FirstClass { public static void main (String [] args) { //User input with different data types Scanner scan = new Scanner(System.in); System.out.println("Enter your age: "); int age = scan.nextInt(); System.out.println("Enter your name: "); String name = scan.nextLine(); System.out.println("Your name is " + name + " and you are " + age + " years old.\n"); } } //OUTPUT: Your name is and you are 25 years old.
Thanks in advance.