I'm trying to do homework for my IT classes and we just started programming a bit. We have 2 classes, Main and Okej. It is just a simple code where the getters and setters have to check if the user input the right number. But the IF statements just do not work.
package okej;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner program = new Scanner(System.in);
System.out.println("Please, type your Name.");
String name = program.nextLine();
System.out.println("Please, type your age.");
int age = program.nextInt();
System.out.println("Please, type your weight.");
double weight = program.nextDouble();
Okej you = new Okej(name, age, weight);
System.out.print(you);
}
}
package okej;
import java.util.Scanner;
public class Okej {
String name = "";
int age = 0;
double weight = 0.0;
public Okej(String name, int age, double weight) {
this.name = name;
this.age = age;
this.weight = weight;
}
public String getName() {
return name;
}
public void setName(String name) {
System.out.println("Okay, your name is " + name + ".");
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age > 18) {
if (age < 99) {
this.age = age;
System.out.println("Okay, your age is " + age + ".");
}
}
else {
System.out.println("You have put an invalid age for this program.");
System.out.println("Setting the number to 20.");
this.age = 20;
}
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
if (weight > 30) {
if (weight < 300) {
this.weight = weight;
System.out.println("Okay, your weight is " + weight + ".");
}
}
else {
System.out.println("You have put an invalid weight for this program.");
System.out.println("Setting the number to 50.");
this.weight = 50;
}
}
#Override
public String toString() {
return "Okay, your name is " + name + ", your age is " + age + ", and you weight "+ weight +".";
}
}
It is not working because logic which validates your inputs are inside setters and you are not calling it. You are creating your object through constructor which doesn't execute any validation. You can do one of following:
move validation codes to static method and call it in constructor to validate before assigning values
use builders with validation code inside
create empty object (with default constructor) and use setters to set values which will trigger your validation
...
Related
I have an abstract class called "Student" and 2 subclasses "Graduate" and "Undergraduate", they both have the same parameters.
I want to create 10 Student objects randomly, some from the "Graduate" and some from the "Undergraduate" classes.
I want to print the displayStudent() method for all objects created, I got stuck on how to randomly generate the 10 students so they are all random of type graduates and undergraduates.
public abstract class Student {
private int ID;
private double GPA;
public Student(int ID, double GPA) {
this.ID = ID;
this.GPA = GPA;
}
public int getID() {
return ID;
}
public double getGPA() {
return GPA;
}
public abstract String getLevel();
public abstract String getStatus();
public final String displayStudent() {
return getLevel() + " ID>> " + getID() + ", GPA>> " + getGPA() + ", Status>> " + getStatus();
}
}
public class Graduate extends Student{
public Graduate(int ID, double GPA) {
super(ID, GPA);
}
#Override
public String getLevel() {
return "graduate";
}
#Override
public String getStatus() {
if( getGPA() >= 3) {
return "honor";
} else if (getGPA() >= 2 && getGPA() <= 3) {
return "good";
} else {
return "probation";
}
}
}
public class Undergraduate extends Student {
public Undergraduate(int ID, double GPA) {
super(ID, GPA);
}
#Override
public String getLevel() {
return "undergraduate";
}
#Override
public String getStatus() {
if( getGPA() >= 3) {
return "honor";
} else if (getGPA() >= 2 && getGPA() <= 3) {
return "good";
} else if( getGPA() > 0 && getGPA() < 2) {
return "probation";
} else {
//for any number that is not in the range of the GPA
return "invalid GPA!";
}
}
}
Try this.
using the ternary operator ?: is key.
exp ? a : b says if exp is true, do a, else do b
I used the loop index+1 as the id.
If the boolean is true, graduate, otherwise undergrad.
The double is multiplied by 4 to get the GPA.
Random r = new Random();
List<Student> students = new ArrayList<>();
for (int i = 0; i < 10; i++) {
students.add(r.nextBoolean() ?
new Graduate(i+1, r.nextDouble() * 4) :
new Undergraduate(i+1, r.nextDouble() * 4));
}
Note, If you change the displayStudent() method to toString() like so
#Override
public String toString() {
return getLevel() + " ID>> " + getID() + ", GPA>> "
+ getGPA() + ", Status>> " + getStatus();
}
You can just print the object directly without having to call any method.
You will probably need to format the GPA to eliminate unnecessary precision. Check out String.format.
I have the following code and I want to ask the user after an name that's already stored in the Arraylist and increase that (dogs) age by +1.
Here's the most important (I guess) part of the code. This is the Register Class.
import java.util.Scanner;
import java.util.ArrayList;
public class Register {
private Scanner keyboard = new Scanner(System.in);
private ArrayList<Dog> dogs = new ArrayList<>();
private String readString() {
return keyboard.nextLine();
}
public int readInt() {
int i = keyboard.nextInt();
keyboard.nextLine();
return i;
}
public double readDouble() {
double d = keyboard.nextDouble();
keyboard.nextLine();
return d;
}
public void registrateDog(){
System.out.println("Dogs name: ");
String name = readString();
System.out.println("Dogs breed: ");
String breed = readString();
System.out.println("Dogs age: ");
int age = readInt();
System.out.println("Dogs weight: ");
double weight = readDouble();
Dog newDog = new Dog(name, breed, age, weight);
dogs.add(newDog);
System.out.println(newDog.toString() + " is added");
}
public void increaseAge(){ //Here's the problem
System.out.print("Enter dog who has aged: ");
String newDogAge = readString();
int addAge = 1;
for (int i = 0; i < dogs.size(); i++) {
if(dogs.get(i).getName().equals(newDogAge))
addAge = (dogs.get(i).getAge());
dogs.set(i, dogs.get(i));
System.out.println("Dog " + newDogAge + " is now " + addAge);
return;
}
}
private void exitProgram(){
System.out.println("Goodbye!");
keyboard.close();
}
private void run(){
setUp();
runCommandLoop();
exitProgram();
}
public static void main(String[] args){
new Register().run();
//setUp();
}
}
And
public class Dog {
private String name;
private String breed;
private int age;
private double weight;
private double tailLenght;
private String tax = "tax";
public Dog(String name, String breed, int age, double weight){
this.name = name;
this.breed = breed;
this.age = age;
this.weight = weight;
if (breed.equals(tax)) {
this.tailLenght = 3.7;
} else {
this.tailLenght = (age*weight) / 10;
}
}
public String getName(){
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBreed(){
return breed;
}
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age;
}
public int newAge(){
return age = age + 1;
}
public double getWeight(){
return weight;
}
public double getTailLenght(){
return tailLenght;
}
public String toString()
{ return String.format("%s, %s, %d years old, %.1f kg, "
+ "tail lenght %.1f cm", name, breed, age, weight, tailLenght);
}
}
So in this code you're finding the Dog by its name. Which is great.
public void increaseAge() {
System.out.print("Enter dog who has aged: ");
String newDogAge = readString();
int addAge = 1;
for (int i = 0; i < dogs.size(); i++) {
if(dogs.get(i).getName().equals(newDogAge))
addAge = (dogs.get(i).getAge());
dogs.set(i, dogs.get(i));
System.out.println("Dog " + newDogAge + " is now " + addAge);
return;
}
}
Inside of your Dog class you have a method which returns the age, what you want to do is modify it to:
public int newAge(){
this.age++; // This will take the current age of the dog and add one to it
}
Now going back to the increaseAge() method you want to modify the for loop to look like:
for (int i = 0; i < dogs.size(); i++) {
if(dogs.get(i).getName().equals(newDogAge))
dogs.get(i).newAge(); // This will update the Dogs age by 1 year
System.out.println("Dog " + dogs.get(i).getName() + " is now " + dogs.get(i).getAge());
return;
}
Where are you incrementing the age ? Call the newAge() method as you have defined in the Dog class.`
Dog dog = dogs.get(i);
dog.setAge(dog.newAge());
dogs.set(i,dog);`
We've fetched the particular dog who's details matched. Then we incremented it's age and set it back in the list at that position.
I'm having trouble doing a user-defined method in my program here, would it be nice if anyone can help me
package Ex_9_2;
public class TestStock {
public static String price;
//main
public static void main(String[] args) {
Stock stock = new Stock("ORCL", "Oracle Corporation");
System.out.println("Please enter previous closing price ");
stock.setPreviousClosingPrice(34.5);
System.out.println("Please enter current price ");
stock.setCurrentPrice(34.35);
System.out.println(stock);
// Display stock info
System.out.println("Previous Closing Price: " + stock.getPreviousClosingPrice());
System.out.println("Current Price: " + stock.getCurrentPrice());
System.out.println("Price Change: " + stock.changePercent());
}
}
Here's my other class
package Ex_9_2;
public class Stock {
private String symbol;
private String name;
private double previousClosingPrice;
private double currentPrice;
public Stock() {
}
public Stock(String symbol, String name) {
this.symbol = symbol;
this.name = name;
}
public String getSymbol() {
return this.symbol;
}
public String getName() {
return this.name;
}
public double getPreviousClosingPrice() {
return previousClosingPrice;
}
public double getCurrentPrice() {
return currentPrice;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public void setName(String name) {
this.name = name;
}
public void setPreviousClosingPrice(double price) {
this.previousClosingPrice = price;
}
public void setCurrentPrice(double price) {
this.currentPrice = price;
}
public double changePercent() {
return (currentPrice - previousClosingPrice) / previousClosingPrice;
}
#Override
public java.lang.String toString(){
return "\nYour Company's name is " + this.name
+ "\nYour Company's Symbol is " + this.symbol;
}
I can't seem to make a user-input in my main for this problem:
System.out.println("Please enter previous closing price ");
stock.setPreviousClosingPrice(34.5);
and this:
System.out.println("Please enter current price ");
stock.setCurrentPrice(34.35);
please help,
You can use java.util.Scanner class to take inputs from the user.
Declare a Scanner variable in your main function:
Scanner scan = new Scanner(System.in);
Then use scan.nexDouble() for taking input from the user. For example:
System.out.println("Please enter previous closing price ");
stock.setPreviousClosingPrice(scan.nextDouble());
import java.util.Scanner;
class IronMan {
private double totalTime = 3.7;
public IronMan() {
System.out.println("First Constructor running");
}
public IronMan() {
System.out.println("Second Constructor running");
}
}
public class Marathon {
public static void main(String[] args) throws InterruptedException {
IronMan person1 = new IronMan();
Scanner scan = new Scanner(System.in);
System.out.println(
"A triathlon is a challenging task. This program will allow you to know which is the perfect course for you.");
Thread.sleep(3000);
System.out.println("What is your age?");
int age = scan.nextInt();
Thread.sleep(1000);
System.out.println("What is your time for one mile, in minutes?(ex: 5.3 or 6.2");
double time = scan.nextDouble();
Thread.sleep(1000);
System.out.println("How much is your budget?");
double money = scan.nextDouble();
System.out.println(money);
if (money <= 100) {
System.out.println("You can't afford entrance!");
} else if (money > 100) {
if (age < 10) {
System.out.println("You don't qualify!");
} else {
if (time > 10) {
System.out.println("You do not qualify");
} else {
System.out.println("Good! you do qualify");
IronMan person2 = new IronMan();
}
}
}
}
}
I am a bit new to the concept of constructors. I was trying to create the constructor IronMan; however, Eclipse gives me an error message under the word IronMan. It says that "Duplicate method IronMan() in type IronMan". I don't understand why it says the method is duplicated, since it is supposed to be a constructor.
You have two constructors with the same signature (both without parameters). This is not allowed, since there's nothing that distinguishes between the two.
When you write IronMan person1 = new IronMan();, you have no way of specifying which of these two constructors should be invoked, so it's not allowed to have both.
Constructors allow you how to create an instance of an object. You can create ironMan IronMan ironMan = new IronMan() without set ironMan name and age, IronMan ironMan = new IronMan("Brad") this means your ironMan name is brad. IronMan ironMan = new IronMan("Brad", 29) means your ironman name is Brad and his age is 29. if you delete IronMan() constructor, you will enforce to the developer to enter ironMan name(with IronMan(String name)) or name and age (with IronMan(String name, int age)) while creating an instance of IronMan.
public class IronMan {
private String name;
private int age;
public IronMan() {
}
public IronMan(String name) {
this.name = name;
}
public IronMan(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
I'm writing code for an application that keeps track of a student’s food purchases at a campus cafeteria. There's two classes - Student, which holds overloaded constructors & appropriate getter & setter methods; and MealCard, which holds a class variable to track the number of meal cards issued, appropriate getter & setter methods, a purchaseItem() method, a purchasePoints() method & an overriddden toString() method. There's a Tester class also.
In my MealCard class, the methods are written but in the Tester when I call them, they don't work correctly. I want to get the itemValue from the user but how do I do this in the MealCard class?
Same goes for the purchasePoints method, how do I get the topUpValue from user in MealCard class?
Code so far is:
public class Student {
// Instance Variables
private String name;
private int age;
private String address;
// Default Constructor
public Student() {
this("Not Given", 0, "Not Given");
}
// Parameterized constructor that takes in values
public Student(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
// Getters and Setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress(){
return address;
}
public void setAddress(String address) {
this.address = address;
}
// toString() to be overriden
#Override
public String toString() {
return "Name: " + this.name + "\n" + "Age: " + this.age + "\n" + "Address: " + this.address;
}
}
`
public class MealCard extends Student {
static int numberOfMealCards;
private final static int DEFAULT_BALANCE = 1000;
private int itemValue;
private int topUpValue;
public int newBalance;
// Getters and Setters
public int getItemValue() {
return itemValue;
}
public void setItemValue(int itemValue) {
this.itemValue = itemValue;
}
public int getTopUpValue() {
return topUpValue;
}
public void setTopUpValue(int topUpValue) {
this.topUpValue = topUpValue;
}
// purchaseItem method for when students buy food
public int purchaseItem() {
newBalance = DEFAULT_BALANCE - itemValue;
return newBalance;
}
// purchasePoints method for students topping up their meal card balance
public int purchasePoints() {
newBalance = DEFAULT_BALANCE + topUpValue;
return newBalance;
}
// Overriden toString method
#Override
public String toString() {
return super.toString() + "Meal Card Balance: " + this.newBalance + "\n" + "Number of Meal Cards: " + numberOfMealCards;
}
}
`
import java.util.Scanner;
public class TestMealCard {
public static void main(String[] args) {
// Create instances of MealCard class
MealCard student1 = new MealCard();
MealCard student2 = new MealCard();
Scanner keyboard = new Scanner(System.in);
System.out.println("Name: ");
student1.setName(keyboard.nextLine());
System.out.println("Age: ");
student1.setAge(keyboard.nextInt());
System.out.println("Address: ");
student1.setAddress(keyboard.nextLine());
System.out.println("Meal Card Balace: ");
student1.newBalance = keyboard.nextInt();
System.out.println("Number of Meal Cards Issued: ");
student1.numberOfMealCards = keyboard.nextInt();
System.out.println("Name: ");
student2.setName(keyboard.nextLine());
System.out.println("Age: ");
student2.setAge(keyboard.nextInt());
System.out.println("Address: ");
student2.setAddress(keyboard.nextLine());
System.out.println("Meal Card Balace: ");
student2.newBalance = keyboard.nextInt();
System.out.println("Number of Meal Cards Issued: ");
student2.numberOfMealCards = keyboard.nextInt();
// Call purchaseItem
student1.purchaseItem();
// Call purchasePoints
student2.purchasePoints();
// Call tString to output information to user
}
}
In order to set the itemValue from the user you need to get get that input from the user using this setItemValue() method.
Ex.
System.out.print("Please enter the item value: ");
student1.setItemValue(keyboard.nextInt());
or
int itemVal = 0;
System.out.print("Please enter the item value: ");
itemVal = keyboard.nextInt();
student1.setItemValue(itemVal);
as for the other method call just call the setter for toUpValue.
Ex.
System.out.print("Please enter the item value: ");
student1.setTopUpValue(keyboard.nextInt());
or
int toUpVal = 0;
System.out.print("Please enter the item value: ");
itemVal = keyboard.nextInt();
student1.setTopUpValue(topUpVal);
Hope that helps =).