How to get user input and store in custom object? JAVA - java

Henlo,
Basically what im trying to do is get user inputs and store in a custom object but I have no idea on how to go about it. I have created a loadDataFromConfig() method? that works fine when creating the object SmartHome app = new SmartHome(loadDataFromConfig());.
But I am completely stumped on how to get user inputs and store them in this format: dev[0] = new SmartDevice("device 1",1.3,true);.
All the code that is meant to run should be inside the main method in Step1.java
Here are the 3 classes used for the code (ignore comments they are just notes for me):
package SmartHomeApp;
public class SmartDevice {
private String name;
private double location;
private boolean switchedOn;
public SmartDevice(String val1, double val2, boolean val3) {
setName(val1);
setLocation(val2);
setSwitchedOn(val3);
}
//YOU CANT ACCESS the 'private classes' so you need to GET them
public void setName(String value) {name = value;}
public void setLocation(double value) {location = value;}
public void setSwitchedOn(boolean value) {switchedOn = value;}
public String getName() {return name;}
public double getLocation() {return location;}
public boolean getSwitchedOn() {return switchedOn;}
}
package SmartHomeApp;
public class SmartHome
{
private SmartDevice[] smrtDev;
public SmartHome(int size) {
smrtDev = new SmartDevice[size];
}
public SmartHome(SmartDevice[] values) {
smrtDev = values;
}
public int size() {return smrtDev.length;}
// can't do toString() for some reason??
public void ToString() {
for(int i=0; i<size();i++)
{
if(smrtDev[i] != null ){
System.out.println("----------");
System.out.println("-DEVICE "+(i+1)+"-");
System.out.println("----------");
System.out.println("Name: "+smrtDev[i].getName());
System.out.println("Location: "+smrtDev[i].getLocation());
System.out.println("Switched On: "+smrtDev[i].getSwitchedOn());
}
}
}
}
package SmartHomeApp;
import java.util.*;
public class Step1 {
public static void main(String args[]) {
SmartHome app = new SmartHome(loadDataFromConfig());
app.ToString();
}
public static SmartDevice[] loadDataFromConfig()
{
SmartDevice[] dev = new SmartDevice[20];
dev[0] = new SmartDevice("device 1",1.3,true);
dev[1] = new SmartDevice("device 2",2.3,false);
dev[2] = new SmartDevice("device 3",3.3,true);
dev[4] = new SmartDevice("device 5",4.3,false);
dev[19] = new SmartDevice("device 20",5.3,false);
return dev;
}
}

Some of the improvements required in your code are as follows:
Follow Java naming conventions e.g. ToString() should be toString(). Check this to learn more about toString(). Most of the IDEs (e.g. eclipse) provide a feature to generate toString() method on click of a button. Whatever way (either manual or with the help of your IDE) you generate it, it must return a String.
You should do away with using next(), nextInt(), nextDouble() etc. and use nextLine() instead. Check this to learn more it. To give you an idea what problems next(), nextDouble() can cause, try entering a name with a space e.g.
Enter size:
2
Name:
Light Amplification by Stimulated Emission of Radiation
Location:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at Main.main(Main.java:83)
Given below is a sample code incorporating the improvements mentioned above:
import java.util.Scanner;
class SmartDevice {
private String name;
private double location;
private boolean switchedOn;
public SmartDevice(String val1, double val2, boolean val3) {
setName(val1);
setLocation(val2);
setSwitchedOn(val3);
}
// YOU CANT ACCESS the 'private classes' so you need to GET them
public void setName(String value) {
name = value;
}
public void setLocation(double value) {
location = value;
}
public void setSwitchedOn(boolean value) {
switchedOn = value;
}
public String getName() {
return name;
}
public double getLocation() {
return location;
}
public boolean getSwitchedOn() {
return switchedOn;
}
#Override
public String toString() {
return "SmartDevice [name=" + name + ", location=" + location + ", switchedOn=" + switchedOn + "]";
}
}
class SmartHome {
private SmartDevice[] smrtDev;
public SmartHome(int size) {
smrtDev = new SmartDevice[size];
}
public SmartHome(SmartDevice[] values) {
smrtDev = values;
}
public int size() {
return smrtDev.length;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (SmartDevice smartDevice : smrtDev) {
sb.append(smartDevice.toString()).append("\n");
}
return sb.toString();
}
}
public class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
int size = getPositiveInt(myObj, "Enter size: ");
SmartDevice[] newList = new SmartDevice[size];
for (int i = 0; i < newList.length; i++) {
System.out.print("Name: ");
String x = myObj.nextLine();
double y = getFloatingPointNumber(myObj, "Location: ");
boolean z = getBoolean(myObj, "Is on?: ");
newList[i] = new SmartDevice(x, y, z);
}
SmartHome newDevice = new SmartHome(newList);
System.out.println(newDevice);
}
static int getPositiveInt(Scanner in, String message) {
boolean valid;
int n = 0;
do {
valid = true;
System.out.print(message);
try {
n = Integer.parseInt(in.nextLine());
if (n <= 0) {
throw new IllegalArgumentException();
}
} catch (IllegalArgumentException e) {
System.out.println("This in not a positive integer. Please try again.");
valid = false;
}
} while (!valid);
return n;
}
static double getFloatingPointNumber(Scanner in, String message) {
boolean valid;
double n = 0;
do {
valid = true;
System.out.print(message);
try {
n = Double.parseDouble(in.nextLine());
} catch (NumberFormatException | NullPointerException e) {
System.out.println("This in not a number. Please try again.");
valid = false;
}
} while (!valid);
return n;
}
static boolean getBoolean(Scanner in, String message) {
System.out.print(message);
return Boolean.parseBoolean(in.nextLine());
}
}
A sample run:
Enter size: x
This in not a positive integer. Please try again.
Enter size: -2
This in not a positive integer. Please try again.
Enter size: 10.5
This in not a positive integer. Please try again.
Enter size: 2
Name: Light Amplification by Stimulated Emission of Radiation
Location: 123.456
Is on?: true
Name: Vacuum Diode
Location: 234.567
Is on?: no
SmartDevice [name=Light Amplification by Stimulated Emission of Radiation, location=123.456, switchedOn=true]
SmartDevice [name=Vacuum Diode, location=234.567, switchedOn=false]

So as suggested I tried to do the following:
public static void main(String args[]) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter size: ");
int size = myObj.nextInt();
SmartDevice[] newList = new SmartDevice[size];
for(int i =0; i<newList.length;i++) {
System.out.println("Name: ");
String x = myObj.next();
System.out.println("Location: ");
double y = myObj.nextDouble();
System.out.println("Is on?: ");
boolean z = myObj.nextBoolean();
newList[i] = new SmartDevice(x,y,z);
}
SmartHome newDevice = new SmartHome(newList);
newDevice.ToString();
}
Got it working but not sure if this is the most efficient way to do so??

Related

How to insert value from user defined datatypes to object in java?

I'm creating an object of type Lightmode, which is a class.
There's also a Smartlamp class which is having a variable of custom data of type Lighmodes and I want to show my defined data type value over there.
I'm trying to create an object and then insert a string against my Lightmode data type which is showing error. I want to print like this:
Name:  lamp1 
Location: 3.1 
Switched On:  false 
Mode:  STANDARD 
Here mode is lightmode datatype and I'm getting a problem over it.
...
public class LightModes
{
String NIGHT_MODE;
String SOFT_MODE;
String STANDARD_MODE;
public String getNIGHT_MODE() {
return NIGHT_MODE;
}
public void setNIGHT_MODE(String NIGHT_MODE) {
this.NIGHT_MODE = NIGHT_MODE;
}
public String getSOFT_MODE() {
return SOFT_MODE;
}
public void setSOFT_MODE(String SOFT_MODE) {
this.SOFT_MODE = SOFT_MODE;
}
public String getSTANDARD_MODE() {
return STANDARD_MODE;
}
public void setSTANDARD_MODE(String STANDARD_MODE) {
this.STANDARD_MODE = STANDARD_MODE;
}
public LightModes() {
this.NIGHT_MODE = "NIGHT";
this.STANDARD_MODE = "STANDARD";
this.SOFT_MODE = "SOFT";
}
}...
...package smart.home.app;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Step5 {
public static void main(String[] args) throws IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int size,mode;
int displayindex=1;
String name;
double location,temperature;
boolean status=false;
System.out.println("Enter number of size of Fridge you want to add.");
Scanner in = new Scanner(System.in);
size=in.nextInt();
// TODO code application logic here
SmartLamp[] smartLamp=new SmartLamp[size];// creating an array object of smartdevice class
//
for(int j=0;j<size;j++)
{
System.out.println("Enter Lamp name.");
name=input.readLine();
System.out.println("Enter Lamp Location.\\hint(1.1)");
Scanner devicelocation=new Scanner(System.in);
location=devicelocation.nextDouble();
System.out.println("Enter Lamp Mode.(1 for Night 2 for Soft 3 for Standard)");
Scanner lampmode=new Scanner(System.in);
mode=lampmode.nextInt();
System.out.println("Enter Lamp status.1 for ON, 0 for OFF.");
Scanner devicestatus=new Scanner(System.in);
int currentstatus=devicestatus.nextInt();
if(currentstatus==1)
{
status=true;
}
else if(currentstatus==0)
{
status=false;
}
LightModes light = null;
smartLamp[j]=new SmartLamp(light.NIGHT_MODE, name, location, status);
}
//////////////Display Data////////////////////////////
for(int i=0;i<size;i++)
{
System.out.println("-Smart lamp "+displayindex+" -");
System.out.println(smartLamp[i].toString());
System.out.println("---------------------------------------------");
displayindex++;
}
}
}...
...public class SmartLamp extends SmartDevice{
private LightModes lightModes;
public LightModes getLightModes() {
return lightModes;
}
public void setLightModes(LightModes lightModes) {
this.lightModes = lightModes;
}
public SmartLamp(String name, double location, boolean switchedOn) {
super(name, location, switchedOn);
}
public SmartLamp(LightModes lightModes, String name, double location, boolean switchedOn) {
super(name, location, switchedOn);
this.lightModes = lightModes;
}
#Override
public String toString() {
return "SmartLamp{"+"\nName."+getName()+"\nLocation."
+getLocation() + "\nSwitchedOn."+isSwitchedOn()+
"\nMode=" + getLightModes() + '}';
}
}...
I downloaded your code and added the missing class SmartDevice. Your code contains two compiler errors.
name = input.readLine();
This line throws java.io.IOException which is an unchecked exception and hence must be handled by your code. There are several ways to do this, one of which is to add throws IOException to method main() in class Step5.
smartLamp[j]=new SmartLamp(light.NIGHT_MODE, name, location, status);
The first argument to SmartLamp constructor is an instance of class LightModes but you are passing a String. You need to create an instance of LightModes.
Here is your code with my modifications that get rid of the two compiler errors.
(Note: The below code includes my guessed implementation of class SmartDevice.)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Step5 {
public static void main(String[] args) throws IOException { // Change here.
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int size, mode;
int displayindex = 1;
String name;
double location, temperature;
boolean status = false;
System.out.println("Enter number of size of Fridge you want to add.");
Scanner in = new Scanner(System.in);
size = in.nextInt();
SmartLamp[] smartLamp = new SmartLamp[size];// creating an array object of smartdevice class
for (int j = 0; j < size; j++) {
System.out.println("Enter Lamp name.");
name = input.readLine(); // throws java.io.IOException
System.out.println("Enter Lamp Location.\\hint(1.1)");
Scanner devicelocation = new Scanner(System.in);
location = devicelocation.nextDouble();
System.out.println("Enter Lamp Mode.(1 for Night 2 for Soft 3 for Standard)");
Scanner lampmode = new Scanner(System.in);
mode = lampmode.nextInt();
System.out.println("Enter Lamp status.1 for ON, 0 for OFF.");
Scanner devicestatus = new Scanner(System.in);
int currentstatus = devicestatus.nextInt();
if (currentstatus == 1) {
status = true;
}
else if (currentstatus == 0) {
status = false;
}
LightModes light = new LightModes(); // Change here.
light.setNIGHT_MODE(light.getNIGHT_MODE()); // Change here.
smartLamp[j] = new SmartLamp(light, name, location, status); // Change here.
}
//////////////Display Data////////////////////////////
for(int i=0;i<size;i++)
{
System.out.println("-Smart lamp "+displayindex+" -");
System.out.println(smartLamp[i].toString());
System.out.println("---------------------------------------------");
displayindex++;
}
}
}
class LightModes {
String NIGHT_MODE;
String SOFT_MODE;
String STANDARD_MODE;
public String getNIGHT_MODE() {
return NIGHT_MODE;
}
public void setNIGHT_MODE(String NIGHT_MODE) {
this.NIGHT_MODE = NIGHT_MODE;
}
public String getSOFT_MODE() {
return SOFT_MODE;
}
public void setSOFT_MODE(String SOFT_MODE) {
this.SOFT_MODE = SOFT_MODE;
}
public String getSTANDARD_MODE() {
return STANDARD_MODE;
}
public void setSTANDARD_MODE(String STANDARD_MODE) {
this.STANDARD_MODE = STANDARD_MODE;
}
public LightModes() {
this.NIGHT_MODE = "NIGHT";
this.STANDARD_MODE = "STANDARD";
this.SOFT_MODE = "SOFT";
}
}
class SmartDevice {
private String name;
private double location;
private boolean switchedOn;
public SmartDevice(String name, double location, boolean switchedOn) {
this.name = name;
this.location = location;
this.switchedOn = switchedOn;
}
public String getName() {
return name;
}
public double getLocation() {
return location;
}
public boolean isSwitchedOn() {
return switchedOn;
}
}
class SmartLamp extends SmartDevice {
private LightModes lightModes;
public LightModes getLightModes() {
return lightModes;
}
public void setLightModes(LightModes lightModes) {
this.lightModes = lightModes;
}
public SmartLamp(String name, double location, boolean switchedOn) {
super(name, location, switchedOn);
}
public SmartLamp(LightModes lightModes, String name, double location, boolean switchedOn) {
super(name, location, switchedOn);
this.lightModes = lightModes;
}
#Override
public String toString() {
return "SmartLamp{" + "\nName." + getName() + "\nLocation." + getLocation()
+ "\nSwitchedOn." + isSwitchedOn() + "\nMode=" + getLightModes() + '}';
}
}

Java testing out a driver class

I've been having some issues with this program. I have to test out using a driver class each method, but I can't seem to understand what I should do when the parameters are strings.
I had an example for int parameters but the example never showed anything on string parameters and how to convert. Using null makes my driver class run but putting an int or string won't.
What can I do to convert this correctly, so it can display whatever I have in the no parameter constructor?
public class StudentListing
{
private String name;
private String number;
public StudentListing(String n, String num)
{
name = n;
number = num;
}
public StudentListing()
{
name = null;
number = null;
}
public String toString()
{
return("Name is " + name +
"\nNumber is " + number + "\n");
}
public void show()
{
System.out.println(toString());
}
public StudentListing Clone()
{
StudentListing clone = new StudentListing (name, number);
return clone;
}
public int compareTo(String targetKey)
{
return (name.compareTo(targetKey));
}
public void input()
{
name = JOptionPane.showInputDialog("Enter a name");
number = JOptionPane.showInputDialog("Enter a number");
}// end of StudentListing
}//end of class
public class StudentListingDriver
{
public static void main(String[] args)
{
StudentListing s1 = new StudentListing();
StudentListing s2 = new StudentListing(null,null);
System.out.println(s1);
s1.input();
StudentListing s3 = s2.clone();
s1.show();
}
}
You can have default values and make the no-args constructor call the other constructor.
Use Integer.parseInt(); to convert from a String to an Integer.
You also need to check the conversion for exceptions.
Like this:
public class StudentListing {
private String name;
private int number;
public StudentListing(String n, int num) {
name = n;
number = num;
}
public StudentListing() {
this("defaultName", 0);
}
public String toString() {
return ("Name is " + name + "\nNumber is " + number + "\n");
}
public void show() {
System.out.println(toString());
}
public StudentListing Clone() {
StudentListing clone = new StudentListing(name, number);
return clone;
}
public int compareTo(String targetKey) {
return (name.compareTo(targetKey));
}
public void input() {
name = JOptionPane.showInputDialog("Enter a name");
number = Integer
.parseInt(JOptionPane.showInputDialog("Enter a number"));
}
}
The tester:
public class StudentListingDriver {
public static void main(String[] args) {
StudentListing s1 = new StudentListing();
StudentListing s2 = new StudentListing(null, 0);
System.out.println(s1);
s1.input();
StudentListing s3 = s2.Clone();
s1.show();
}
}

Printing a separate String from the same Object

I asked this question but the way I worded it was considered a duplicate which was not similar. I am trying to print a separate String for my printAllFlights method which prints all of the user entered information. My other methods print just fine. Here is the output I am trying to achieve.
Choose action:
[1] Print planes
[2] Print flights
[3] Print plane info
[x] Quit
> 2
HA-LOL (42 ppl) (HEL-BAL)
HA-LOL (42 ppl) (BAL-HEL)
How my code is now I get the output null(0) (HEL-BAL). How can i change it to reflect the correct output. Any help would be appreciated.
public class Airport {
private String planeId;
private int capacity;
private String dest;
private String dep;
public Airport(String planeId,int capacity){
this.planeId= planeId;
this.capacity = capacity;
}
public Airport(String planeId, String dep, String dest){
this.dest= dest;
this.dep= dep;
}
public String getPlaneId(){
return this.planeId;
}
public void setPlaneId(String planeId){
this.planeId = planeId;
}
public int getCapacity(){
return this.capacity;
}
public void setCapacity(int capacity){
this.capacity = capacity;
}
public String getDestination(){
return this.dest;
}
public void setDestination(String dest){
this.dest = dest;
}
public String getDeparture(){
return this.dep;
}
public void setDeparture(String dep){
this.dep = dep;
}
public String toString(){
return planeId + " (" + capacity + ")";
}
public String secString(){
return planeId + " (" + capacity + ")" + "(" + dest + "-" + dep;
}
}
import java.util.ArrayList;
public class FlightServices {
private ArrayList<Airport> airport;
public FlightServices() {
airport = new ArrayList<Airport>();
}
public void add(String planeId, int capacity) {
airport.add(new Airport(planeId, capacity));
}
public void addFlight(String planeId, String dest, String dep) {
airport.add(new Airport(planeId, dest, dep));
}
public void printAllPlanes() {
for (Airport all : airport) {
System.out.println(all);
}
}
public void printAllFlights() {
for (Airport all : airport) {
System.out.println(all.secString());
}
}
public void printPlanesInfo(String planeId) {
for (Airport info : airport) {
if (planeId.equals(info.getPlaneId())) {
System.out.println(info);
}
}
}
}
import java.util.Scanner;
public class UserInput {
private Scanner reader;
private FlightServices air;
public UserInput(Scanner reader, FlightServices air) {
this.reader = reader;
this.air = air;
}
public void start() {
while (true) {
System.out.println("Choose operation: ");
System.out.println("[1] Add airplane");
System.out.println("[2] Add flight");
System.out.println("[3] Exit");
int input = Integer.parseInt(reader.nextLine());
if (input == 3) {
break;
} else if (input == 1) {
this.addPlane();
} else if (input == 2) {
this.addFlight();
}
}
}
public void addPlane() {
System.out.println("Give plane ID: ");
String id = reader.nextLine();
System.out.println("Give plane capacity: ");
int capacity = Integer.parseInt(reader.nextLine());
this.air.add(id, capacity);
}
public void addFlight() {
System.out.println("Give plane ID: ");
String id = reader.nextLine();
System.out.println("Give departure airport code: ");
String dep = reader.nextLine();
System.out.println("Give destination airport code: ");
String des = reader.nextLine();
this.air.addFlight(id,dep,des);
}
public void printing() {
while (true) {
System.out.println("Choose operation: ");
System.out.println("[1] Print planes");
System.out.println("[2] Print flights");
System.out.println("[3] Print plane info");
System.out.println("[4] Quit");
int command = Integer.parseInt(reader.nextLine());
if (command == 4) {
break;
} else if (command == 1) {
this.air.printAllPlanes();
} else if (command == 2) {
this.air.printAllFlights();
} else if (command == 3) {
this.addPlaneInfo();
}
}
}
public void addPlaneInfo() {
System.out.println("Give plane ID: ");
String id = reader.nextLine();
this.air.printPlanesInfo(id);
}
}
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
FlightServices air = new FlightServices();
UserInput ui = new UserInput(reader,air);
ui.start();
System.out.println("Flight Service");
System.out.println("----------");
ui.printing();
}
}
Ok.
public void add(String planeId, int capacity) {
airport.add(new Airport(planeId, capacity));
}
public void addFlight(String planeId, String dest, String dep) {
airport.add(new Airport(planeId, dest, dep));
}
You're adding some Airportobjects to your airport using addFlight() and others using add(). The ones you add using addFlight() have no capacity values and the ones using add() have no dest or dep. Do you see? Simply making two entries with the same planeId will not combine them in your arraylist. When you try to print, some values will be null depending on how you had added the Airport objects.
EDIT:
One solution i can think of, while changing your code as less as possible-
public void add(String planeId, int capacity) {
int flag=0;
for(Airport air:airport) {
if(air.planeID.equals(planeID)) {
air.capacity=capacity;
flag=1;
}
}
if(flag==0)
airport.add(new Airport(planeId, capacity));
}
And similarly edit your add() function. This way, you can have all relevant fields filled in a single entry.
Of course, a much better idea would be to restructure your classes entirely, but this should work.

Java cannot find symbol error - a method from another class

I'm trying to access the method changeAll from class MarkMaker the following way:
import java.util.Scanner;
class Question10e
{
public static void main(String[] args)
{
System.out.println();
Scanner input = new Scanner(System.in);
System.out.print("Enter mark 1: ");
int newm1=input.nextInt();
System.out.print("Enter mark 2: ");
int newm2=input.nextInt();
System.out.print("Enter mark 3: ");
int newm3=input.nextInt();
String linem=input.nextLine();
System.out.print("Enter a master password: ");
String masterpass = input.next();
linem=input.nextLine();
MarkMaker mm = new MarkMaker(masterpass);
Mark masterMark1 = mm.makeMark(newm1);
Mark masterMark2 = mm.makeMark(newm2);
Mark masterMark3 = mm.makeMark(newm3);
try{
System.out.println("The new mark 1 is "+masterMark1.provisional(masterpass));
System.out.println("The new mark 2 is "+masterMark2.provisional(masterpass));
System.out.println("The new mark 3 is "+masterMark3.provisional(masterpass));
System.out.println("The new master password is is "+masterMark1.returnPass());
int avg = mm.average();
System.out.println("The average is "+avg);
changeAll(5.5, 3);
}
catch(IncorrectPasswordException e){}
}
}
This is the MarkMaker class:
import java.util.*;
class MarkMaker{
private String masterPass = "";
private ArrayList<Mark> masterArr = new ArrayList<Mark>();
public MarkMaker(String masterPass)
{
this.masterPass = masterPass;
}
public Mark makeMark(int m)
{
Mark newMarkObj = new Mark(m,masterPass);
masterArr.add(newMarkObj);
return newMarkObj;
}
public ArrayList<Mark> returnMasterArr()
{
return masterArr;
}
public int average() throws IncorrectPasswordException
{
int n = 0;
for(int i=0; i<masterArr.size(); i++)
{
n = n + masterArr.get(i).provisional(masterPass);
}
int avg = n/masterArr.size();
return avg;
}
public void changeAll(double d, int x) throws IncorrectPasswordException
{
for(int i=0; i<masterArr.size(); i++)
{
double currentMark = masterArr.get(i).provisional(masterPass);
System.out.println("Current mark is: "+currentMark);
currentMark = currentMark*d;
System.out.println("Current mark is: "+currentMark);
currentMark = Math.ceil(currentMark);
System.out.println("Current mark is: "+currentMark);
}
} }
And this is the Mark class:
class Mark
{
private int value;
private String password;
boolean released;
public Mark(int value, String password)
{
this.value = value;
this.password = password;
released = false;
}
public void release(String p) throws IncorrectPasswordException
{
if(p.equals(password))
{
if(released==false)
released = true;
}
else throw new IncorrectPasswordException(p);
}
public int value() throws UnReleasedException
{
if(released==true)
return value;
else
throw new UnReleasedException();
}
public int provisional(String p) throws IncorrectPasswordException
{
if(p.equals(password))
return value;
else
throw new IncorrectPasswordException(p);
}
public void change(String p, int arg) throws IncorrectPasswordException
{
if(p.equals(password))
value = arg;
else
throw new IncorrectPasswordException(p);
}
public String returnPass()
{
return password;
}
public boolean isReleased()
{
return released;
}
public boolean equals(Mark m2) throws UnReleasedException
{
if(this.isReleased() && m2.isReleased())
{ //it throws an error, that's why i'm using the Unreleased Exception
if(this.value()==m2.value())
return true;
}
throw new UnReleasedException();
} }
The problem is that I always get a "cannot find symbol error - method changeAll(double, int), location class Question10e"
Question10e doesn't have this method. Perhaps you intended to call this on an instance of a class which does like.
mm.changeAll(5.5, 3);
changeAll is a method which belongs to the MarkMaker class rather than the current Question10e class where you are attempting to call the method:
mm.changeAll(5.5, 3);
You need to call changeAll() through a MarkMarker object. It doesn't exist in your Question10e class. So, you could do this by:
mm.changeAll(5.5, 3)
Just because changeAll() is public doesn't mean that you can call it from anywhere. It simply means that a MarkMarker object can call it from anywhere.
You need
mm.changeAll(5.5, 3);

I need help in trying to re-input a value whenever the user inputs a negative number

import java.util.*;
public class Inheritance {
public static Scanner objScan = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter name:");
String strName = objScan.nextLine();
double dSalary;
int iYears;
String strTIN;
String strLoopControl = "1";
try {
System.out.println("Enter salary:");
dSalary = dGetSalary();
System.out.println("Enter years worked:");
iYears = iGetYears();
System.out.println("Enter ID number:");
strTIN = strGetID();
Employee1 objEmp = new Employee1(strName, dSalary, iYears, strTIN);
objEmp.print();
}
catch (Exception e) {
if (e instanceof NegativeInputException) {
strLoopControl = "0";
System.out.println(e.getMessage());
//strLoopControl = "0";
}
else if (e instanceof ZeroIdentificationException) {
System.out.println(e.getMessage());
}
}
}
public static double dGetSalary () throws NegativeInputException {
double dSalary;
do {
try {
dSalary = objScan.nextDouble();
if (dSalary < 0) {
throw new NegativeInputException();
}
return dSalary;
}
catch (NegativeInputException nie) {
throw nie;
}
} while (dSalary<0);
}
public static int iGetYears() throws NegativeInputException {
int iYears;
try {
iYears = objScan.nextInt();
if (iYears < 0) {
throw new NegativeInputException();
}
return iYears;
}
catch (NegativeInputException nie) {
throw nie;
}
}
public static String strGetID() throws ZeroIdentificationException {
String strTIN;
try {
strTIN = objScan.next();
if (strTIN.equals("0000000")) {
throw new ZeroIdentificationException();
}
return strTIN;
}
catch (ZeroIdentificationException zie) {
throw zie;
}
}
}
class NegativeInputException extends Exception {
public NegativeInputException() {
super("You have inputted a negative number.");
}
public NegativeInputException (String strMessage) {
super(strMessage);
}
}
class ZeroIdentificationException extends Exception {
public ZeroIdentificationException() {
super("You inputted an invalid ID number. \n Please input again.");
}
public ZeroIdentificationException(String strMessage) {
super(strMessage);
}
}
class Person1 {
private String strName;
public Person1() {
strName = "";
}
public Person1(String strName) {
this.strName = strName;
}
public void setName(String strName) {
this.strName = strName;
}
public String getName() {
return strName;
}
public void print() {
System.out.println("Name: " +strName);
}
}
class Employee1 extends Person1 {
private String strName;
private double dSalary;
private int iYears;
private String strTIN;
public Employee1 (String strName, double dSalary, int iYears, String strTIN) {
this.strName = strName;
this.dSalary = dSalary;
this.iYears = iYears;
this.strTIN = strTIN;
}
public void print() {
System.out.println();
System.out.print("Name: " +this.strName);
System.out.println();
System.out.print("Salary:" +this.dSalary);
System.out.println();
System.out.print("Years WorkedS:" +this.iYears);
System.out.println();
System.out.print("ID Number:" +this.strTIN);
}
}
This is a program that asks for an employee's records. It asks for the name, salary, years worked and ID number. It catches an Exception whenever the user inputs a negative value and catches an exception whenever "0000000" is inputted in the strTIN variable. This program works flawlessly however I need to re-input whenever a negative value and "0000000" is inputted. I've tried using do-while statements but no luck. Can anyone help me? I'm having an idea of using "flag" for controlling the loop but I do not know where to put it in my code. I'm pretty sure there's a way to re-input, I just can't figure it out.
Your methods are broken - they're trying to loop while the value is negative, but they'll throw an exception if it's negative... so they'll only ever go through the loop once, either returning a value or throwing an exception.
You want something like this:
public static double getNonNegativeDouble(Scanner scanner) {
while (true) {
double value = scanner.nextDouble();
if (value >= 0) {
return value;
}
}
}
You should probably repeat the prompt and give an error message on invalid input though...
Also note that:
Catching an exception only to throw it again like this is horrible:
// Ick: just don't catch! (May mean you don't need "try" block at all.)
catch (NegativeInputException nie) {
throw nie;
}
Your "pseudo-Hungarian" method names go against Java naming conventions
Catching Exception and then using instanceof to check for different types is horrible; just catch the types you're interested in.
Instead of throwing a NegativeInputException you could wrap your nextInt code in a while loop that only returns for a positive value...
In addition, maybe it's a good idea to wrap input functionality in methods like
int readInteger(int minValue, int maxValue) {
if (minValue >= maxValue)
throw new IllegalArgumentException("...")
while(true) {
System.out.println("Please enter an integer ("+minValue+"-"+maxValue+")");
int val = objScan.nextInt();
if (val >= minValue && val <= maxValue) return val;
}
}
double readDouble(...

Categories

Resources