To be honest i am really struggling with Java, i am trying to access an array from another class. I believe i have created the array in this code
public class aff_array {
String name;
public static void main (String[] args) {
int z = 3; //total no of affirmations
int x = 1;
aff_array[] afz = new aff_array[z]; //dim
while ( x < z ) {
afz[x] = new aff_array(); // create objects for array
x = x + 1;
}
afz[1].name = "i am the best";
afz[2].name = "you are the rest";
}
but i am really having trouble trying to figure out how i access afz[1].name for example, from another class. This is probably basic but i am really struggling..
You cannot access it from another class as long as it is created as an automatic variable (in other terms, local variable). In the above code, your "afz" construct will be visible only inside the main method (and can be used only after it's instatiation). To make it visible for other classes you can define it as an instance variable. I.e:
public class aff_array {
String name;
aff_array[] afz;
public static void main (String[] args) {
int z = 3; //total no of affirmations
int x = 1;
afz = new aff_array[z]; //dim
First, you should define it as private, and create a getter method (this is a common practice, to respect encapsulation), and then get it on the other class simply calling this method.
You can access public instance variable "name" of aff_array class
//this will print value of instance variable name
System.out.println(afz[1].name);
//If you want to modify the value of variable
afz[1].name = "modified name";
However this is not recommended. Protect your instance variable with private access modifier and access it using public getter, setter methods.
Example:
public class aff_array {
private String name;
public String getName()
{
return this.name;
}
public void setName(String new_name)
{
//You can add some validations here
this.name = new_name;
}
public static void main (String[] args) {
int z = 3; //total no of affirmations
int x = 1;
aff_array[] afz = new aff_array[z]; //dim
while ( x < z ) {
afz[x] = new aff_array(); // create objects for array
x = x + 1;
}
//To print name
System.out.println(afz[1].getName());
//to set new value to name
afz[1].setName("i am the best");
afz[2].setName("you are the rest");
}
So i have tried to add getters and it looks like this
public class aff_array {
String name;
aff_array[] afz;
public aff_array[] getAfz() {
return afz;
}
public String getName() {
return name;
}
public static void main (String[] args) {
int z = 3; //total no of affirmations
int x = 1;
aff_array[] afz = new aff_array[z]; //dim
while ( x < z ) {
afz[x] = new aff_array(); // create objects for array
x = x + 1;
}
afz[1].name = "i am the best";
afz[2].name = "you are the rest";
}
This is the other class and where i want the array value to replace aff_array.class.getName() with aff_array[] getAfz() but i dont know how to do it or reference afz(1) for example (getName is working)
public void onReceive(Context context, Intent intent)
{
setNotification(context, aff_array.class.getName());
WakeLocker.acquire(context);
Toast.makeText(context,"One shot alarm received. No more toasts will be shown.", Toast.LENGTH_SHORT).show();
WakeLocker.release();
}
Related
I am trying to call the array variables in the reference class, try to sort them using a user-defined method and call the method onto the case statement that will be invoked if the user chooses a particular number. I wanted to provide the user the option what attribute of a student will be sorted (i.e. name, course...) and show the sorted one dimensional array called in the case statements and invoked through the main method.
Here's the variables in the Reference class:
class RecordReference {
private int idNumber;
private String firstName = "";
private String middleName = "";
private String lastName = "";
private int age;
private String yearLevel;
private String course = "";
private double gwa;
public RecordReference(int i, String f, String m, String l, int a, String y, String c, double g) {
idNumber = i;
firstName = f;
middleName = m;
lastName = l;
age = a;
yearLevel = y;
course = c;
gwa = g;
}
public int getIdNumber() {
return idNumber;
}
public String getFirstName() {
return firstName;
}
public String getMiddleName() {
return middleName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getYearLevel() {
return yearLevel;
}
public String getCourse() {
return course;
}
public double getGwa() {
return gwa;
}
public void setIdNumber(int idnumber) {
idNumber = idnumber;
}
public void setFirstName(String fName) {
firstName = fName;
}
public void setMiddleName(String mName) {
middleName= mName;
}
public void setLastNameName(String lName) {
lastName= lName;
}
public void setAge(int a) {
age = a;
}
public void setYearLevel(String yLevel) {
yearLevel = yLevel;
}
public void setCourse(String c) {
course = c;
}
public void setGwa(int gwa) {
gwa = gwa;
}
public String toString() {
return String.valueOf(System.out.printf("%-15s%-15s%-15d%-15d%n",
firstName, course , yearLevel ,gwa));
}
} // end of class
And I am trying to call it in this sort method, but I don't know how to reference it.
public static void sortFirstNameArray(String[] f){
for (int i = 0; i < f.length - 1; i++) {
for (int j = i + 1; j < f.length; j++) {
if (f[i].compareToIgnoreCase(f[j]) > 0) {
String temp = f[i];
f[i] = f[j];
f[j] = temp;
}
}
}
}
After the sorting is successfully done, I'll call it in a switch case statements that will be invoked once the user chooses a particular number. This part has 5 case statements (Name, Age, Course, General Weighted Average and the option to sort it all - I plan to add more student attributes if this works)
(I don't know if I should store this in another method and call it in the main method or just put it in the main method like that)
public RecordReference Process(RecordReference[] f, RecordReference[] a) {
// for loop?
for (int x = 0; x < f.length; x++) {
switch (choice) {
case 1:
System.out.println("Sorted array of first name: ");
sortFirstNameArray(f[x].getFirstName());
System.out.printf("%-15s%n", Arrays.toString(f));
break;
case 2:
System.out.println("Sorted array of age: ");
// invokes the age method
sortAgeArray(a[x].getAge());
System.out.printf("%-15s%n", Arrays.toString(a));
break;
}
}
}
If it is in another method, what param do I include when I call it in the main method?
I tried this but it doesn't work, I don't know what to do
System.out.print("Please choose what student attribute you want to
sort :");
choice = keyboard.nextInt();
// calling the process method here, but I receive syntax error
Process(f,a); // Here, I want to pass the sorted values back into the array but I get an error.
If you can help me out that would be great. Thank you in advance.
I'm just a first year student and I am eager to learn in solving this error.
It's good to see that you have attempted the problem yourself and corrected your question to make it clearer, because of that I am willing to help out.
I have tried to keep the solution to the problem as close to your solution as possible, so that you are able to understand it. There may be better ways of solving this problem but that is not the focus here.
First of all, let's create a class named BubbleSorter that will hold methods for sorting:
public class BubbleSorter
{
//Explicitly provide an empty constructor for good practice.
public BubbleSorter(){}
//Method that accepts a variable of type RecordReference[], sorts the
//Array based on the firstName variable within each RecordReference
//and returns a sorted RecordReference[].
public RecordReference[] SortByFirstName(RecordReference[] recordReferencesList)
{
for (int i = 0; i < recordReferencesList.length - 1; i++) {
for (int j = i + 1; j < recordReferencesList.length; j++) {
if (recordReferencesList[i].getFirstName().compareToIgnoreCase
(recordReferencesList[j].getFirstName()) > 0) {
RecordReference temp = recordReferencesList[i];
recordReferencesList[i] = recordReferencesList[j];
recordReferencesList[j] = temp;
}
}
}
return recordReferencesList;
}
}
That gives us a class that we can instantiate, where methods can be added to be used for sorting. I have added one of those methods which takes a RecordReference[] as a parameter and sorts the RecordReference[] based on the firstName class variable within each RecordReference. You will need to add more of your own methods for sorting other class variables.
Now for the main class:
class Main {
public static void main(String[] args) {
//Get a mock array from the GetMockArray() function.
RecordReference[] refArray = GetMockArray();
//Instantiate an instance of BubbleSorter.
BubbleSorter sorter = new BubbleSorter();
//Invoke the SortByFirstName method contained within the BubbleSorter
//and store the sorted array in a variable of type RecordReference[] named
//sortedResult.
RecordReference[] sortedResult = sorter.SortByFirstName(refArray);
//Print out the results in the sorted array to check if they are in the correct
//order.
//This for loop is not required and is just so that we can see within the
//console what order the objects in the sortedResult are in.
for(int i = 0; i < sortedResult.length; i++)
{
System.out.println(sortedResult[i].getFirstName());
}
}
public static RecordReference[] GetMockArray()
{
//Instantiate a few RecordReferences with a different parameter for
//the firstName in each reference.
RecordReference ref1 = new RecordReference(0, "Ada", "Test", "Test", 22, "First",
"Computer Science", 1.0f);
RecordReference ref2 = new RecordReference(0, "Bob", "Test", "Test", 22, "First",
"Computer Science", 1.0f);
RecordReference ref3 = new RecordReference(0, "David", "Test", "Test", 22,
"First", "Computer Science", 1.0f);
//Create a variable of type RecordReference[] and add the RecordReferences
//Instantiated above in the wrong order alphabetically (Based on their firstName)
//class variables.
RecordReference[] refArray = {
ref2, ref3, ref1
};
return refArray;
}
}
In the main class I have provided verbose comments to explain exactly what is happening. One thing I would like to point out is that I have added a method named GetMockArray(). This is just in place to provide a RecordReference[] for testing and you probably want to do that somewhere else of your choosing.
If anything is not clear or you need some more assistance then just comment on this answer and I will try to help you further.
Thanks.
The goal of the application is as following: I want to create objects (airplanes) of the class "Flugzeug" (German word for airplane). I want to create an array which refers to the different attributes of the objects.
The problem is (as far as I know) that one single array can only refer to variables of the exact same type.
How can I change my program that it works? Is it inevitable to create an array for each attribute (e.g. for each different type of variable)?
The code:
public class Fluggesellschaft {
public static void main(String[] args) {
Flugzeug [] airline = new Flugzeug [4];
for (int i = 0; i < 4; i=i+1){
airline[i] = new Flugzeug ();
airline[0].type = "A320";
airline[0].idNumber = "1";
airline[0].seats = "165";
airline[0].velocity = "890";
airline[0].range = "12600";
airline[1].type = "Boeing 747";
airline[1].idNumber = "2";
airline[1].seats = "416";
airline[1].velocity = "907";
airline[1].range = "12700";
airline[2].type = "Avro RJ 85";
airline[2].idNumber = "3";
airline[2].seats = "93";
airline[2].velocity = "760";
airline[2].range = "2200";
airline[3].type = "Airbus 380";
airline[3].idNumber = "4";
airline[3].seats = "516";
airline[3].velocity = "907";
airline[3].range = "12000";
}
for (int i=0; i < 4; i=i+1) {
airline[i].printInfo();
double time = airline[i].getTime(6320); //distance from Zurich to New York
System.out.println("duration: " + time + " h");
int capacity = airline[i].getCapacity(365);
System.out.println("capacity: " + capacity + " passengers / year");
}
}
}
public class Flugzeug {
String type;
int idNumber;
int seats;
double velocity;
double range;
double distance;
int days;
public void printInfo() {
System.out.println("type: " + this.type);
System.out.println("ID-number: " +this.idNumber);
System.out.println("seats: " + this.seats);
System.out.println("velocity: " + this.velocity);
System.out.println("range: " + this.range);
}
public double getTime (double dist) {
double result = 0;
result = dist / velocity;
double time = result;
return time;
}
public int getCapacity(int days) {
int capacity = seats * days;
return capacity;
}
}
The core of your problem is this:
one single array can only refer to variables of the exact same type.
That is correct (or mostly correct, all elements of an array must have a common base type, but that's not a relevant distinction right now).
But the type inside of your array is Flugzeug, not String!
So each element of the array must be a Flugzeug. That doesn't mean that the fields of that class have to all share a single type (and indeed, as you posted, they don't).
Look at this line:
airline[0].idNumber = "1";
this is almost correct, but since idNumber is an int you must assign it an int value (such as 1) instead:
airline[0].idNumber = 1;
The second (mostly unrelated) problem is that you try to access all 4 Flugzeug instances inside of the loop that creates them. That means when you try to access the second instance after just having created the first one (only!) it will crash:
Replace this:
for (int i = 0; i < 4; i=i+1) {
airline[i] = new Flugzeug ();
airline[0].type = "A320";
airline[1].type = "Boeing 747";
airline[2].type = "Avro RJ 85";
airline[3].type = "Airbus 380";
}
with this:
for (int i = 0; i < 4; i=i+1) {
airline[i] = new Flugzeug ();
}
airline[0].type = "A320";
airline[1].type = "Boeing 747";
airline[2].type = "Avro RJ 85";
airline[3].type = "Airbus 380";
if some type like int,double,long... was used " " ,They almost all become String type
I found two problems with your code.
First, you have declared idNumber as int int idNumber; but while assigning the value you are inserting a string value airline[0].idNumber = "1";.
NOTE: "1" is a string not integer.
The solution here would be airline[0].idNumber = 1;
You need to assign same type of values to every variable as they are declared.
And second, you are creating multiple objects in the loop airline[i] = new Flugzeug (); but overwriting the same single object (stored in the 0th position of the array) everytime. I would suggest to do,
airline[i].type = "A320";
airline[i].idNumber = 1; // Again this should not be "1"
airline[i].seats = 165; // And this should not be "165"
airline[i].velocity = 890; // Same is applicable here
airline[i].range = 12600; // and here
The problem is the variables are not only String type but ints and doubles as well. You need to assign the correct type. In addition you shouldn't access class variables like that, make them private create a constructor with getters and setters.
public class Flugzeug {
private String type;
private int idNumber;
private int seats;
private double velocity;
private double range;
private double distance;
private int days;
public Flugzeug(String type, int idNumber, int seats, double velocity, double range) {
this.type = type;
this.idNumber = idNumber;
this.seats = seats;
this.velocity = velocity;
this.range = range;
}
public double getDistance() {
return this.distance;
}
public void setDistance(double distance) {
this.distance = distance;
}
}
public class Fluggesellschaft {
public static void main(String[] args) {
Flugzeug[] airline = new Flugzeug [4];
airline[0] = new Flugzeug("A320", 1, 165, 890, 12600);
airline[1] = new Flugzeug(...);
}
}
public void processVmCreate(SimEvent ev) {
int[] data = (int[]) ev.getData();
int datacenterId = data[0];
int vmId = data[1];
int result = data[2];
}
I want to access the local variable of method processVmCreate(SimEvent ev)
in another class that is in another package. How can i access?
Local variables die after the method execution is done.
If you want to use them in other method, your choices are :
1) Pass to that method, assuming you calling that method here (using it's instance may be or with in the same class method).
2) Creating static variable and assign here , so it avail there. But make sure that you call this method before using it. but I prefer the first. Unless you have no option choose the static.
To get your results from another class, you can :
1 - Declare them as global attributes and access to them by their getters like this:
public class YourClass {
int datacenterId = -1;
int vmId = -1;
int result = -1;
public void processVmCreate(SimEvent ev) {
int[] data = (int[]) ev.getData();
datacenterId = data[0];
vmId = data[1];
result = data[2];
}
public int getDatacenterId() {
return datacenterId;
}
public int getVmId() {
return vmId;
}
public int getResult() {
return result;
}
}
2- Or you can transform your method like this and let it return a hashMap :
public HashMap<String, Integer> processVmCreate(SimEvent ev) {
int[] data = (int[]) ev.getData();
HashMap<String, Integer> map = new HashMap<>() ;
map.put("datacenterId", data[0]) ;
map.put("vmId", data[1]) ;
map.put("result", data[2]) ;
return map ;
}
And from another class you can access to your attributs like this :
public class AnotherClass {
//other code
public void anotherMethod(){
YourClass yourClass = new YourClass() ;
int datacenterId = yourClass.processVmCreate(simEvent).get("datacenterId") ;
int vmId yourClass.processVmCreate(simEvent).get("vmId") ;
int result yourClass.processVmCreate(simEvent).get("result") ;
}
}
Unless , you can not access to local variable from another class because they are local
You can make the variables global but change the access to private and make their getter and setter methods then access them in other class.
I am new to Java and I am trying to print the student numbers and numbers (cijfer in this case) on 1 line. But for some reason I get weird signs etc. Also when I'm trying something else I get a non-static context error. What does this mean and how does this exactly work?
Down here is my code:
import java.text.DecimalFormat;
import java.util.Arrays;
public class Student {
public static final int AANTAL_STUDENTEN = 50;
public int[] studentNummer = new int[AANTAL_STUDENTEN];
public String[] cijfer;
public int[] StudentNummers() {
for (int i = 0; i < AANTAL_STUDENTEN; i++) {
studentNummer[i] = (50060001 + i);
}
return studentNummer;
}
public String[] cijfers(){
for (int i = 0; i < AANTAL_STUDENTEN; i++) {
DecimalFormat df = new DecimalFormat("#.#");
String cijferformat = df.format(Math.random() * ( 10 - 1 ) + 1);
cijfer[i++] = cijferformat;
}
return cijfer;
}
public static void main(String[] Args) {
System.out.println("I cant call the cijfer and studentnummer.");
}
}
Also I'm aware my cijfer array is giving a nullpointer exception. I still have to fix this.
I am not java developer but try
System.out.print
You could loop around System.out.print. Otherwise make your functions static to access them from main. Also initialize your cijfer array.
Besides the things I noted in the comments, your design needs work. You have a class Student which contains 50 studentNummer and cijfer members. Presumably, a Student would only have one studentNummer and and one cijfer. You need 2 classes: 1 for a single Student and one to hold all the Student objects (StudentBody for example).
public class StudentBody {
// An inner class (doesn't have to be)
public class Student {
// Just one of these
public int studentNummer;
public String cijfer;
// A constructor. Pass the student #
public Student(int id) {
studentNummer = id;
DecimalFormat df = new DecimalFormat("#.#");
cijfer = df.format(Math.random() * ( 10 - 1 ) + 1);
}
// Override toString
#Override
public String toString() {
return studentNummer + " " + cijfer;
}
}
public static final int AANTAL_STUDENTEN = 50;
public Student students[] = new Student[AANTAL_STUDENTEN];
// StudentBody constructor
public StudentBody() {
// Create all Students
for (int i = 0; i < AANTAL_STUDENTEN; i++) {
students[i] = new Student(50060001 + i);
}
}
// Function to print all Students
public void printStudents(){
for (int i = 0; i < AANTAL_STUDENTEN; i++) {
System.out.println(students[i]);
}
}
public static void main(String[] Args) {
// Create a StudentBody object
StudentBody allStudents = new StudentBody();
// Print
allStudents.printStudents();
}
}
Just make all your methods and class variables as static. And then you have access to them from main method. Moreover you have got some errors in code:
public class Student {
public static final int AANTAL_STUDENTEN = 50;
// NOTE: static variables can be moved to local ones
// NOTE: only static method are available from static context
public static int[] StudentNummers() {
int[] studentNummer = new int[AANTAL_STUDENTEN];
for (int i = 0; i < AANTAL_STUDENTEN; i++)
studentNummer[i] = 50060001 + i;
return studentNummer;
}
// NOTE: only static method are available from static context
public static String[] cijfers() {
// NOTE: it is better to use same `df` instance
DecimalFormat df = new DecimalFormat("#.#");
String[] cijfer = new String[AANTAL_STUDENTEN];
for (int i = 0; i < AANTAL_STUDENTEN; i++)
// NOTE: remove `i++`, because we have it in the loop
cijfer[i] = df.format(Math.random() * (10 - 1) + 1);
return cijfer;
}
// NOTE: this is `static` method, therefore it has access only to static methods and variables
public static void main(String[] Args) {
String[] cijfer = cijfers();
int[] studentNummer = StudentNummers();
// TODO you can pring two arrays one element per line
for(int i = 0; i < AANTAL_STUDENTEN; i++)
Sytem.out.println(cijfer[i] + '-' + studentNummer[i]);
// TODO as alternative, you can print whole array
System.out.println(Arrays.toString(cijfer));
System.out.println(Arrays.toString(studentNummer));
}
}
I have 2 different Java file
Mark.java
public class Mark
//class'name has to be the same with file's name
{
private String studentName;
private int studentMark;
//studentName and studentMark are private instance variables
//which cannot be accessed by other classes
public Mark() //a default constructor
{studentName = "unknown"; studentMark = 0;} //giving a starting value
public Mark(String n, int m) //a parameterised constructor
{studentName = n; studentMark = m;}
//2 set mthods
public void setname (String n)
{studentName = n;}
public void setmark (int m)
{studentMark = m;}
//2 get methods
public String getname()
{return studentName;}
public int getmark()
{return studentMark;}
//get Grade method
public String Grade;
//"final" means constant
final int PASS = 50;
final int CREDIT = 65;
final int DISTINCTION = 75;
final int highDISTINCTION = 85;
{
//if statement
if (studentMark < PASS)
Grade = "F";
else if (studentMark < CREDIT)
Grade="P";
else if (studentMark < DISTINCTION)
Grade="C";
else if (studentMark < highDISTINCTION)
Grade="D";
else
Grade="HD";
}
public void setGrade (String g) {Grade = g;}
public String getGrade() {return Grade;}
}
And GUI.java
import javax.swing.*; //to run JFrame
import java.awt.*; //to run FlowLayout
import java.awt.event.*; //to run ActionListener
import javax.util.*;
public class MarksGUI extends JFrame implements ActionListener
{
//declare class instance variables
String studentName = nameField.getText();
int studentMark = Integer.parseInt(markField.getText());
final int MAX_STUDENT = 10;
//declare maximum student constant
private Mark [] markArray = new Mark[MAX_STUDENT];
//declare current student variable
private int currentStudent = 0; //to count the numbers of students from 0 to 9
markArray[currentStudent] = new Mark (studentName, studentMark);
private void enterStudentNameAndMark()
{
}
Currently I am trying to find a way so that the name and mark input data would be processed through the mark.java and store in the array, what would be the most efficient way to do this>
First, move your "if statements" into the constructor or to another private method and add it into the constructor.
NOTE: don't make public because you will use it in the constructor as a grade init method
private void updateGrade(int studentMark){
if (studentMark < PASS)
Grade = "F";
else if (studentMark < CREDIT)
Grade="P";
else if (studentMark < DISTINCTION)
Grade="C";
else if (studentMark < highDISTINCTION)
Grade="D";
else
Grade="HD";
}
don't forget to update Grade in setters.
public void setmark (int m){
studentMark = m;
updateGrade(m);
}
If I got your question right, you could call the method as soon as the parameterized constructer is called.
As you call the constructor in the array, the Grade would be generated.
Or you could call the the constructor in your actionPerformed method.