Calling an Array from an Object? - java

in my class SummerStats I need to create another method that locates the largest element of the array created in my method setSalaries. How can I call the array, "salaries" to another method in the same class?
class SummerStats
{
public SummerStats()
{
}
public int[][] setSalaries(int people, int years)
{
int[][] salaries = new int[people][years];
//rows respresent people and columns represent years
for (people = 0; people < salaries.length; people++)
{
for (years = 0; years < salaries[people].length; years++)
{
salaries[people][years] = (int)(1000 + Math.random()*1000);
}
}
return salaries;
}
Also, my test class is
import java.util.*;
public class testSummerStats
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
SummerStats one = new SummerStats();
System.out.println("Enter people, then years: ");
int x = input.nextInt();
int y = input.nextInt();
one.setSalaries(x, y);
}
}

setSalaries should not return the array. Assign the array to a field of SummerStats instead. Then add another method to SummerStats for locating the largest element.

Declare your 2D-Array as a member variable. This way it will be accessible to all the methods of the class:
class SummerStats
{
private int[][] salaries;
public SummerStats()
{
}
public void setSalaries(int people, int years)
{
salaries = new int[people][years]; // initialize the array
//rows respresent people and columns represent years
for (people = 0; people < salaries.length; people++)
{
for (years = 0; years < salaries[people].length; years++)
{
salaries[people][years] = (int)(1000 + Math.random()*1000);
}
}
}
public void locateMax() {
// Your code goes here. (You can access the salaries array)
}
}
Then create a new method (locateMax i.e) that will calculate the max number of the 2D-array.

you can assign your array to a field. and access it outside. or second option you can pass pass this array to new method and there you can do operations for finding out largest element.

Your current program:
class SummerStats
{
public SummerStats()
{
}
public int[][] setSalaries(int people, int years)
**{**
int[][] salaries = new int[people][years];
....
return salaries;
**}**
}
Solution:
class SummerStats
**{**
private int[][] salaries;
public SummerStats()
{
}
public int[][] setSalaries(int people, int years)
{
salaries = new int[people][years];
....
return salaries;
}
**}**
In your current program is the variable salaries declared as a local variable of the method setSalaries and therefore its scope is limited to the scope of the method. In the solution program is the variable salaries declared as a member variable/field of the class SummerStats and therefore its scope is limited to the scope of all member method/variable declarations of the class.

Related

How to make the array size 6 in the following program by passing it like I did here?

I am practising dynamic coding so I want to create a list for class. I hereby Initialized a list for class and want to create an array with different length for each iteration in list. But It doesnt initialize it like I expected instead its length says 0.
import java.io.*;
import java.util.*;
class testcase
{
int N;
int play []= new int [N];
int villain[]=new int [N];
String status;
}
public class Main {
public static void main(String args[] ) throws Exception {
List<testcase> caseno=new ArrayList<testcase>();
Scanner sc=new Scanner(System.in);
int n1=1;
//int n1=sc.nextInt();
int i,j;
testcase t;
for(i=0;i<n1;i++)
{
int n=6;
//int n=sc.nextInt();
t=new testcase();
t.N=n;
System.out.println(t.N+" "+t.play.length);
}
}
}
The array length should print 6 instead it shows 0
You have to create a parametrized constructor in which you'll pass the value of N and then initilaze the arrays. Like
class testcase // Name should be in PASCAL
{
int N;
int [] play;
int [] villain;
String status;
public testcase (int n) { // Constructor
this.N=n;
play = new int [N];
villain=new int [N];
}
}
And in the main methos you create object like this
int n= . . .;//taking input from user
testcase t=new testcase(n);
You need to write a constructor which does these assignment based on the value passed.
// Implement your constructor something like this
public Testcase(int value) {
this.N = value;
play = new int [value];
// Some more assignment based on the need
}
And after that, you need to create the object instance
int N = 6;
Testcase newTestcase = Testcase(N);
NOTE: Clase name should always start with a capital letter.
Try declaring these variable like N, status, play e.t.c as private. After that assign and access them using getter() and setter().

Inputting random integers into a file and sorting them into another file? FileIO

I'm trying to create a FileIO where random numbers are placed into a .txt file and outputted, sorted in another .txt file. I have a bubble sort code that can sort numbers & I have another code that makes a .txt file. I'm just not sure how I'd implement these 2 together.
Here's my fileIO code:
public static void main(String[] args) {
File file = new File("test.txt");
//Writes name and age to the file
try {
PrintWriter output = new PrintWriter(file);
output.println("Rober");
output.println(27);
output.close();
} catch (IOException ex) {
System.out.printf("ERROR: %s\n", ex);
}
//Reads from the file
try {
Scanner input = new Scanner(file);
String name = input.nextLine();
int age = input.nextInt();
System.out.printf("Name: %s Age %d\n", name, age);
} catch (FileNotFoundException ex) {
System.out.printf("ERROR: %s\n", ex);
}
}
And here is my bubble sort code:
public static void main(String[] args) {
Random num = new Random();
//Creating an array for 10 integers
int [] number = new int [10];
System.out.print("Random Numbers:");
/*Display the unsorted numbers in a random order.
These numbers range from 0 to 100
*/
for (int d = 0 ; d<number.length ; d++){
/* We add a "+1" to the nextInt(100) here because then the numbers
will only range from 0 to 99.
*/
int RandomG = num.nextInt(100)+1;
number[d] = RandomG;
System.out.print(" " +RandomG);
}
//Display the sorted numbers
System.out.print("\nSorted Numbers:"+Arrays.toString(BubbleSortAsceMethod(number)));
}
public static int [] BubbleSortAsceMethod(int[] number){
int placeholder;
for(int i = 0 ; i < number.length-1 ; i++){
for ( int x = 1 ; x < number.length-i ; x++){
/*If the first number in the sequence is greater than the second
number, than save the first number of sequence in placeholder
and place the second number in the first numbers position, and
put the placeholder in the second numbers position (SWAP).
*/
/*
Since this is saying that when the first term is bigger than the
2nd term, the sequence will increase. If we flip the relational
operator, the sequence will decrease.
*/
if ( number[x-1] < number[x]){
placeholder = number[x-1];
number[x-1] = number[x];
number[x] = placeholder;
}
}
}
return number;
}
I'm kinda new to all this java stuff so please go a bit easy on me! Any help at all is appreciated :)
As the data contained in the file will consist of a pair of values: The name (String) and the age (int), you will need to retain their relationship. The best way of doing this would be to create a Class to represent the data. Eventually you want to sort the data on age using your BubbleSort method. While practically this would not be your first choice to sort data, I assume that this is a requirement. The BubbleSort method you have sorts an int[] by comparing each entry against it's immediate neighbor. With int being primitive, you can directly compare each element using the < operator.
public class Person implements Comparable<Person> {
private String name;
private int age;
public Person(String name, int age) {
this.age = age;
this.name = name;
}
public String getName() { return name; }
public int getAge() { return age; }
#Override
public String toString() {
return name + System.lineSeperator() + age;
}
#Override
public int compareTo(Person person) {
return this.age - person.age;
}
}
You may want to implement the Comparable interface to compare Objects; in which the interface must be implemented by Overriding the compareTo(Person person) method. You can impose sorting on age by returning the difference in age. This is not the only way you can impose the order you want; you may wish to compare directly using the getAge() of each Object or create a Comparator object.
Using the Comparable interface does allow you to make your BubbleSort class more generic, however (though the array must be of Objects that implement the interface; hence no primitive types).
public class BubbleSort {
public static <T extends Comparable> T[] BubbleSortAsceMethod(T[] array) {
for (int i = 0; i < array.length - 1; i++) {
for (int x = 1; x < array.length - i; x++) {
if (comparator.compare(array[x - 1], array[x]) < 0) {
T placeholder = array[x - 1];
array[x - 1] = array[x];
array[x] = placeholder;
}
}
}
return array;
}
}
You will notice that this sort method has some slight differences from your original, namely the BubbleSortAsceMethod method signature with the introduction of generic type parameters. Once again, this is completely optional, though this does give you the flexibility to use this method in the future for other arrays of Classes that extend the Comparable interface.
If you don't want to use generics or the Comparable interface, you will need to change the method signature and if statement.
You're method signature should instead look like public static Person[] BubbleSortAsceMethod(Person[] array) and the if statement if (array[x-1].getAge() < array[x].getAge())
This can give you an illustration of it working, though this does not consider the file io which should be simple to implement from what you have done already.
static Random random = new Random();
public static void main (String args[]) {
int size = 100;
Person[] peopleArray = new Person[size];
for (int i = 0; i < size; i++) {
String name = generateName(random.nextInt(4) + 4);
int age = random.nextInt(100);
peopleArray[i] = new Person(name, age);
}
peopleArray = BubbleSort.BubbleSortAsceMethod(peopleArray);
}
Note that this conforms, at least as much as possible, to the code you have implemented this far. If the BubbleSort and use of arrays are not critical, data structures that implement the List interface, such as ArrayList, can allow you to implement this much cleaner. This does not use the BubbleSort method at all.
public static void main (String args[]) {
int size = 100;
ArrayList<Person> people = new ArrayList<>();
for (int i = 0; i < size; i++) {
String name = generateName(random.nextInt(4) + 4);
int age = random.nextInt(100);
people.add(new Person(name, age));
}
peopleList.sort(Person::compareTo);
//or, if you don't want to implement comparable
peopleList.sort(Comparator.comparing(Person::getAge));
}
Appendix:
Used for illustrative purposes: Generates a name of a set length (randomly).
static char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
public static String generateName(int length) {
if (length > 0) {
return alphabet[random.nextInt(alphabet.length)] + generateName(length - 1);
}
return "";
}

calculate number of occurrences in array in java

I want to calculate the number of occurences of a specific number I decide in my main method. Here is what I have to do :
• A function that fills the array with random numbers.
• A function that calculates the number of occurrences,this function may not do any input or output.
• The main function that asks the user for the number and present the result on the screen.
Here is my code in java :
import java.util.Random;
import java.util.Scanner;
public class Code {
public void calculate(int value) {
Code c = new Code();
int count=0;
for (int n=0; n<array.length; n++) { // the code does not recognize array
if (array[n]==value) { // the code does not recognize array
count++;
}
}
System.out.println(count);
}
public void addToArray() {
int k =0;
int [] array = new int[10];
int min=0;
int max=10;
int diff = max-min;
while (k<10) {
Random r = new Random();
int x = r.nextInt(diff);
array[k]=x;
k=k+1;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("give your number");
Code c = new Code();
Scanner s = new Scanner(System.in);
int value = s.nextInt();
c.addToArray();
c.calculate(value);
}
}
The only thing I need help with is the calculate method ,, eclipse does not recognize array in the calculate method above ..
How to correct the calculate method to make it recognize array ?
thank you
Your array is limited to the scope of the method addToArray(). So, it will not be visible to other methods. You need to make it global. Then it will work.
Instead of declaring array in the method addToArray, declare it in your class, like:
public class Code {
int [] array = new int[10];
...
if using Java 8 you could update your calculate methode like this :
public void calculate(int value) {
System.out.println(Arrays.stream(array)
.filter(i -> i == value)
.count());
}
By adding this imports to your class :
import java.util.Arrays;
And like mentionned HackerDarshi declaring the attribut array as a member of your class

Setter function with arguments

Alright so I am doing an exercise where I have an object that contains scores for 3 tests.
I then have a set-function that takes 2 arguments, the test number and the score you set to it.
Right now my problem is that I do not know how to make the test number argument work correctly.
The code works if I do test1 = score, but when I put student1.test1 in the set argument, for some reason it does not register.
I hope you can point me in the right direction, I would be really grateful!
I have a main class and a student class:
public class Main {
public static void main(String[] args) {
Student student1 = new Student();
student1.setTestScore(student1.test1, 50);
System.out.print(student1.test1);
}
}
public class Student {
int test1;
int test2 = 0;
int test3;
Student() {
int test1 = 0;
int test2 = 0;
int test3 = 0;
}
public void setTestScore(int testNumber, int score){
testNumber = score;
}
}
Java is a pass by value language, so when you pass student1.test1 to student1.setTestScore, you are passing a copy of that member. You are not passing a reference to the member. Therefore the method can't change the member's value.
Even if the language allowed such modification, it would be a bad idea in terms of object oriented programming, since you normally make members private and don't access them directly from outside the class.
A possible alternative is to use an array :
public class Student {
int[] test = new int[3];
...
public void setTestScore(int testNumber, int score){
if (testNumber >= 0 && testNumber < test.length)
test[testNumber]=score;
}
...
}
and you'd call the method like this :
student1.setTestScore(0, 50); // note that valid test numbers would be 0,1 and 2

How to use an ArrayList from one class in another?

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

Categories

Resources