I am working on a report file to call multiple methods to function on an external Reporting file. Below is my report.java file and the getter elements do not seem to be working. These elements are generateReport and isServerActive. This is what I am trying to figure out as all of my other methods when called work properly, but these two still seem to be getting hung up.
class Report {
//Variables to be used within my methods/functions below
private static String serverName;
private static String userName;
private static String password;
private String reportName;
private int numParameters;
private int reportParameter;
private String reportParameterString;
private static String outputType;
private static String systemName;
private static String genReport;
private static boolean active;
// Constructor
Report(String name){
reportName = name;
}
//setServerName method, assigned variable serverName the value passed into "name"
public static void setServerName(String name){
serverName = name;
}
//setUserName method, assigned variable userName the value passed into "user"
public static void setUserName(String user){
userName = user;
}
//setPassword method, assigned variable password the value passed into "pw"
public static void setPassword(String pw){
password = pw;
}
//setNumParameters method, assigned variable numParameters the value
passed into int "numParm"
public void setNumParameters (int numParm){
numParameters = numParm;
}
//setParameter method, assigned variable reportParameter the value
passed into int "reportParam"
//Assigned variable reportParameterString the value passed into
"param"
public void setParameter (int reportParam, String param){
reportParameter = reportParam;
reportParameterString = param;
}
//setOutputType method, assigned variable outputType the value passed
into "output"
public void setOutputType (String output){
outputType = output;
}
//setReportSystemName method, assigned variable systemName the value
passed into "reportSystemName"
public void setReportSystemName (String reportSystemName){
systemName = reportSystemName;
}
public void generateReport(String reportGen){
genReport = reportGen;
}
public void isServerActive(boolean isActive){
active = isActive;
}
}
Here is the file in which I am calling all of the above methods
public class ReportClassPrinter {
public static void main(String[] args) {
//Set the server name
Report.setServerName("\\\\fancyServer");
Report.setUserName("NHAUser");
Report.setPassword("NHAPassword");
//Create the two reports
Report report1 = new Report("Report #1");
Report report2 = new Report("Report #2");
//Set the numbe of parameters for each report
report1.setNumParameters(2);
report2.setNumParameters(4);
//Add the needed parameters, Report should make sure I am not trying to break it
report1.setParameter(0, "01/01/1970");
report1.setParameter(1, "01/01/2018");
report1.setParameter(2, "pjdt");
report2.setParameter(0, "08/01/2017");
report2.setParameter(1, "08/01/2018");
report2.setParameter(2, "notpjdt");
report2.setParameter(3, "THIS IS A PARAMETER");
report2.setParameter(4, "THIS WON'T BE ADDED");
//Set the output type
report1.setOutputType("pdf");
report2.setOutputType("xls");
//Set the report system name:
report1.setReportSystemName("reportNumberOne.rdl");
report2.setReportSystemName("reportNumberTwo.rdl");
//Display the Report information
System.out.println(report1.generateReport());
System.out.println("Server up is: " + Report.isServerActive());
System.out.println(report2.generateReport());
System.out.println("Server up is: " + Report.isServerActive());
//Change the server - notice how chaning this once, affects ALL reports
System.out.println("\nUpdating Server information\n");
Report.setServerName("\\\\SercureServerName");
Report.setUserName("SecureNHAUser");
//Again display the Report information
System.out.println(report1.generateReport());
System.out.println("Server up is: " + Report.isServerActive());
System.out.println(report2.generateReport());
System.out.println("Server up is: " + Report.isServerActive());
}
}
You need
return statement at the last line of your getters
change return type of the function
delete parameter from the function signature since you don't call the functions with argument
add static to the return type
to work as you intended on Main function. What you did in your getters are just allocated value to the variable.
class Report {
[...]
public static String generateReport(){
return genReport;
}
public static boolean isServerActive(){
return active;
}
}
Related
I noticed a scenario today. When we pass a parameter on private methods, the entity will return the revised values but not primitives.
Here is my sample code,
/**
* #author gowthami
*
*/
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
String s = "gowth";
System.out.println("before " + s);
concateMe(s, "ami");
System.out.println("after " + s);
BeanTest bt = new BeanTest();
bt.setId("1");
System.out.println("before");
System.out.println(bt.getId());
System.out.println(bt.getName());
setBeanTestName(bt, "gowthami");
System.out.println("after");
System.out.println(bt.getId());
System.out.println(bt.getName());
String st = new String("gowth");
System.out.println("before " + st);
concateMe(st, "ami");
System.out.println("after " + st);
}
private static void setBeanTestName(BeanTest bt, String string) {
bt.setName(string);
}
private static void concateMe(String s, String string) {
s = s+string;
System.out.println("inside method " + s);
}
}
BeanTest.java
public class BeanTest {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
So the bean is getting updated even though we are not returning it from private method but a string is not. Can someone explain me whats happening on JVM level?
This is because Java follows Call by value, not Call by reference.
When you are passing s you are actually passing value of s, not the actual s. So though you are changing s in concateMe(), it will not change in your main method.
When you are passing bt, then the change is affecting as you are changing the field variable of that reference. But if you change the reference, then there will be no effect. You can add this in main method:
System.out.println("before......");
System.out.println(bt.getId());
System.out.println(bt.getName());
changeBeanTest(bt);
System.out.println("after");
System.out.println(bt.getId());
System.out.println(bt.getName());
Suppose your changeBeanTest is like this:
private static void changeBeanTest(BeanTest tempBeanTest) {
BeanTest bt = new BeanTest();
bt.setId("2");
bt.setName("Trump");
tempBeanTest = bt;
}
run this. There will be no change to bt sent from main().
The Bean is a full object in java passed by reference to the private method so it is the same instance in the main method and the private method.
You are modifying the values of that instance so the changes show up in both places.
The string is more or less a primitive and passed as a copy of the value instead of the exact instance from main. It is a new instance in the private method and so you are modifying a new variable. The changes don't show up in the main method as it is a different entity.
String s = "gowth"; in this line s is pointing to "gowth" from String Pool.When you are calling
private static void concateMe(String s, String string) here String s is different from caller method String s.Here String s scope is local to method ContactMe,But contactMe local String s pointing same "gowth" which is pointed by Caller class String s.After s = s + string;since String is immutable the method local reference String s pointing a different String "gowthami",but caller method String s is still pointing to "gowth".So you are getting this output.
But in case of Bean both the object pointing same String reference,Once we made any change in reference it would be reflected for both object.
I wrote some classes in Java but when I run the program I receive the error "ArrayIndexOutOfBoundsException", the incriminate class is this:
public class Bank {
private String name;
private int maxbankaccount;
private int activebankaccount;
private String radice = "IT8634";
private Conto[] bankaccount = new Conto[maxbankaccount];
public void addconto(String cf) {
bankaccount[activebankaccount] = new Conto(radice + activebankaccount , cf);
activebankaccount++;
}
public Bank(String name, int maxbankaccount) {
this.name = name;
this.maxbankaccount = maxbankaccount;
}
}
I wrote a tester class to test :
public class TestBank {
public static void main (String[] args) {
Bank b1 = new Bank("Fidelity", 10);
b1.addconto("PROVA");
}
}
Since I didn't seem to have made logical errors using the array I debugged, I realized that in the creation of the array of objects the maxbankaccount variable isn't 10 (value passed in Test) but as default value (0),then I tried passing 10 directly and it works good. Why is not the value 10 of maxbankaccount passed but 0?
private Conto[] bankaccount = new Conto[maxbankaccount];
This initialization takes place before the rest of the constructor runs.
Move it into the constructor:
public Bank(String name, int maxbankaccount) {
this.name = name;
this.maxbankaccount = maxbankaccount;
this.bankaccount = new Conto[maxbankaccount];
}
You have indeed made a logical error. The array bankaccount is getting initialized when the class is instantiated and is always 0.
Move it into the constructor and initialize it.
public Bank(String name, int maxbankaccount) {
/* ... */
this.bankaccount = new Conto[maxbankaccount];
}
Further more than the issues that are in the other answers, this
private int activebankaccount;
does not initialize the variable activebankaccount
So in:
public void addconto(String cf) {
bankaccount[activebankaccount] = new Conto(radice + activebankaccount , cf);
activebankaccount++;
}
you are using an uninitialized vale as index of the array bankaccount
I am building my own class, which is similar to an Enum. Here's the code:
public final class MyClass {
public final static MyClass V1 = new MyClass("v1");
public final static MyClass V2 = new MyClass("v2");
public final static MyClass V3 = new MyClass("v3");
private static Map<String, MyClass> values;
private final String name;
private MyClass(String name) {
this.name = name;
if (values == null)
values = new HashMap<>();
values.put(name,this);
}
public static MyClass[] values() {
return values.values().toArray(new MyClass[values.size()]);
}
public static MyClass valueOf(String key) {
return values.get(key);
}
public String getName() {
return name;
}
public String toString() {
return getName();
}
public static void print() {
Iterator<Map.Entry<String, MyClass>> i = values.entrySet().iterator();
while (i.hasNext()) {
String key = i.next().getKey();
System.out.println(MyClass.class.getSimpleName() + ": " + key + ", " + values.get(key));
}
}
}
I am observing a weird behavior: when I try to invoke MyClass.valueOf("v1") I get null.
I tried to debug and:
the constructor is invoked long before valueOf is invoked (when I invoke print, it gets invoked 3 times)
values gets populated (last constructor invocation, of course, takes the map size to 3, as expected.
when in valueOf, values is empty
====UPDATE
ONLY if I am in debug mode and put a breakpoint in the print method, then I can see the "enum-like-class" values printed in the console. When I do htis, valueOf returns the correct results.
What's happening?
Currently, the best way I found to tackle the issue is to move values definition and initialization before the other static variables.
This way, it gets initialized before the constructors are invoked.
Look at this: Static initializer not called on Activity creation
I am making a program that simulates a Store and a Member. I am trying to write a method, memberRegister2(). This method is the the Store class but calls the constructor from the Member class to make a member object. This method is to be passed the name, id and pinNumber as parameters and then creates the Member object, which is to be stored in a local variable 'member'. I have no idea how to do this. As you will see from the code below I have tried to use the 'Member member = new Member()' But i do not know how to make the parameters user input.
(P.S I am using BlueJ)
Here is my code for both classes hopefully making my question make more sense. I am very new to java so excuse bad coding.
public class Store
{
// instance variables
private String storeName;
private int total;
//Member member;
/**
* Constructor for objects of class Store
*/
public Store(String newStoreName, int newTotal)
{
// initialise instance variables
storeName = newStoreName;
total = newTotal;
}
//Accessor Methods
public String getStoreName()
{
return storeName;
}
public int getTotal()
{
return total;
}
public void memberRegister1(Member newMember)
{
System.out.println("Salford Thrifty " + storeName + ": Welcome " + newMember.getName() + " (id:" + newMember.getId() + ")" );
}
public void memberRegister2()
{
//Member member = new member(memberName, memberId, memberPinNumber);
}
//Mutator Methods
public void newStoreName(String newName)
{
storeName = newName;
}
public void newTotal(int newTotal)
{
total = newTotal;
}
}
and the Member class
public class Member
{
// instance variables
private String name;
private String id;
private String pinNumber;
/**
* Constructor for objects of class Member
*/
public Member(String memberName, String memberId, String memberPinNumber)
{
// initialise instance variables
name = memberName;
id = memberId;
pinNumber = memberPinNumber;
}
public Member()
{
// initialise instance variables
name = "Bob";
id = "ASD123";
pinNumber = "5678";
}
//Accessor Methods
public String getName()
{
return name;
}
public String getId()
{
return id;
}
public String getPinNumber()
{
return pinNumber;
}
//Mutator Methods
public void newName(String newMemberName)
{
name = newMemberName;
}
public void newId(String newMemberId)
{
name = newMemberId;
}
public void newPinNumber(String newMemberPinNumber)
{
name = newMemberPinNumber;
}
}
I have been told to keep the variable at the top private and use pointers? Not sure what this means but it has not been explained to me very well.
You can a Scanner to read the user's input like so.
Scanner s = new Scanner(System.in);
String userInput = s.nextLine();
Then just initialize your member instance using the strings entered by the user.
String memberName, memberId, memberPin;
Scanner s = new Scanner(System.in);
System.out.println("Enter a name");
memberName = s.nextLine();
System.out.println("Enter an id");
memberId = s.nextLine();
System.out.println("Enter a pin");
memberPin = s.nextLine();
Member m = new Member(memberName, memberId, memberPin);
Also, you probably want to make pin, and maybe the id ints instead of strings.
Here's something I have from an old class that should show you how:
SavingsAccount myAccount = new SavingsAccount(200, 5);
So when you want to create an object from another class you have to use that second class to initialize it as shown above the SavingsAccount is like int it instantiates the object and then the two integers SavingsAccount(200, 5); is used because the method within the second class is instantiated with two integers of its own so the object you are creating must have two integers of its own. And what I mean by the method has two integer instantiated is as shown in the code below:
public SavingsAccount(double amount, double rate)
{
super(amount);
interestRate = rate;
}
if you do not instantiate a method with two objects within the parentheses then you do not need them within:
SavingsAccount myAccount = new SavingsAccount(200, 5);
I hope this helps any with your question i'm fairly new myself and am trying to help with as much as I can My course uses BlueJ as well and I know a good bit about BlueJ so I hope this helps.
So i'm a little bit confused as i've never used an enum before. I want to use this enum in my main method. For some reason, i can't (i keep getting errors anytime i even try to do Status s; in main). I can however call my TestingEnum method from main and of course this works... but i am 100% sure that using the enum this way is just plain wrong. Could someone tell me how i'd go about using this in main properly?
If i try to do: Status s; in my main method, i get this error - "connot find symbol Status s;"
BACKGROUND: new to java and enums...
class MyClass {
public Status s;
public enum Status {
STATUS_OPEN(1),
STATUS_STARTED(2),
STATUS_INPROGRESS(3),
STATUS_ONHOLD(4),
STATUS_COMPLETED(5),
STATUS_CLOSED(6);
private final int status;
Status(int stat) {
this.status = stat;
}
public int getStatus() {
return this.status;
}
}
private void setStatus(Status stat) {
s = stat;
}
public void TestingEnum() {
Status myStat = Status.STATUS_ONHOLD;
setStatus(myStat);
}
#Override
public String toString() {
StringBuilder result = new StringBuilder();
String NEW_LINE = System.getProperty("line.separator");
result.append(NEW_LINE + " Status: " + s + NEW_LINE);
return result.toString();
}
}
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
// PROBLEM SETTING STATUS HERE
// I can't do this:
Status s;
}
}
Move the enum to its own class file, or access it with a reference to the enclosing class.
It looks like you defined the Enum as an inner class of another class. If you're doing this, you need to access it with the syntax OuterClass.Status to access it. You made it public, so that will work. You can access it from within the class with no problem because it's contained in the scope of the parent class.
So you can either add the OuterClass. before Status, or you can move the Enum into its own file like any other class.
From the limited code I think the problem is that you try to access
public Status s;
which is not static from the static method main
public static void main(String[] args) {
...
}
Create a instance of your class from main and have a method on that instance use s or declare s as static.
You cannot just instantiate an Enum just before a public class like that. One way to resolve the issues is to have an outer class which will have your Enum class as inner class like this:
public class MyStatus {
static enum Status {
STATUS_OPEN(1),
STATUS_STARTED(2),
STATUS_INPROGRESS(3),
STATUS_ONHOLD(4),
STATUS_COMPLETED(5),
STATUS_CLOSED(6),
ABANDONED(7);
private final int status;
Status(int stat) {
this.status = stat;
}
public int getStatus() {
return this.status;
}
}
private Status s;
public void setStatus(Status stat) {
s = stat;
}
public void TestingEnum() {
Status myStat = Status.ABANDONED;
setStatus(myStat);
}
#Override
public String toString() {
StringBuilder result = new StringBuilder();
String NEW_LINE = System.getProperty("line.separator");
result.append(NEW_LINE + " Status: " + s + NEW_LINE);
return result.toString();
}
}
Also ABANDONED wasn't defined so I just added it in the end.
Based on your edit. The problem you have is the name of the class is nested and called MyClass.Status
Try
public static void main(String[] args) {
MyClass obj = new MyClass();
//PROBLEM SETTING STATUS HERE
//I can't do this:
MyClass.Status s = MyClass.Status.STATUS_OPEN;
}
BTW: Your IDE should be able to auto fix this mistake.
The only compilation error I see is that you have used
Status myStat = Status.ABANDONED;
without defining it. I suggest you add this enum or use one you have defined.
I resolved this error by creating a nonstatic enum as outside the class.
public enum Status {
STATUS_OPEN(1),
STATUS_STARTED(2),
STATUS_INPROGRESS(3),
STATUS_ONHOLD(4),
STATUS_COMPLETED(5),
STATUS_CLOSED(6),
ABANDONED(7);
private final int status;
Status(int stat) {
this.status = stat;
}
public int getStatus() {
return this.status;
}
}
Created MyStatus class without inner enum block:
public class MyStatus {
private Status s;
public void setStatus(Status stat) {
s = stat;
}
public void TestingEnum() {
Status myStat = Status.ABANDONED;
setStatus(myStat);
}
#Override
public String toString() {
StringBuilder result = new StringBuilder();
String NEW_LINE = System.getProperty("line.separator");
result.append(NEW_LINE + " Status: " + s + NEW_LINE);
return result.toString();
}
}
Resolved for me.
You would not be able to refer to Status in main() because, while Status is public, it is not static. You would need to create an instance of your enclosing class and then use it to create an instance of the enum:
MyEnclosingClass clz = new MyEnclosingClass();
Status status = clz.new Status();
This should resolve the error I believe you are probably getting.