Java Phone/Item Picker - java

I'm creating a project in which users input the basic specifications of a phone and the program will compare this data to phones on the market now and return results of phones they would likely be happiest with.
I've currently only been able to get to a point in which users input this data, and as someone who's only been programming for a month, I have no clue as to how to compare this data to previously determined data, can someone help me finish this out?
import cs1.Keyboard;
public class CoolProject {
public static void main (String [] args) {
double num_Memory, num_Screen, num_ProcessorSpeed, num_ProcessorCores, num_Battery, num_Camera, num_PPI;
System.out.println("The most noticeable part of a phone is its' screen size. \nEnter the minimum screen size you'd like your phone to have: ");
num_Screen = Keyboard.readInt();
System.out.println("Fantastic! Most phones today have a 720p, 1080p, or 2K screen. \nWhat's the minimum screen resolution you'd like to have: ");
num_PPI = Keyboard.readInt();
System.out.println"(Nice! Now you're going to want to pick a battery to help power that display! What's the smallest battery you'd like to have: ");
num_Battery = Keyboard.readInt();
System.out.println("Great! So to run that powerhouse, you'll need a beast of a processor. How many cores do you want in your CPU: ");
num_ProcessorCores = Keyboard.readInt();
System.out.println("How fast do you want it to be? Keep in mind most phones run between 1 and 2.5ghz: ");
num_ProcessorSpeed = Keyboard.readInt();
System.out.println("Perfect! Last but not least, how many megapixels do you want in your phone? Remember most phones have between 4 and 21 Megapixels: ");
num_Camera = Keyboard.readInt();
}
}

You have a group of fields that you want to consider as one object. Let's call these fields "phone specifications".
So, you create a class to store these fields and their values. Let's call the class PhoneSpecification.
package com.ggl.testing;
public class PhoneSpecification {
private double num_Memory, num_Screen, num_ProcessorSpeed,
num_ProcessorCores, num_Battery, num_Camera, num_PPI;
private String name;
private String manufacturer;
public double getNum_Memory() {
return num_Memory;
}
public void setNum_Memory(double num_Memory) {
this.num_Memory = num_Memory;
}
public double getNum_Screen() {
return num_Screen;
}
public void setNum_Screen(double num_Screen) {
this.num_Screen = num_Screen;
}
public double getNum_ProcessorSpeed() {
return num_ProcessorSpeed;
}
public void setNum_ProcessorSpeed(double num_ProcessorSpeed) {
this.num_ProcessorSpeed = num_ProcessorSpeed;
}
public double getNum_ProcessorCores() {
return num_ProcessorCores;
}
public void setNum_ProcessorCores(double num_ProcessorCores) {
this.num_ProcessorCores = num_ProcessorCores;
}
public double getNum_Battery() {
return num_Battery;
}
public void setNum_Battery(double num_Battery) {
this.num_Battery = num_Battery;
}
public double getNum_Camera() {
return num_Camera;
}
public void setNum_Camera(double num_Camera) {
this.num_Camera = num_Camera;
}
public double getNum_PPI() {
return num_PPI;
}
public void setNum_PPI(double num_PPI) {
this.num_PPI = num_PPI;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
}
You would create an instance of this class for each phone you want to use in the comparison. You would create one instance of this class with the values received from the user.
Then, you compare the user phone specifications with the specifications you already created for the various phones.

Related

How to add Multiple objects using indexes in a ArrayList

I'm doing a menu-based system where it will calculate my monthly rent using specific variables (double - monthlyRent, double waterBill, double energyBill etc.)
The program starts with prompting the user to select an option:
(1) create a budget invoice (this is where a projected monthly rent invoice will be calculated)
When the user selects this option I want to use an ArrayList to store the monthly rent invoices. I have a variable where the user can put an InvoiceID to search an already existing monthly rent invoices or delete etc.
My problem is how to use specific indexes in my ArrayList to input monthly rent, water bill and so forth and the next index will be a different monthly rent, waterbill, energy bill etc.). In a general sense, store multiple variable and variable types within 1 index of the ArrayList.
My ArrayList is in its own class, different from the function that I want to create to generate monthly budget invoices. My problem is how to prompt user input for each rent variable and store all of those inputs in its proper index of the ArrayList where that specific monthly invoice will be stored. The variables are double, string and int types.
import java.util.ArrayList;
public class InvoicerHub {
static ArrayList<Object> invoicerSys = new ArrayList<Object>();
}
import java.util.ArrayList;
import java.util.Scanner;
public class BudgetInvoice extends InvoicerHub {
protected double monthlyRent ;
protected double waterBill;
protected double energyBill;
protected double carRent;
protected double internetRent;
protected String invoiceID;
public int counter = 0;
static Scanner myScan= new Scanner(System.in);
public double getMonthlyRent() {
return monthlyRent;
}
public void setMonthlyRent(double monthlyRent) {
this.monthlyRent = monthlyRent;
}
public double getWaterBill() {
return waterBill;
}
public void setWaterBill(double waterBill) {
this.waterBill = waterBill;
}
public double getEnergyBill() {
return energyBill;
}
public void setEnergyBill(double energyBill) {
this.energyBill = energyBill;
}
public double getCarRent() {
return carRent;
}
public void setCarRent(double carRent) {
this.carRent = carRent;
}
public double getInternetRent() {
return internetRent;
}
public void setInternetRent(double internetRent) {
this.internetRent = internetRent;
}
public String getInvoiceID() {
return invoiceID;
}
public void setInvoiceID(String invoiceID) {
this.invoiceID = invoiceID;
}
public static InvoicerHub getInvoice()
{
invoicerSys = new ArrayList<>();
if (invoicerSys.isEmpty()== true)
{
} // This is where I'm stuck.

Constructors and methods in java

I want to create the below class
associatename:String
workstatus:String
associate() :constructor
getassociatename():String
setassociatename(String):void
getworkstatus()String
tracksassociatestatus():int
setworkstatus(String):void
The trackAssociateStatus method takes the number of days as argument and sets the work status of the associate based on the number of days. The first 20 days they learn “C”, the next 20 days they learn “Java” In the Main class invoke the trackAssociateStatus method and find the work status and display the output.
output:The associate abc work status:Project phase
I tried this....But i got error
//associate class
public class associate{
private int associatename;
private String workstatus;
private int days;
void associate()
{
getassociatename();
setassociatename();
getworkstatus();
tracksassociatestatus();
setworkstatus();
}
public int getassociatename()
{
return associatename;
}
public void setassociatename(int associatename)
{
this.associatename=associatename;
}
public String getworkstatus()
{
return workstatus;
}
public void tracksassociatestatus(int days)
{
if(days<20)
setworkstatus("C");
else
setworkstatus("Java");
}
public void setworkstatus(String workstatus)
{
this.workstatus=workstatus;
}
}
//main class
associate a =new associate();
Scanner in=new Scanner(System.in);
int associateid=0;
String workstatus=null;
int days=0;
System.out.println("Enter the associateid:");
associateid=in.nextInt();
a.associateid=(associateid);
System.out.println("Enter the no of days:");
days=in.nextInt();
a.trackassociatestatus();
System.out.println("The id is "+a.getassocaiteid()+" work status "+a.getworkstatus());
Based on your (seemingly) UML spec, your class would look like the following:
public class Associate {
private String associateName;
private String workStatus;
public Associate() {
// This constructor is optional, a no-args constructor is added by the compiler to any class not explicitly naming a constructor.
}
public String getAssociateName() {
return associateName;
}
public void setAssociateName(String associateName) {
this.associateName = associateName;
}
public String getWorkStatus() {
return workStatus;
}
public void setWorkStatus(String workStatus) {
this.workStatus = workStatus;
}
public int tracksAssociateStatus() {
// TODO write logic here
return 1; // TODO change to whatever you need to return
}
}
You were specifying int for getAssociateName, when associateName is a String. This won't work; you need your getter return type to be the same as your field data type, or you need to convert the data to the method's return type. (The former is best practice).
Constructors don't specify a type, the class name is used and the compiler will understand what you want to do (which is return a new instance of the class). Therefore, your void associate() will tell the compiler "create a method called associate that doesn't return anything".
Well, would be nice if you provide the error itself for us.
But meanwhile, have you notice that your tracksassociatestatus method recieves an integer parameter days, and your constructor passes nothing to it?
So try changing your constructor to be something like:
Public associate() {
getassociatename();
setassociatename();
getworkstatus();
tracksassociatestatus(10);
setworkstatus();
}
For a cleaner code, check the other answer.
If you still have errors, please share them.
import java.util.*;
public class Associate
{
private String associateName;
private int workStatus;
private int days;
Scanner sc = new Scanner(System.in);
public String getAssociateName()
{
System.out.println("Enter the Associate id:");
associateName = sc.nextLine();
return associateName;
}
public void setassociatename(int associatename)
{
this.associateName=associateName;
}
public String tracksAssociatename()
{
return associateName;
}
public int getWorkStatus()
{
System.out.println("Enter the number of days");
days = sc.nextInt();
return days;
}
public void setWorkStatus(String workStatus)
{
this.workStatus=workStatus;
}
enter code here
public `enter code here`int tracksAssociateStatus()
{
return days;
}
public static void main(String args[])
{
Associate obj = new Associate();
obj.getAssociateName();
obj.getworkstatus();
System.out.println("The Associate name "+obj.tracksAssociatename()+" work Status "+obj.tracksAssociateStatus());
}
}

UML diagram confusion

Hi guys,this is my first question on StackOverflow
I am kind of new to java and I need to solve this uml diagram .
I got a solution from one of my classmates but I don't think it's correct and I did it my way. My question is which one of the solutions is correct? I know that the type of relation is an association one . Not an inheritance
Her code
class Sensor {
protected int value;
protected String location;
public Sensor() { // default constructor
value = 0;
location = "North-West";
}
public Sensor(int value, String location) { // overridden constructor
this.value = value;
this.location = location;
}
protected int getValue() { // value getter
return value;
}
protected void setValue(int v) { // value setter
this.value = v;
}
protected void displaySenzorInfo() { // display information on the sensor
System.out.println("Temperature is " + value + ", located " + location + ".");
}
}
class Controller extends Sensor {
protected String name;
public Controller(String name) { // overridden constructor
this.name = name;
}
public Controller(String name, int value, String location) { // overridden
// instructor
this.name = name;
super.value = value;
super.location = location;
}
public Controller() { // default constructor, which creates a new Sensor()
//Sensor s = new Sensor();
}
protected void checkTemperature() { // checks temperature of sensor
System.out.println("Temperature of " + name + " is " + super.value + ", located at " + super.location + ".");
}
}
public class E3 {
public static void main(String[] args) {
Controller control = new Controller();
control.displaySenzorInfo();
Controller c = new Controller("Pizza", 30, "North");
c.checkTemperature();
}
}
My code
class Sensor{
int value;
String location;
Sensor(){
value=0;
location="Sibiu";
}
Sensor(int value,String location){
this.value=value;
this.location=location;
}
int getValue(){
return value;
}
void setValue(int v){
this.value=v;
}
void displaySenzorInfo(){
System.out.println("Temperature is " + value + ", located " + location + ".");
}
}
class Controller{
Sensor tempSensor;
String name;
Controller(){
name="Sibiu";
tempSensor=30;
}
Controller (String name,Sensor tempSensor){
this.name=name;
this.tempSensor=tempSensor;
}
void checkTemperature(Sensor tempSensor){
if (tempSensor>=30)
System.out.println("the temperature is too high!");
else
System.out.println("the temp is too low" );
}
}
public class E3{
public static void main(String []args){
Sensor s1=new Sensor();
Controller c1=new Controller();
c1.displaySenzorInfo();
Controller c2=new Controller(30,"Oliver");
}
}
Please guys. If you have some suggestions or if you see any problems in m program tell me. I know that I will have some errors because I didn't work at this exercise in any IDE because I am at work and I don't have any . Thank you!!!
your solution is the correct one. As you mentioned already, it is an association and not an inheritance. You can see how an inheritance looks like on wikipedia: https://en.wikipedia.org/wiki/Class_diagram
Though overall coding (MyCode) for relationship from the given diagram is OK, I have following observations. (Her code) - Inheritance is not correct. Unidirectional association is correct.
If this is diagram is only for exercise purpose its OK, otherwise it will violate data hiding and encourage client classes to violate encapsulation (Using somebody else's data directly)
tempSensor=30;is not correct for data type.
if (tempSensor>=30) is incorrect for data type and even if you correct, it violates encapsulation (works on somebody else's data) as an effect of first violation of making instance variables non-private. classes should work on their own data.
Even if for some reason we accept above violation, checkTemperature(Sensor tempSensor) makes use of fresh instance of Sensor (for every call), which is not the one obtained from association relationship. This method should not have parameter, it should work on this.tempSensor (with accepted data leakage). Ideally this is indication that data and its behavior are getting separated and design needs to be corrected.
In case the diagram can not be changed then just remove the parameter in checkTemperature() and take care of data types as shown above.
But I would suggest change at Design level as follows for better encapsulation.
public class SensorNew {
private static final double UPPER_THRESHOLD = 25;
private static final double LOWER_THRESHOLD = 20;
private String location;
private Controller controller;
public SensorNew(String location, Controller controller) {
this.location = location;
this.controller = controller;
}
public int getCurrentTemp() {
// obtain from sensor hardware
return 10; // Just example
}
private void makePeriodicCheck(){
double currentTemp = getCurrentTemp();
if (currentTemp > UPPER_THRESHOLD){
controller.coolDown();
} else if (currentTemp < LOWER_THRESHOLD){
controller.heatUp();
} else {
controller.stopIfRunning();
}
}
public void displaySenzorInfo() { // replace by toString()
System.out.println("Temperature is " + getCurrentTemp()
+ ", located " + location + ".");
}
}
public class ControllerNew {
private String name;
// Need to maintain the state of Controller
// either by variable or State design pattern (preferred)
public ControllerNew(String name, Sensor tempSensor) {
this.name = name;
}
public void coolDown() {
// action depending upon current state of controller
}
public void heatUp() {
// action depending upon current state of controller
}
public void stopIfRunning() {
// action depending upon current state of controller
}
}
The advantage is that we do not have to provide public getXX() setXX() methods to these classes. Hence it maintains encapsulation.

Issues using String data type in my constructor, application file not running properly

So i've been messing around with String data types in the constructor of my class file, and while everything compiles correctly, when I run the application file, the program doesn't give the desired result. I kept it short to see if it would work, so my class file is as follows:
public class StringPractice
{
private String color;
private String brand;
public StringPractice() {
String color = "";
String brand = "";
}
public StringPractice(String clor, String brnd) {
setColor(clor);
setBrand(brnd);
}
public void setColor(String clor) {
if (clor.equalsIgnoreCase("Red")) {
color = clor;
}
else {
System.out.println("We dont't carry that color");
}
}
public void setBrand(String brnd) {
if (brnd.equalsIgnoreCase("Gibson")) {
brand = brnd;
}
else {
System.out.println("We do not carry that brand");
}
}
public String getColor() {
return color;
}
public String getBrand() {
return brand;
}
public void display() {
System.out.println("Our brands are: " + brand + "Our colors are: " + color);
}
My application file is as follows:
import java.util.Scanner;
public class UseStringPractice
{
public static void main(String[] args)
{
String brand = "";
String color = "";
Scanner keyboard = new Scanner(System.in);
StringPractice Guitar1;
System.out.println("Please enter the brand you would like");
brand = keyboard.next();
System.out.println("Please enter the color you would like");
color = keyboard.next();
Guitar1 = new StringPractice(brand, color);
Guitar1.display();
}
}
What am I doing incorrectly? Am I using the wrong methods to parse the information from scanner? Or am I using equalsIgnoreCase incorrectly? This is my first attempt at implementing these methods, so I may be wayyy off for all I know. When I run the application class, my result is that of the trailing else clause, or, "We do not carry those brands" or "We don't carry that color". Then, in my display statement, the variable names are replaced with "null". This is all for practice so any insight would be fantastic. Thanks!
Your arguments being passed to your constructor should be flipped.
In your application:
Guitar1 = new StringPractice(brand, color);
but in your code:
public StringPractice(String clor, String brnd) {

error checking not registering

im sure theres a simple answer to this, but when i set my balance to a negative number, i want the system to print an error, at the moment, it just prints the negative number to the console, would anyone be able to help me as to why this may be happening. Any replies appreciated.
package Assignment1;
public class Customer
{
private String name;
private String address;
private int balance;
public Customer(String nameParam, String addressParam, int balanceParam)
{
name = nameParam;
address = addressParam;
balance = balanceParam;
}
public void setName(String nameParam)
{
name = nameParam;
}
public String getName()
{
return name;
}
public void setAddress(String addressParam)
{
address = addressParam;
}
public String getAddress()
{
return address;
}
//I want the system to print an error should the balanceParam be less than 0
public void setBalance(int balanceParam)
{
if (balanceParam >= 0)
{
balance = balanceParam;
}
else
{
System.out.println("Error: Invalid balance");
}
}
public int getBalance()
{
return balance;
}
public static void main(String[] args)
{
Customer customer1 = new Customer("Tom", "High Street", 100);
Customer customer2 = new Customer("Mary", "Low Street", 110);
//The balance for customer3 is set to a negative number
Customer customer3 = new Customer("John", "Middle Street", -10);
System.out.print(customer1.getName() + "\t");
System.out.print(customer1.getAddress()+ "\t");
System.out.println(customer1.getBalance());
System.out.print(customer2.getName()+ "\t");
System.out.print(customer2.getAddress()+ "\t");
System.out.println(customer2.getBalance());
System.out.print(customer3.getName()+ "\t");
System.out.print(customer3.getAddress()+ "\t");
System.out.println(customer3.getBalance());
}
}
You never call the method setBalence which prints the error.
To have the error printed as soon as you construct the Customer object change your constructor to use the setter methods for the class fields
public Customer(String nameParam, String addressParam, int balanceParam)
{
setName(nameParam);
setAddress(addressParam);
setBalance(balanceParam);
}
Also you might want to prevent the construction of such an object or setting a negative balance into an existing object by throwing an exception:
public void setBalance(int balanceParam) {
if (balanceParam < 0) {
throw new IllegalArgumentException("Error: Invalid balance");
}
balance = balanceParam;
}
Note that the check occurs in your setBalance() method, but you never call this method. In particular, your constructor sets the balance field directly without a similar check One way to fix this (and reduce duplication at the same time) is to call setBalance() (and the other setters) from your constructor.

Categories