javaeclipse

Struggling with Java assignment that reads name, age and height


I am working on a java assignment for class. Very basic but just starting to learn programming. The main jist of the assignment is to write a Java program that reads a student name, his/her age, and his/her height (in feet) from the console and prints out all pieces of data related to a student on one line. This is what I have so far but I am getting a few errors.

import java.util.Scanner;

public class assignment1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String Name = Mike;
        int age = 21;
        double height = 5.9;

        Scanner inReader = new Scanner(System.in);

        System.out.println("Mike");

        Name = inReader.nextLine("Mike");

        System.out.print("21");

        age = inReader.nextInt("21");

        System.out.println("5.9");

        height = inReader.nextDouble ("5.9");

        System.out.println ("Mike" + "21" + "5.9");
    }

}

Solution

  • You are off track in a few ways.

    1. inReader.nextLine("Mike"); should be inReader.nextLine();. You cannot put something between those brackets in this case.

    2. String Name = Mike; int age = 21;double height = 5.9; just need to be declared. You want to enter the data in the console, not the code itself. String Name; int age = 0;double height = 0;

    3. System.out.println("Mike"); is not where you put inputs. Rather, it is where you put prompts that go to the user. You want to ask the user for their input there.

    4. To print the variables in a string, you want to put the variable name in the string like so: System.out.println (height);

    The full working code is below, but I encourage you to try and understand how this works. Feel free to ask any questions in the comments below.

    public static void main(String[] args) {
            // TODO Auto-generated method stub
            String Name;
            int age = 0;
            double height = 0;
    
            Scanner inReader = new Scanner(System.in);
            System.out.println("What is their name?");
            Name = inReader.nextLine();
            System.out.println("What is their age?");
            age = inReader.nextInt();
            System.out.println("What is their height?");
            height = inReader.nextDouble ();
            System.out.println (Name + " " + age + " " + "  " + height);
        }