Calling a double array with parameters from field as method - java

disclaimer: Sorry if I used the terms incorrectly. It would be great if you could provide the correct terms (if I used them incorrectly!)
This is my class with the field and constructor:
double[] studentMathScores = {81.5,89.0,45.5,99.0,55.0,34.5,56.0,78.0,76.0,80.0};
public StudentDashboard(double[] studentMathScores)
{
this.studentMathScores = studentMathScores;
}
How do I declare an object in my main class using studentMathScores?
StudentDashboard test = new StudentDashboard(studentMathScores);
`

If you want to keep current constructor/class syntax you should declare in your main method.
double[] studentMathScores = {81.5,89.0,45.5,99.0,55.0,34.5,56.0,78.0,76.0,80.0};
In this case your declaration of studentMathScores in StudentDashboard shoul look like double[] studentMathScores;
Then have it like this:
public class Main {
public static void main(String[] args) {
double[] studentMathScores = {81.5,89.0,45.5,99.0,55.0,34.5,56.0,78.0,76.0,80.0};
StudentDashboard test = new StudentDashboard(studentMathScores);
}
}
If class syntax could be changed and studentMathScores can be static you can have it this way:
public class StudentDashboard {
static double[] studentMathScores ={81.5,89.0,45.5,99.0,55.0,34.5,56.0,78.0,76.0,80.0};
public StudentDashboard()
{
}
public static double[] getStudentMathScores() {
return studentMathScores;
}
public class Main {
public static void main(String[] args) {
StudentDashboard test = new StudentDashboard();
double[] studentMathScores = StudentDashboard.getStudentMathScores();
}
}

I'll start of with the OOP concepts.
this is how Declaration is done:
StudentDashboard test;
Now i'll initialize the object by assigning it the constructor of the class. Also providing constructor the required parameter of an array:
StudentDashboard test = new StudentDashboard(studentMathScores);
now whenever i'll need to use this array from this object this is how it will be done.
double Singleindex = test.studentMathScores[1];
double[] wholeArray = test.studentMathScores;

Related

Passing variable from another file and then use variable within to another method within same class

I am trying to call a variable from another class in another to the second java file
public class selectFile {
public void hdrFile(){
String hdrName = "directory";
readImage sendVari = new readImage();
sendVari.setprintHDR(hdrName);
}
}
public class readImage {
private String hdr_dir;
public static void main(String[] args){
selectFile call_vari = new selectFile();
call_vari.hdrFile();
}
public void setprintHDR(String hdr_dir){
this.hdr_dir = hdr_dir;
}
public String getprintHDR(){
return hdr_dir;
}
public void anotherMethod(){
System.out.println(getprintHDR());
}
}
I am doing this because I want to use "anotherMethod" Method in second in the third file, but when I am testing in the second java file by printing it to the terminal "anotherMethod" cannot print any hdr_dir even I return hdr_dir. But if I check "setprintHDR" by printing it to the command everything seem fine, it returns "directory"
public class Main {
public static void main(String[] args){
readImage call_vari = new readImage();
call_vari.anotherMethod();
}
}
Since you want to use the updated value in another object( basically trying to share the value between multiple objects), you should keep your variable hdr_dir as static. Static vs Instance Variables: Difference?
You were currently using the variable as instance one due to which if one object updates the value, it will remain specific to that object only.
For your main class,
public class Main {
// private String hdr_dir;
public static void main(String[] args){
int res = 0;
selectFile call_var = new selectFile();
call_var.hdrFile();
readImage call_vari = new readImage();
// call_var.anotherMethod();
// call_vari.setprintHDR("printHDR");
call_vari.anotherMethod();
}
}
and the output is
value of hdr_dir is passed is -------directory // doing some console logging
value of hdr_dir assigned is -------directory
directory

Creating multiple objects using the same instance

I just saw this tutorial creating multiple objects using the same instance by applying the DAO pattern and tried it in a simple console, but I always get this message java.lang.NullPointerException I'm now confused, as far as I know, a constructor can be used once only, and the object will be immutable. Kindly look at this:
Fighter.java
public class Fighter {
private String style;
public Fighter() {}
public String getStyle() {
return style;
}
public void setStyle(String style) {
this.style = style;
}
}
FightersDAO.java
public class FightersDAO {
public List<Fighter> getFighters(){
List <Fighter> fighter = new ArrayList<>();
String [] styles= { "Karate", "Sumo", "Pro-Wrestling" };
for(int i=0; i < styles.length; i++) {
Fighter temp = new Fighter();;
temp.setStyle(styles[i]);
fighter.add(temp);
}
return fighter;
}
}
Demo.java
public class Demo {
private static FightersDAO fighterDAO;
public static void main (String [] args) {
List <Fighter> fighters = fighterDAO.getFighters();
for(Fighter e: fighters) {
System.out.println(e.getStyle()); //this should output the objects, but nothing shows
}
}
}
Why is it null? What part did went wrong
The variable fighterDAO is never initialized. Therefore you get a NPE here:
List <Fighter> fighters = fighterDAO.getFighters();
To fix that use:
private static FightersDAO fighterDAO = new FightersDAO();
private static FightersDAO fighterDAO;
I think there is a problem because it is not initialized.
Change it:
private static FightersDAO fighterDAO = new FightersDAO();
In your code
private static FightersDAO fighterDAO;// here is not initialized. its just a declaration so fighterDAO = null;
while executing below code will throw exeption
List fighters = fighterDAO.getFighters();// means null.getFighters();
Below is the correct code
package aks;
import java.util.List;
public class Demo {
private static FightersDAO fighterDAO= new FightersDAO();
public static void main (String [] args) {
List <Fighter> fighters = fighterDAO.getFighters();
for(Fighter e: fighters) {
System.out.println(e.getStyle());
}
}
}
You can analyse this by just debuggin on eclise or any IDE
If you want same instance use below code
private static FightersDAO fighterDAO = new FightersDAO();

Convert array to string using an object from a different class

Hello I'm very new to Java and currently I'm trying to convert an array, that is a playfield, into a string through using a method(object) I created in a different class . This is what I have tried:
public class Testing
{
public static void main(String[] args) {
//create an empty playfield that is 10x10
Board emptyBoard = new Board(10,10);
//convert playfield to string and save it in new variable
String newBoard = convertToString(emptyBoard); // this throws an error saying "cannot resolve method 'convertToString(...)'
//now show the playfield as a string
System.out.println(newBoard);
}
}
The method convertToString lies in another class called ArrayToString, if that matters for any reason and "convertToString" should take in a Board and return a String. Any ideas on how to solve this kind of problem? :)
package foo;
// add static import to not write it before method name
import static foo.ArrayToString;
public class Testing {
public static void main(String[] args) {
// method should be static, because you don't use new ArrayToString().convertToString(emptyBoard)
String newBoard = convertToString(emptyBoard);
}
}
package foo;
public class ArrayToString {
// should be static method
public static String convertToString(Board board) {}
}

static variables appear null outside of main method

Im building a lexical/syntex analyzer for class. The problem I am having is when I try to access my static variable "lexems" or "tokens" from a method besides main they are NULL. When I use them in main (such as the lex.printList method) they are fine and filled with data.
Whats going on???
import java.io.IOException;
import java.util.ArrayList;
public class SyntaxAnalyzer {
public static int pos = 0;
public static ArrayList<String> lexems = new ArrayList<String>();
public static ArrayList<String> tokens = new ArrayList<String>();
public static String nextToken;
public static void main(String[] args) throws IOException {
LexicalAnalysis lex = new LexicalAnalysis();
lex.getFile();
lex.parseText();
ArrayList<String> lexems = lex.getLexems();
lex.printList(lexems);
ArrayList<String> tokens = lex.getTokens();
lex.printList(tokens);
//expr();
lex();
}
static void lex(){
//String lexem = lexems.get(pos);
//System.out.println(lexem);
nextToken = tokens.get(pos);
pos++;
}
}
You are overriding the lexems object with the local one so it is not static variable you are modifying inside main function.
To operate on the static one you should do
/*NOTHING HERE!!*/ lexems = lex.getLexems();
lex.printList(lexems);
...
The same issue with tokens occurs
/*NOTHING HERE!!*/ tokens = lex.getTokens();
lex.printList(tokens);
...
The problems are here:
ArrayList<String> lexems = lex.getLexems();
lex.printList(lexems);
ArrayList<String> tokens = lex.getTokens();
In you main function you do not modify the static variables but local ones (local in the main function).
Just change it to that:
lexems = lex.getLexems();
tokens = lex.getTokens();
You are creating another pair of variables in your main method, which happen to have same names as your static variables, and "overshadow" them within the scope of main method.
To fix it, you should not declare new variables, but initialise the existing ones:
public static void main(String[] args) throws IOException {
LexicalAnalysis lex = new LexicalAnalysis();
lex.getFile();
lex.parseText();
lexems = lex.getLexems();
lex.printList(lexems);
tokens = lex.getTokens();
lex.printList(tokens);
//expr();
lex();
}
This should help make the difference between the scopes used in your code :
public class MyClass{
private static int myInt;
public static void main(String[] args){
int myInt = 6;
printMyInt();
}
static void printMyInt(){ System.out.println(myInt); } // Prints 0 because uses the class field
}

Return a string value to the pass-in varibale from the argument in a function

I want the pass-in variable "aaa" to be returned the value from the argument of the function. I really need my argument in the function to be defined as String, and want whatever change of the argument in the function to be return to the pass-in variable.
How do I make this happen in Java? If anyone could help I will appreciate!
public class DeppDemo {
private String aaa;
public void abc(String aaa) {
aaa = "123";
}
public static void main(String[] args) {
DeppDemo demo = new DeppDemo();
demo.abc(demo.aaa);
System.out.println(demo.aaa);
}
}
You cannot do it like this: String class in Java is immutable, and all parameters, including object references, are passed by value.
You can achieve the desired result in one of three ways:
Return a new String from a method and re-assign it in the caller,
Pass mutable StringBuilder instead of a String, and modify its content in place, or
Pass an instance of DeppDemo, and add a setter for aaa.
Here are some examples:
public class DeppDemo {
private String aaa;
private StringBuilder bbb = new StringBuilder();
public String abc() {
return "123";
}
public void def(StringBuilder x) {
x.setLength(0);
x.append("123");
}
public static void main(String[] args) {
DeppDemo demo = new DeppDemo();
demo.aaa = demo.abc(); // Assign
demo.def(demo.bbb); // Mutate
System.out.println(demo.aaa);
}
}
It's really unclear what you're asking, but it sounds like you're trying to change the content of a variable passed into a function. If so, you can't in Java. Java doesn't do pass-by-reference.
Instead, you pass in an object or array, and modify the state of that object or array.
public class DeppDemo {
public void abc(String[] aaa) {
aaa[0] = "123";
}
public static void main(String[] args) {
String[] target = new String[1];
DeppDemo demo = new DeppDemo();
demo.abc(target);
System.out.println(target[0]);
}
}
But if you're asking how to update the aaa field using the aaa argument, then you need to qualify your reference to the field using this., since you've used the same name for both. Or change the name of the argument.
public class DeppDemo {
private String aaa;
public void abc(String aaa) {
this.aaa = aaa;
}
public static void main(String[] args) {
DeppDemo demo = new DeppDemo();
demo.abc("New value");
System.out.println(demo.aaa);
}
}

Categories

Resources