How to use an ArrayList from one class in another? - java

I'm fairly new to Java and this may sound a bit strange.
Okay basically I'm taking in 9 values and storing them as Integers in an ArrayListScores.
I have verified that they are storing in there and all looks okay with that.
I'm developing a simple androids app.
So we take it as if I take in the 9 values in class 1 as such from text views parseInt them. This works fine that is not my issue.
Class 1
ArrayList<Integer> Scores = new ArrayList<Integer>();
Scores.add(Integer.parseInt(et1.getText().toString()));
Scores.add(Integer.parseInt(et2.getText().toString()));
Scores.add(Integer.parseInt(et3.getText().toString()));
Scores.add(Integer.parseInt(et4.getText().toString()));
Scores.add(Integer.parseInt(et5.getText().toString()));
Scores.add(Integer.parseInt(et6.getText().toString()));
Scores.add(Integer.parseInt(et7.getText().toString()));
Scores.add(Integer.parseInt(et8.getText().toString()));
Scores.add(Integer.parseInt(et9.getText().toString()));
My Problem is that I have another class which I want to do some basic calculations, just add up all the scores as such.
Class 2
public class AddNumbers {
private static AddNumbers instance;
private AddNumbers(){
}
public static AddNumbers getInstance() {
if(instance == null) {
instance = new AddNumbers();
}
return instance;
}
public int getFinalScore() {
ArrayList<Integer> Scores = new ArrayList<Integer>();
int final_score = 0;
for(int s: Scores){
final_score += s;
}
return final_score;
}
}
I was to do the basic adding up of all the scores in class 2 and send the result back to class 1 but I don't know how.

Do you really need another class for this? Why not just put this in a method in Class 1?
It would look like:
public int getFinalScore(){
You want to put in your ArrayList here. This should look like:
public int getFinalScore(ArrayList<Integer> Scores) {
Then put your for loop, and return final_score:
int final_score = 0;
for (int s: Scores) {
final_score += s;
}
return final_score;
So your final method would look like this:
public int getFinalScore(ArrayList<Integer> Scores) {
int final_score = 0;
for (int s: Scores) {
final_score += s;
}
return final_score;
}
You would call it just via getFinalScore(Scores).

Pass Scores from Class 1 as a parameter into the getFinalScore method in Class 2
public int getFinalScore(List<Score> scores) {
int final_score = 0;
for(int s: scores){
final_score += s;
}
return final_score;
}
Then use the return value as your sum in Class 1.

What I would do is make a variable/instance of the ArrayList from class 1. so first you need to make Scores public so your other class can access it:
public static ArrayList<Integer> Scores = new ArrayList<Integer>(); //add public and static
Scores.add(Integer.parseInt(et1.getText().toString()));
Scores.add(Integer.parseInt(et2.getText().toString()));
Scores.add(Integer.parseInt(et3.getText().toString()));
Scores.add(Integer.parseInt(et4.getText().toString()));
Scores.add(Integer.parseInt(et5.getText().toString()));
Scores.add(Integer.parseInt(et6.getText().toString()));
Scores.add(Integer.parseInt(et7.getText().toString()));
Scores.add(Integer.parseInt(et8.getText().toString()));
Scores.add(Integer.parseInt(et9.getText().toString()));
Then, you need to refer back to it like so:
public int getFinalScore() {
ArrayList<Integer> scores = Class1.Scores; //make a new variable referring to the Scores (Case Matters!)
int final_score = 0;
for(int s: scores){ //use the new variable
final_score += s;
}
return final_score;
}
Alternatively, you can make the new variable scores (CASE matters) public and static if you want to use it in yet another class again (if you want to, this isn't necessary). However, you still need to make the ArrayList public! The public scores would look like this:
public class AddNumbers {
private static AddNumbers instance;
public static ArrayList<Integer> scores = Class1.Scores //made the variable public and static (optional)
private AddNumbers(){
}
public static AddNumbers getInstance() {
if(instance == null) {
instance = new AddNumbers();
}
return instance;
}
//same as before
public int getFinalScore() {
ArrayList<Integer> scores = Class1.Scores; //make a new variable referring to the Scores (Case Matters!)
int final_score = 0;
for(int s: scores){ //use the new variable
final_score += s;
}
return final_score;
}
}
Alternatively again, you can make a new parameter and set it to Scores (Again, you still need to make Scores public):
public int getFinalScore(ArrayList<Integer> scores) {
scores = Class1.Scores //set local variable to public variable
int final_score = 0;
for(int s: scores){
final_score += s;
}
return final_score;
}

Related

How do I write a union method without affecting the other sets?

This is the interface
public interface Set{
public static final int MAX=10;
public void add(int e);
public Set union(Set s);
public void display();
}
SetImp
public class SetImp implements Set{
private int[] set;
private int count;
public SetImp(){
set = new int[MAX];
count = 0;
}
public void add(int e){
if(!contains(e))
set[count++]=e;
}
private boolean contains(int e){
boolean found=false;
for(int i=0;i<count;i++){
if(set[i]==e){
found=true;
break;
}
}
return found;
}
public void display(){
for(int i=0;i<count;i++)
System.out.print(set[i] + " ");
System.out.println();
}
Where I had most of my problems.
Whenever I try to unite Set s with set, the union takes effect in both s.
I tried making a temp variable but it still doesn't work.
public Set union(Set s){
for(int i=0; i<count; i++){
s.add(set[i]);
}
return s;
}
}
Your code starts with 2 sets:
Given set1.union(set2), there's set1 and set2 of course.
Given: Set set3 = set1.union(set2); there are 3 completely separate sets: set1 and set2 did not change, which means set3 is different.
Therefore, you must have 3 sets. Given that at the start of the union method there are only 2... that means you must invoke new SetImp() someplace, or this is never going to work out.
I'm sure with that hint you can figure this one out :)
Create a new SetImp and add both Sets to it.
public Set union(Set s){
final Set res = new SetImp();
for(int i = 0; i < count; i++){
res.add(set[i]);
}
for(int i = 0; i < s.count; i++){
res.add(s.set[i]);
}
return res;
}

Printing on same line

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));
}
}

How do I access an ArrayList from a previous method in the same class?

In this project, I'm trying to access information from an ArrayList which contains only the dates which are Strings.
Here is part of the class I tried. If not having the whole class makes it hard to understand I can edit...
public ArrayList<String> getTicketDates(){
ArrayList<String> theDateArray= new ArrayList<>();
int i;
for (i=0; i <tickets.size(); i++){
if(tickets .get(i).getPurchased()== false){
theDateArray.add(tickets.get(i).getDate());
}
}
for(int f=0; f<theDateArray.size();f++){
System.out.println(theDateArray.get(f)+ " ");
}
return theDateArray;
}
public int getTickets(String date){
int tix= theDateArray.indexOf(date);
int occurrences= Collections.frequency(theDateArray, tix);
if (tix>=0){
System.out.println(occurrences);
}
return occurrences;
}
The 2nd class, I'm trying to count the amount of times one particular date occurs in the previous ArrayList, but it says that theDateArray cannot be resolved to a variable.
One method I've tried is just calling the entire method getTicketDates(), but what it does is it prints out the ArrayList triple, and the occurrences still don't work.
Your theDateArray variable scope is local to the getTicketDates() method, so you are not able to access it in the other method, so declare it as an instance variable as shown below:
public class YourTicketsClass {
//declare ArrayList as an instance variable
ArrayList<String> theDateArray= new ArrayList<>();
public ArrayList<String> getTicketDates(){
int i;
for (i=0; i <tickets.size(); i++){
if(tickets .get(i).getPurchased()== false){
theDateArray.add(tickets.get(i).getDate());
}
}
for(int f=0; f<theDateArray.size();f++){
System.out.println(theDateArray.get(f)+ " ");
}
return theDateArray;
}
public int getTickets(String date){
int tix= theDateArray.indexOf(date);
int occurrences= Collections.frequency(theDateArray, tix);
if (tix>=0){
System.out.println(occurrences);
}
return occurrences;
}
}
Define the array list outside of the method, then populate the list inside the method. Like this:
public class YourdataClass {
private List<String> theDateArray = new ArrayList<String>();
public ArrayList<String> getTicketDates(){
int i;
for (i=0; i <tickets.size(); i++){
if(tickets .get(i).getPurchased()== false){
theDateArray.add(tickets.get(i).getDate());
}
}
for(int f=0; f<theDateArray.size();f++){
System.out.println(theDateArray.get(f)+ " ");
}
return theDateArray;
}
public int getTickets(String date){
int tix= theDateArray.indexOf(date);
int occurrences= Collections.frequency(theDateArray, tix);
if (tix>=0){
System.out.println(occurrences);
}
return occurrences;
}
}/* end class */
Here are some references. http://www.javawithus.com/tutorial/scope-and-lifetime-of-variables
https://en.wikibooks.org/wiki/Java_Programming/Scope

Random Data Analyzer

I'm creating a program that will generate 100 random numbers between 1 and 1000, add them to a list, and then sum up those numbers. Here's my code:
public class Iteration {
public static void main (String [] args){
private int RandomDataAnalyzer(int Rando) {
Random rand = new Random();
List<Integer> NumList = new ArrayList<Integer>();
for (int i=0;i<=100;i++){
Rando = rand.nextInt(1001);
NumList.add(Rando);
}
int sum = 0;
for (int i=0; i<100; i++)
{
Rando = rand.nextInt(100);
sum = sum + Rando;
}
return sum;
}
}
}
And here's my errors:
H:\Java\Iteration.java:12: error: illegal start of expression
private int RandomDataAnalyzer(int Rando) {
^
H:\Java\Iteration.java:12: error: ';' expected
private int RandomDataAnalyzer(int Rando) {
^
H:\Java\Iteration.java:12: error: ';' expected
private int RandomDataAnalyzer(int Rando) {
Any help, please?
You can't define a method inside another method. Close your main method first, then start RandomDataAnalyzer:
public static void main(String[] args) {
// Contents of main.
}
public int RandomDataAnalyzer(int Rando) {
// Contents of RandomDataAnalyzer.
}
I'm going to assume that this isn't a homework problem and that you're learning Java on your own. If I'm wrong, shame on me for giving a working version. But my impression is that you'll learn from this:
public class gpaCalc
{
static Random rand;
static int rando;
public static void main(String[] args)
{
ArrayList<Integer> NumList = new ArrayList<>(); // use ArrayList
for (int i=0;i<=100;i++)
{
rand = new Random();
rando = rand.nextInt(1001);
NumList.add(rando);
}
int sum = 0;
for (int i=0; i<100; i++)
{
rando = NumList.get(i); // get is "opposite" of put--get the value put into the list earlier
sum = sum + rando;
}
System.out.println(sum);
}
}
There doesn't seem to be a need for a separate method called randomDataAnalyzer.
Welcome to StackOverflow.
Let's begin with the first issue: randomDataAnalyzer is being defined inside main method. Which is wrong, you should be actually defining it at the same level.
Taken into consideration, you should also add the static word before this function because this method is part of the class, and not of the elements. It's not necessary to create a new element of the class 'Iteration' for using a simple method.
Last, but not least, you are looping through the arraylist incorrectly. You are not even calling it. As you will see now:
import java.util.*;
public class Iteration
{
public static void main(String[] args)
{
ArrayList<int> numberList = new ArrayList<int>(); // we define the arraylist
for (int i = 0; i < 100; i++)
{
numberList.add(new Random().nextInt(1001)); // we add a random number to the list
}
// finally, after the 100 values were added..
System.out.println(randomDataAnalyzer(numberList)); // we show the output
}
public static int randomDataAnalyzer(ArrayList<int> list) // we will send this function an arraylist which will get the Σ.
{
int sum = 0;
for (int value : list) // this is how we loop through foreach value in the list
{
sum += value; // which means sum = sum + value.
}
return sum; // after looping and summing up, here'll be the result
}
}
I hope this was what you were looking for.
Here's a working version. Note the changes to your original:
Don't define methods inside methods: it is illegal syntax.
Rando, NumList: the naming conventions are to start classes, interfaces, enums (i.e. types) with a capital letter, and methods, fields, and variables with a lowercase case letter;
Removed the int Rando parameter alltogether: it's value was never used (it was only assigned to)
Use the values from numList rather than generating new numbers.
Added a method illustrating that the use of such a list is not needed in this case; the 'list' of 1000 numbers is still present, but only conceptually.
import java.util.*;
public class Iteration {
public static void main (String [] args) {
int sum = new Iteration().randomDataAnalyzer();
System.out.println(sum);
}
private int randomDataAnalyzer() {
Random rand = new Random();
List<Integer> numList = new ArrayList<Integer>();
for ( int i=0; i<100; i++ )
{
numList.add( 1 + rand.nextInt(1000) );
}
int sum = 0;
for ( int i=0; i<numList.size(); i++ )
{
sum = sum + numList.get(i);
}
return sum;
}
// Note that the above method has the same effect as this one:
private int moreEfficient() {
Random rand = new Random();
int sum = 0;
for ( int i=0; i < 100; i++)
sum += 1 + rand.nextInt(1000);
return sum;
}
}

How to make an Array Accessible from instantiation in main class? Accessible to all classes in same class

I want to run a method that returns an array. Code such as this:
public static int[] getArray() {
int square[] = new int[5];
int input = 0;
System.out.println("Input a valid integer from 1-49");
System.out.println("for array input please \\(^-^)/");
System.out.println("Remember (^_'), don't repeat numbers");
Scanner reader = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.println(
"Please input the integer for position " + (i + 1) + " of the array");
input = reader.nextInt();
square[i] = input;
}
return square;
}
I have researched that you can make a variable like so int[] data = getArray();
How would I make it so that data can be accessible to other methods in the same class so I could do something like
public static int linearSearch(data) {
}
without having to constantly be re-entering the values for the array?
You can try out to introduce private variable of int[] and provide a lazy initialization for it, something like this:
class aClass {
int[] data; // default to the null
private int[] getArray() {
if (data == null) {
// your console logic for initialization
}
return data;
}
public static int linearSearch() {
int[] localData = getArray();
}
}
But in this case you can change the contents of data field in your methods across the class.
This can be done two ways:
- Either declaring the variable as class-level variable
- Or declaring it as local variable inside main method
public class ReturnIntArraysSO {
/**
* #param args
*/
public static void main(String[] args) {
int[] data = getArray();
for(int i : data){
System.out.print(i+" ");
}
linearSearch(data);
}
/**
*
* #return
*/
public static int[] getArray() {
int square[] = new int[5];
int input = 0;
System.out.println("Input a valid integer from 1-49");
System.out.println("for array input please \\(^-^)/");
System.out.println("Remember (^_'), don't repeat numbers");
Scanner reader = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.println("Please input the integer for position "
+ (i + 1) + " of the array");
input = reader.nextInt();
square[i] = input;
}
return square;
}
/**
*
* #param data
* #return
*/
public static void linearSearch(int[] data) {
for(int a : data){
if(a == 5){
System.out.println("\nFound 5!!");
}
}
}
}
You need to declare i your array like this:
public YourClass {
public static int[] square = new int[5];
}
This way you can access this array from any other class and it will remain with the exact array (that's what static for). Example:
From Class1 - YourClass.square
From Class2 - YourClass.square
Both are the same array instance

Categories

Resources