Array average calculation - java

Cannot find why my array in the class aint working. Not sure if maybe static has something to do with the problem. I receive alot of errors but i think the main one is "cannot make a static ref to the non-static field rej"
MAIN:
public class Arajmain {
public static void main (String[]args){
System.out.println(Araj.genomsnittet());
}
}
CLASS
public class Araj {
double [] rej = new double[3];
public static double genomsnitt;
rej[0] = 4;
rej[1] = 7;
rej[2] = 9;
public static double genomsnittet(){
genomsnitt = (rej[0] + rej[1] + rej[2])/3;
return genomsnitt;
}
}

public class Araj {
private static double [] rej = new double[3];
static {
rej[0] = 4;
rej[1] = 7;
rej[2] = 9;
}
public static double genomsnittet(){
double genomsnitt = (rej[0] + rej[1] + rej[2])/3;
return genomsnitt;
}
}
That's some piece of ugly code though. You should definetly have a look at a tutorial about Java and OOP.

Add the static modifier to reg:
static double [] rej = new double[3];
Also, you can initialize it using a static initialization block:
static {
rej[0] = 4;
rej[1] = 7;
rej[2] = 9;
}
Or using using a more concise array literal:
static double [] rej = new double[]{4, 7, 9};

This is quite terrible code, anyway to make it work you should have "rej" declared as static.
EDIT: As already suggested, you should also initalize it properly :
static {
rej[0] = 4;
rej[1] = 7;
rej[2] = 9;
}

Related

How can I add together a method level integer and and instance level integer in Java? [duplicate]

This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 4 years ago.
I got an error that says "non-static variable constantInteger cannot be referenced from a static context"
How do I add all three integers without changing their level?
public class VariableAdder {
final int constantInteger = 5;
int instanceInteger = 10;
public static void main(String[] args) {
int methodInteger = 20;
int result = constantInteger + instanceInteger + methodInteger;
System.out.println(result);
}
}
Expected results: adding two instance variables and one method variable and printing. Actual results: error
Thank you all for your help!
You cannot use an Instance variable(Class level, non static , final/non final) inside a static method(main() in your case).
Instantiating VariableAdder and using the instance to refer to the instance variables will solve your problem. Something like this:
public class VariableAdder {
final int constantInteger = 5;
int instanceInteger = 10;
public static void main(String[] args) {
VariableAdder t = new VariableAdder();
int methodInteger = 20;
int result = t.constantInteger + t.instanceInteger + methodInteger;
System.out.println(result);
}
If you are not looking for creating an instance, declare constantInteger and instanceInteger as static and access them directly inside the main()
An instance variable and an instance constant means you need an instance in order to access them. For your code example this means creating an instance of class VariableAdder. To create an instance you call a constructor. The following runs successfully with JDK 11.0.2 on Windows 10
public class VariableAdder {
final int constantInteger = 5;
int instanceInteger = 10;
/** Constructor */
public VariableAdder() {
}
public static void main(String[] args) {
int methodInteger = 20;
// Create an instance of class 'VariableAdder'
VariableAdder adder = new VariableAdder();
int result = adder.constantInteger + adder.instanceInteger + methodInteger;
System.out.println(result);
}
}
This should work:
final static int constantInteger = 5;
static int instanceInteger = 10;
public static void main(String[] args) {
int methodInteger = 20;
int result = constantInteger + instanceInteger + methodInteger;
System.out.println(result);
}
EDIT : OR
final static int constantInteger = 5;
static int instanceInteger = 10;
public static void main(String[] args) {
MyClass runner = new MyClass();
int ti=runner.instanceInteger;
int methodInteger = 20;
int result = constantInteger + instanceInteger + methodInteger;
System.out.println(result);
}

How to access an array from the main method?

public static int arraylistExample() {
int length [] = new int [10];
length[0] = 2;
length[1] = 3;
length[5] = 8;
return length [1];
}
I have written in the main method this:
System.out.println(length[5]);
Hence, my code looks like this:
import java.util.ArrayList;
public class Javanotes {
public static void main(String[] args) {
System.out.println(length[5]);
}
public static int arraylistExample() {
int length [] = new int [10];
length[0] = 2;
length[1] = 3;
length[5] = 8;
return length [1];
}
}
and I get a "0" what should I do?
1) The array is defined in the method scope of arraylistExample(). It is not visible from main().
2) The array will be empty if you never call the method.
You could change it in this way :
public class Javanotes {
static int length [];
public static void main(String[] args) {
System.out.println(arraylistExample()); // print 3
System.out.println(length[5]); // print 8
}
public static int arraylistExample() {
length = new int [10]; // init the static field
length[0] = 2;
length[1] = 3;
length[5] = 8;
return length [1];
}
}
But note that using static everywhere is generally not the right thing.
You do that for utility classes.
You should declare the function before calling it.
your function arraylistexample is not seen by the main class

How to read copy the array with the array from another class? [In loading file]

I want to create a game and I need to read file from the notepad
when I use my loadfile.java alone, it work very well. Then, I would like to copy my data into datafile.java as it will be easier for me to do the fighting scene. However, I can't copy the array in my loadfile.java to the datafile.java and I don't understand why.
import javax.swing.*;
import java.io.*;
import java.util.Scanner;
public class loadfile
{
static String filename = "Save.txt";
static int size = 4;
static int s;
static int[] number;
static String[] line;
private static void load() throws IOException
{
BufferedReader reader = new BufferedReader(new FileReader(filename));
while (reader.readLine()!= null)
{
size++;
}
size -= 4;
reader.close();
line = new String[size];
number = new int[size];
BufferedReader reader2 = new BufferedReader(new FileReader(filename));
for (int i = 0; i < size; i++)
{
line[i] = reader2.readLine();
}
reader2.close();
for (int i = 4; i < size; i++)
{
number[i] = Integer.parseInt(line[i]);
}
}
public static String[] getData()
{
return line;
}
public static int[] getNumber()
{
s = size - 4;
int[] num = new int[s];
for (int i = 0; i < s; i++)
{
num[i] = number[i+4];
}
return num;
}
public static int getDataSize()
{
return size;
}
public static int getNumberSize()
{
return size - 4;
}
This is my loadfile.java
I use the file with 4 names and 9 * n int in the notepad as I want to check whether I have the character first before I read the file. However, before I can handle this problem, I got another problem that I can't copy the array into my datafile.java
The datafile.java is separate with two constructor. One is for Starting the game and one is for loading the data. The constructor with the (int num) is the problem I have. First, I would like to show the java first:
import java.util.Arrays;
import java.io.*;
public class datafile
{
private static String[] data;
private static int[] number;
private static String[] name;
private static int[] a, d, s;
private static int[] hp, maxhp;
private static int[] mp, maxmp;
private static int[] lv, exp;
public datafile()
{
initialization();
name[0] = "Pet";
a[0] = 100;
d[0] = 100;
s[0] = 100;
hp[0] = 500;
mp[0] = 500;
maxhp[0] = 500;
maxmp[0] = 500;
exp[0] = 100;
lv[0] = 1;
}
public datafile(int num) throws IOException
{
initialization();
loadfile l = new loadfile();
for (int i = 0; i < l.getNumberSize(); i++)
{
number[i] = l.getNumber()[i];
}
for (int i = 0; i < l.getDataSize(); i++)
{
data[i] = l.getData()[i];
}
for(int i = 0; i < 4; i++)
{
name[i] = data[i];
}
for(int i = 0; i < 4; i++)
{
a[i] = number[1+(i*9)];
d[i] = number[2+(i*9)];
s[i] = number[3+(i*9)];
hp[i] = number[4+(i*9)];
mp[i] = number[5+(i*9)];
maxhp[i] = number[6+(i*9)];
maxmp[i] = number[7+(i*9)];
lv[i] = number[8+(i*9)];
exp[i] = number[9+(i*9)];
}
}
public static String getName(int n)
{
return name[n];
}
public static int getAttack(int n)
{
return a[n];
}
public static int getDefense(int n)
{
return d[n];
}
public void initialization()
{
name = new String[3];
a = new int[3];
d = new int[3];
s = new int[3];
hp = new int[3];
mp = new int[3];
maxhp = new int[3];
maxmp = new int[3];
lv = new int[3];
exp = new int[3];
}
public static void main (String[] args) throws IOException
{
new datafile(1);
}
}
When I run the program, the debugging state this line
data[i] = l.getData()[i];
as an error
I don't know what wrong with this line and I tried so many different ways to change the way the copy the method. However, it didn't work
The error says this:
Exception in thread "main" java.lang.NullPointerException
at datafile.<init>(datafile.java:38)
at datafile.main(datafile.java:92)
I hope you guys can help me with this problem because I don't want to fail with my first work
in your datafile(int num)
you call
loadfile l = new loadfile();
but you never call the load() method on you loadfile
l.load();
Edit: my bad, I didn't see your initialization method, but regardless, I'm going to stick with my recommendation that you radically change your program design. Your code consists of a kludge -- you've got many strangely named static array variables as some kind of data repository, and this suggests that injecting a little object-oriented design could go a long way towards creating classes that are much easier to debug, maintain and enhance:
First I recommend that you get rid of all of the parallel arrays and instead create a class, or likely classes, to hold the fields that need to be bound together and create an ArrayList of items of this class.
For example
public class Creature {
private String name;
private int attack;
private int defense;
// constructors here
// getters and setters...
}
And elsewhere:
private List<Creature> creatureList = new ArrayList<>();
Note that the Creature class, the repository for some of your data, should not be calling or even have knowledge of the code that loads the data, but rather it should be the other way around. The class that loads data should create MyData objects that can then be placed within the myDataList ArrayList via its add(...) method.
As a side recommendation, to help us now and to help yourself in the future, please edit your code and change your variable names to conform with Java naming conventions: class names all start with an upper-case letter and method/variable names with a lower-case letter.

What am I doing wrong with using arrays?

I'm trying to fill an array using a method and later print that array out.
However when I try to do so all it gives me are zeroes. I think my fill method is not working properly but I'm not sure why. I'm trying to understand arrays but so far no good. I would prefer an explanation rather than an answer. If I can get this myself it would be best.
import java.util.Scanner;
public class diverScore {
static double score = 0;
static double validDegreeOfDiff = 0;
public static void main(String[] args) {
double[] score = new double[6];
inputAllScores(score);
printArray(score);
}
public static double[] inputAllScores(double[] x) {
Scanner s = new Scanner(System.in);
double[] array_score = new double[6];
for (int i = 0; i < 6; i++) {
System.out.println("What is the score given by the judge?");
array_score[i] = s.nextDouble();
}
return array_score;
}
public static void printArray(double[] j) {
for (int i = 0; i < 6; i++) {
System.out.println("The array is:" + j[i]);
}
}
}
In your inputAllScores, you're writing to a new local array, and returning it, but you're not using the returned array. It would be better if you wrote to the array that you passed into that method (which inside the method is called x).
try
import java.util.Scanner;
public class DiverScore {
static double score = 0;
static double validDegreeOfDiff = 0;
public static void main(String[] args) {
// double[] score = new double[6];
double[] score = inputAllScores(/*score*/);
printArray(score);
}
public static double[] inputAllScores(/*double[] x*/) {
Scanner s = new Scanner(System.in);
double[] array_score = new double[6];
for (int i = 0; i < 6; i++) {
System.out.println("What is the score given by the judge?");
array_score[i] = s.nextDouble();
}
return array_score;
}
public static void printArray(double[] j) {
for (int i = 0; i < 6; i++) {
System.out.println("The array is:" + j[i]);
}
}
}
double[] score = new double[6];
This line simply initializes an array of type double with 6 indexes allocated for it, with each resulting in 0 when printed out.
You could simply change the code in main to this, thus actually using the return value of the inputAllScores function.
public static void main(String[] args) {
double[] score = new double[6];
printArray(inputAllScores(score));
}
HTH

Array of queues not compiling - cannot find symbol error

I'm trying to get a radix sort going with an array of queues to avoid long rambling switch statements but I'm having some trouble getting the array properly initialized. The constructor and an example of an implementation are given below.
I'm just getting a cannot find symbol error when I try to compile though.
public static radixj(){
IntQueue[] buckets = new IntQueue[10];
for (int i = 0; i < 10; i++)
buckets[i] = new IntQueue();
}
public static void place(int temp, int marker)
{
int pos = temp % marker;
buckets[pos].put(temp);
}
I'm pretty sure it is a really simple mistake that I'm making but I can't find it. Any help would be greatly appreciated.
In your code
IntQueue[] buckets = new IntQueue[10];
is a local variable to the function
public static radixj()
which must have a return type
public static void radixj()
So then you can't use it in another function
buckets[pos].put(temp);
You should declare a static class variable
class Foo {
static IntQueue[] buckets = new IntQueue[10];
...
and access it using: Foo.buckets
class Foo {
public static IntQueue[] buckets = new IntQueue[10];
public static void radixj() {
for (int i = 0; i < 10; i++) {
Foo.buckets[i] = new IntQueue();
}
}
public static void place(int temp, int marker) {
int pos = temp % marker;
Foo.buckets[pos].put(temp);
}
}
the return type in radixj() is missing and buckets cannot be resolved to a variable

Categories