Struggling with Java assignment that reads name, age and height - java

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");
}
}

You are off track in a few ways.
inReader.nextLine("Mike"); should be inReader.nextLine();. You cannot put something between those brackets in this case.
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;
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.
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);
}

Here ist a first solution to give you a starting point:
public static void main(String[] args) {
String name ;
int age ;
double height;
Scanner inReader = new Scanner(System.in);
System.out.println("Enter name:");
name = inReader.nextLine();
System.out.println("Enter age:");
age = inReader.nextInt();
System.out.println("Enter height");
height = inReader.nextDouble();
System.out.println ("name: " + name + ", age: " +age + ", height: " + height);
}
The above code will work as long as you enter valid input. Try it. Then input something invalid (for example a char for age)

Related

How do I accept the user input and put it into the while condition

This is my code, the while loop does not have an input and the rep variable does not accept an input:
import java.util.Scanner;
public class MixedData {
public static void main(String[] args) {
String rep = "";
do {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your full name");
String name = keyboard.nextLine();
System.out.print("Enter your GPA: ");
double gpa = keyboard.nextDouble();
System.out.println("Name: " + name + ", GPA: " + gpa);
System.out.println("Do you want to enter the data for another student?(y/n)");
rep = keyboard.nextLine();
} // This does not accept input
while (rep.equals("y"));
}
}
Either just add one more keyboard.nextLine() before rep = keyboard.nextLine(); (in order to clear the newline character), or read your double gpa value with:
double gpa = Double.parseDouble(keyboard.nextLine());
Important point to understand here (especially if you're a novice Java developer), about why your code doesn't work, is, that you invoke nextDouble() as a last method on your Scanner instance, and it doesn't move the cursor to the next line.
A bit more details:
All the methods patterned nextX() (like nextDouble(), nextInt(), etc.), except nextLine(), read next token you enter, but if the token isn't a new line character, then the cursor isn't moved to the next line. When you enter double value and hit Enter, you actually give to the input stream two tokens: a double value, and a new line character, the double value is initialized into the variable, and the new line character stays into input stream. The next time you invoke nextLine(), that very new line character is read, and that's what gives you an empty string.
Here's the same code using a while loop instead of do-while. It works the way you want it to.
import java.util.Scanner;
public class MixedData {
public static void main(String[] args) {
String rep = "y";
while (!rep.equals("n")) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your full name: ");
String name = keyboard.nextLine();
System.out.print("Enter your GPA: ");
double gpa = keyboard.nextDouble();
System.out.println("Name: " + name + ",GPA: " + gpa);
System.out.println("Do you want to enter the data for another student?(y/n)");
rep = keyboard.next();
}
}
}
You need to skip blank lines.
public static void main(String[] args) {
String rep;
Scanner keyboard = new Scanner(System.in);
do {
System.out.print("Enter your full name");
String name = keyboard.nextLine();
System.out.print("Enter your GPA: ");
double gpa = keyboard.nextDouble();
System.out.println("Name: " + name + ", GPA: " + gpa);
System.out.println("Do you want to enter the data for another student?(y/n)");
rep = keyboard.next();
keyboard.skip("\r\n"); // to skip blank lines
}
while (rep.equalsIgnoreCase("y"));
keyboard.close();
}
Use nextLine instead of nextDouble:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String rep = "";
do {
System.out.println("Enter your full name:");
String name = keyboard.nextLine();
System.out.println("Enter your GPA:");
// double gpa = keyboard.nextDouble();
double gpa = Double.parseDouble(keyboard.nextLine());
System.out.println("Name: " + name + ", GPA: " + gpa);
System.out.println("Do you want to enter the data for another student?(y/n)");
rep = keyboard.nextLine();
} while (rep.equals("y"));
keyboard.close();
}

How to compare attributes from multiple class instances?

Alright, so here's the pickle. I'm taking this course that teaches logic programming in Java. I only know a bit of JavaScript so Java is pretty much alien tech for me.
I'm doing this assignment where I need to create a conference manager app (which is console-based only). Each conference holds lectures (as many as you want). Each conference has attributes such as the conference manager's name, his telephone number, his hourly rate etc; and it's the same for the lectures. I wanted to be able to input these data with Scanner method. So this is what I did so far:
Started creating two classes:
1) a conference creator
import java.util.*;
public class Conference {
String nameConference;
String nameManagerConference;
String telManagerConference;
String dateStartConference;
String dateEndConference;
float hourlyRateManager;
float hoursAmountConference;
public void setConferenceData() {
Scanner keyboard = new Scanner(System.in);
System.out.print("Conference name: ");
this.nameConference = keyboard.nextLine();
System.out.print("Conference manager name: ");
this.nameManagerConference = keyboard.nextLine();
System.out.print("Conference manager telephone number: ");
this.telManagerConference = keyboard.nextLine();
System.out.print("Conference start date: ");
this.dateStartConference = keyboard.nextLine();
System.out.print("Conference end date: ");
this.dateEndConference = keyboard.nextLine();
System.out.print("Manager hourly rate: ");
this.hourlyRateManager = keyboard.nextFloat();
System.out.print("Conference amount of hours: ");
this.hoursAmountConference = keyboard.nextFloat();
System.out.println(this.nameManagerConference + ", manager of the conference " + "\"" + this.nameConference +"\"" + ", cost R$ " + (this.hoursAmountConference * this.hourlyRateManager));
}
}
2) a lecture creator
import java.util.*;
public class Lectures {
float totalCost = 0;
String lecturesList = "Lectures list: ";
ArrayList<Float> arrLecturesCostTotal = new ArrayList<>();
ArrayList<String> listLectures = new ArrayList<>();
public void getLecturesTotalCost() {
for (int i = 0; i < arrLecturesCostTotal.size(); i++) {
totalCost += arrLecturesCostTotal.get(i);
}
System.out.println("The total lectures cost is $ " + totalCost);
}
public void getLecturesList() {
for (int i = 0; i < listLectures.size(); i++) {
lecturesList += "\n" + "- " + listLectures.get(i);
}
System.out.println(lecturesList);
}
public class Lecture{
String lectureTitle;
String lectureStartHour;
String lecturerName;
String lecturerTelephone;
String lectureDescription;
float lecturerHourlyRate;
float lectureHoursAmount;
float lectureCost = 0;
public void setDataLecture() {
Scanner keyboard = new Scanner(System.in);
System.out.print("Lecture title: ");
this.lectureTitle = keyboard.nextLine();
System.out.print("Lecture start time: ");
this.lectureStartHour = keyboard.nextLine();
System.out.print("Lecturer name: ");
this.lecturerName = keyboard.nextLine();
System.out.print("Lecturer telephone number: ");
this.lecturerTelephone = keyboard.nextLine();
System.out.print("Lecture description: ");
this.lectureDescription = keyboard.nextLine();
System.out.print("Lecturer hourly rate ");
this.lecturerHourlyRate = keyboard.nextFloat();
System.out.print("Lecture hours amount: ");
this.lectureHoursAmount = keyboard.nextFloat();
this.lectureCost = this.lecturerHourlyRate * this.lectureHoursAmount;
System.out.println("The cost of the lecture " + this.lecturerName + " is $ " + this.lectureCost);
arrLecturesCostTotal.add(this.lecturerHourlyRate * this.lectureHoursAmount);
listLectures.add(this.lectureTitle + " by " + this.lecturerName);
}
}
}
As you can see, there are a lot of attributes to each class.
Then, I proceeded to create another class to create the objects using these setters (setConferenceData() and setDataLecture()).
public class Manager {
public static void main(String[] args) {
Conference conference01 = new Conference();
Lectures lectureSet = new Lectures();
Lectures.Lecture lecture01 = lectureSet.new Lecture();
Lectures.Lecture lecture02 = lectureSet.new Lecture();
conference01.setConferenceData();
lecture01.setDataLecture();
lecture02.setDataLecture();
lectureSet.getLecturesList();
lectureSet.getLecturesTotalCost();
}
}
So, one of the deliverables is a comparison between the lectures' costs. I need to return the most and the least expensive lectures (their costs and their names). However, I can't figure out how to do that because I don't know how to compare instances' attributes values. Specially because they're created by inputting data in the console.
My logic is probably wrong as I'm pretty much experimenting and crossing my fingers so I don't see an error in the console, but this is all I could come up with.
Could someone assist me, please?
Few tips here.
You probably should not call Scanner in you data classes. Instead call scanner in your main method and just feed the results to your classes through constructor or setters. This way you separate concerns and classes like Conference and Lecture don't need to know anything about your input method (scanner in this case).
Conference should contain lectures means that List<Lecture> should probably be field inside the class Conference among other fields.
Lecture should probably have two fields (among other stuff) double lengthHours and double hourlyCost. Then you could have a method in Lecture:
public double totalCost() {
return hourlyCost * lengthHours;
}
And then you could have a method in Conference:
public double totalCost() {
double lecturesTotal = 0.0;
for (Lecture lecture : lectures {
lecturesTotal += lecture.totalCost();
}
return lecturesTotal + //other stuff like conference managers pay;
}
Hope that gets you going in the right direction.

Errors in Java check integer is inputted

I know that the question has been asked but I tried to apply what I saw here and got an error.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner get_input = new Scanner(System.in);
System.out.println("Enter your name ");
String name = get_input.nextLine();
boolean is_int = false;
int year_of_birth = 0;
System.out.println("Enter your year of birth");
while (!get_input.hasNextInt()) {
// If the input isn't an int, the loop is supposed to run
// until an int is input.
get_input.hasNextInt();
year_of_birth = get_input.nextInt();
}
//year_of_birth = get_input.nextInt();
System.out.println("Enter the current year");
int current_year=get_input.nextInt();
int age = current_year-year_of_birth;
System.out.println("Your name is " + name + " and you are " + age + " year old.");
get_input.close();
}
}
Without the loop, everything works fine. What is wrong in my code? To be clear, I'm trying to ask for an input until the input can be validated as an integer.
Thanks a lot in advance.
If you would like to skip invalid non-int values, your loop should look like this:
while (!get_input.hasNextInt()) {
// skip invalid input
get_input.next();
}
// here scanner contains good int value
year_of_birth = get_input.nextInt();
This works for me if i understood you correctly. You need to keep checking what value has the scanner, so you need to keep advancind through the scanner while the value is not an integer:
Scanner get_input = new Scanner(System.in);
System.out.println("Enter your name ");
String name = get_input.nextLine();
int year_of_birth = 0;
System.out.println("Enter your year of birth");
while (!get_input.hasNextInt()) { //check if it is not integer
System.out.println("Enter your year of birth"); // ask again
get_input.next(); //advance through the buffer
}
year_of_birth = get_input.nextInt(); //here you get an integer value
int current_year=get_input.nextInt();
int age = current_year-year_of_birth;
System.out.println("Your name is " + name + " and you are " + age + " year old.");
get_input.close();

Simplest Dialog/Message Box for beginners?

I am unsure of how to do this. I am in a intro to java class and it asks us to use a message box (instead of just system.out.println) I remember we imported something and it was an easy change, but I am unable to find any notes on it.
Furthermore all examples I've found across the web and this site are taking it beyond the scope of this class.
I apologize in advance if this is an incorrect format, this is my first time posting here.
TLDR: Trying to change
System.out.print("Enter renter name: ");
renterName = input.next();
to appear in a message box instead of in the Eclipse Console
I know we imported something (same way we import Scanner) to make this work, but every example I find is essentially saying create your own dialog box methods which is beyond my scope of knowledge, and this class.
COMPLETE CODE IS FOLLOWS:
import java.util.Scanner;
public class RentYourVideo {
public static void main(String[] args) {
int numberOfRentals, finalBill;
VideoRental rental = new VideoRental(); //runs constructor
Scanner input = new Scanner(System.in);
String renterName;
System.out.print("Enter renter name: ");
renterName = input.next();
System.out.print("Enter number of videos to rent: ");
numberOfRentals = input.nextInt();
rental.setRentalFee(); //needs to set rental fee to $5 according to assignment
rental.calculateBill(numberOfRentals); //from prev input
finalBill = rental.getFinalBill();
System.out.println(renterName + " your total bill for " +numberOfRentals+ " videos is $" +finalBill);
input.close();
}
}
//CHANGE ALL PROMPTS & OUTPUT TO DIALOG/MESSAGE BOX!!!!
public class VideoRental {
private int rentalFee, finalBill, numberOfRentals;
public VideoRental() { //constructor method
rentalFee = 0;
finalBill = 0;
}
public void setRentalFee() { //set method
rentalFee = 5;
} //the assignment claims this must set rentalFee = 5
public void calculateBill(int inRented) {
numberOfRentals = inRented;
finalBill = rentalFee * numberOfRentals;
}
public int getFinalBill() {
return finalBill;
}
}
Check this out:
String name = JOptionPane.showInputDialog(null, "Enter name here:");
http://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html
import javax.swing.JOptionPane;
[...]
public static void main(String[] args) {
int numberOfRentals, finalBill;
VideoRental rental = new VideoRental(); //runs constructor
String renterName;
renterName = JOptionPane.showInputDialog(null, "Enter renter name: ");
numberOfRentals = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number of videos to rent: "));
rental.setRentalFee(); //needs to set rental fee to $5 according to assignment
rental.calculateBill(numberOfRentals); //from prev input
finalBill = rental.getFinalBill();
JOptionPane.showMessageDialog(null, renterName + " your total bill for " +numberOfRentals+ " videos is $" +finalBill);
}

Java - Array outputing null

My program is supposed to output labels. All of the input works when I run it but the output is wrong and all that it outputs is null, for every part of the label except for the box number.
import javax.swing.JOptionPane;
public class MailOrderpractice {
static String nameAddressArray[] = new String[7];
public static void main(String[] args) {
// declare variables
String nameAddressArray[] = new String[7];
String numBoxesInput;
int numBoxes;
String enterAnother = "Y";
int counter;
getLabelData();
numBoxesInput = JOptionPane.showInputDialog("Enter number of boxes in the order:");
numBoxes = Integer.parseInt(numBoxesInput);
// begin outer loop logic that determines when user is finished entering mail orders
while (enterAnother.equalsIgnoreCase("Y")) {
counter = 1;
// begin the inner loop to display a label and increment the counter
while (counter <= numBoxes) {
System.out.println(nameAddressArray[0] + " " + nameAddressArray[1] + " " + nameAddressArray[2]);
System.out.println(nameAddressArray[3]);
System.out.println(nameAddressArray[4] + ", " + nameAddressArray[5] + " " + nameAddressArray[6]);
System.out.println("Box " + counter + " of " + numBoxes);
System.out.println();
counter = counter + 1;
}
enterAnother = " "; // initialize the variable to something other than "Y" before sending the prompt
enterAnother = JOptionPane.showInputDialog("Do you want to produce more labels? Y or N");
while (!enterAnother.equalsIgnoreCase("Y") && !enterAnother.equalsIgnoreCase("N")) {
enterAnother = JOptionPane.showInputDialog(null, "Invalid Response. Please enter Y or N.",
"DATA ENTRY ERROR", JOptionPane.ERROR_MESSAGE);
} // end while
if (enterAnother.equalsIgnoreCase("Y")) {
getLabelData();
numBoxesInput = JOptionPane.showInputDialog("Enter number of boxes in the order:");
numBoxes = Integer.parseInt(numBoxesInput);
} // end if
} // end while
System.exit(0);
}
public static void getLabelData() {
nameAddressArray[0] = JOptionPane.showInputDialog("Enter title (Mr., Ms., Dr., etc.): ");
nameAddressArray[1] = JOptionPane.showInputDialog("Enter first name: ");
nameAddressArray[2] = JOptionPane.showInputDialog("Enter lastname: ");
nameAddressArray[3] = JOptionPane.showInputDialog("Enter street address: ");
nameAddressArray[4] = JOptionPane.showInputDialog("Enter city: ");
nameAddressArray[5] = JOptionPane.showInputDialog("Enter state (IL, MO, etc.): ");
nameAddressArray[6] = JOptionPane.showInputDialog("Enter zip (e.g., 62025): ");
}
The array nameAddressArray is declared twice. You have a static field
static String nameAddressArray[] = new String[7];
You also have a local variable with the same name in the main method.
String nameAddressArray[] = new String[7];
Your main method is putting values into the second array, whereas your getLabelData method is using the values from the static field, and these are all the initial value (null).
One way to solve this problem is to just get rid of the local variable. Then both parts of the code will use the same array.
Alternatively, you could get rid of the static field, and pass the array as a parameter to the getLabelData method. This is probably a better solution, as mutable static fields are generally not a good idea.
you just need to comment this line into Main method(),
// String nameAddressArray[] = new String[7];

Categories