I need to access an array that is in a different class without using a getter. I have a scanner passed to a method which creates the array then calls a method to recursively fill the array with the data from a file. I then need to access the toString method and use the array from that class (Student[] list).
Public class Test
{
public static void main(String[] args) throws IOException
{
int actual = 0;
File input = new File("input.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));
Scanner scan = new Scanner(input);
C155.createList(scan);
actual = C155.getSize();
// writer.write(C155.toString(C155.list, ??????));
writer.close();
}
}
public class C155 {
public static final int MAXSIZE = 22;
private static int size = 0;
public static Student[] createList(Scanner scan)
{
Student[] list = new Student[MAXSIZE];
return populateList(list, scan);
}
private static Student[] populateList( Student[] list, Scanner scan )
{
Student s;
if ( size < MAXSIZE && scan.hasNext() )
{
s = new Student(scan.next(), scan.next(),scan.next(),
scan.nextDouble(), scan.nextInt());
list[size] = s;
size++;
System.out.println(s);
return populateList(list, scan);
}
else
return list;
}
public static String toString(Student[] list, int n)
{
String all= "All Students \n";
for (int x = 0; x <= n; x++)
{
all += list[x].toString() + "\n";
}
return all;
}
I need to call the toString method (which requires the Student[] list)from the Test class but do not really know the best way to besides creating a get method.
As a note, all the methods in class C155 are static, which is probably not the best approach.
To answer your question though, your method createList(Scanner scan) has a return type of Student[]. That's where you would obtain a reference to that array in your main method.
Scanner scan = new Scanner(input);
Student[] studentArray = C155.createList(scan); <------
actual = C155.getSize();
writer.write(C155.toString(studentArray, studentArray.length())); <------
writer.close();
Why do you need to access the list if you return it by method? Just do this:
Student[] list = C155.createList(scan);
writer.write(C155.toString(list, list.length()));
Related
I'm working on a project where I will tally a Student's choices and add them to a count array (still working on this part). For now, I'm trying to retrieve the choices that have been sent and added to a Student ArrayList in my Student class.
Student class:
public class Students {
private String name;
private ArrayList<Integer> choices = new ArrayList<Integer>();
public Students(){
name = " ";
}
public Students(String Name){
name = Name;
}
public void setName(String Name){
name = Name;
}
public String getName(){
return name;
}
public void addChoices(int Choices){
choices.add(Choices);
}
public ArrayList<Integer> getChoices(){
return choices;
}
Here is my main driver class:
public class P1Driver {
public static void main(String[] args) throws IOException{
ArrayList<Students> students = new ArrayList<Students>();
String[] choices = new String[100];
int[] count;
Scanner scan1 = new Scanner(new File("Choices.txt"));
Scanner scan2 = new Scanner(new File("EitherOr.csv"));
// Scan the first file.
int choicesIndex = 0;
while(scan1.hasNextLine()){
String line = scan1.nextLine();
choices[choicesIndex] = line;
choicesIndex++;
}
scan1.close();
// Scan the second file.
int studentIndex = 0;
while(scan2.hasNextLine()){
String line = scan2.nextLine();
String [] splits = line.split(",");
students.add(new Students(splits[0]));
for(int i = 1; i < splits.length; i++){
students.get(studentIndex).addChoices(Integer.parseInt(splits[i]));
}
studentIndex++;
}
scan2.close();
// Instantiate and add to the count array.
int countIndex = 0;
for(int i = 0; i < students.size(); i++){
if(students.get(i).getChoices(i) == -1){
}
}
The last part is where I am now. It's nowhere near done obviously (I'm right in the middle of it) but during my construction of a for loop to get the choices from the students, I'm getting an error that says, "The method getChoices() in the type Students is not applicable for the arguments (int)." Can someone explain what this means, where me error is, and possibly how to fix it? Thanks all.
getChoices(int i) is not a method you've defined.
if(students.get(i).getChoices(i) == -1){
}
getChoices() returns a list, so you can just use the get method on the list:
if(students.get(i).getChoices().get(i) == -1){
}
Alternatively, make a getChoice method:
public Integer getChoice(int i){
return choices.get(i);
}
Have you tried getChoices()[i] instead of getChoices(i)
I am trying to make the compiler pass the array from one of the classes to the main method. I don't know why it does not work, the code looks like this:
This is my main method -
public class Main {
public static void main(String[] args) {
int[] board2;
int userInput;
playBoard = methods.createBoard();
userInput = methods.input();
}
}
And this is my methods class -
import java.util.Scanner;
public class methods {
//Create board method
int[] createBoard()
{
int[] board = new int[7];
int randomNum =(int) (Math.random()*5);
for (int i=0; i<2; i++)
{
board[randomNum+i] = 1;
}
System.out.println("Board created");
return board;
}
//Take a guess method
int input()
{
int input=0;
Scanner reader = new Scanner(System.in);
System.out.println("Please enter your guess now");
input = reader.nextInt();
System.out.println("Guess entered successfully");
return input;
}
}
I am aware of that I could easily put everything in one class and even one method but i'm to practice on using classes and methods therefore I create lots of them.
You'll have to create a new instance of Main and methods first or alternatively declare the createBoard() and input() methods static.
Here is the code snippet:
public class Main {
public static void main(String[] args) {
Main m = new Main();
m.run();
}
private void run() {
methods me = new methods();
int[] playBoard = me.createBoard();
int userInput = me.input();
}
}
Also, as per the naming convention rules for the class name it should be Methods instead of methods.
You haven't declared the variable playBoard being used inside Main. Did you intend to use board2 instead. I guess you want something like below:
board2 = new methods().createBoard();
userInput = new methods().input();
You need to create an object of class methods, in order to access instance methods.
In my class ReadInput, i read a file containing integers separated by space one by one and put them into inputArray. I then want to use inputArray (and its size) in my class B and i'm attempting to do that with get and set methods but I guess i'm not using them correctly and can't pinpoint my error. Can anyone help? Thanks
import java.io.*;
import java.util.*;
public class ReadInput
{
String INPUT_FILE_NAME = "pages.dat"; // filename
private int [] inputArray;
private int size;
public ReadInput()
{
Scanner fileIn=null; //(Initialization keeps compiler happy)
try { // open file
fileIn = new Scanner(new FileInputStream(INPUT_FILE_NAME));
} catch (FileNotFoundException e) {
System.out.println("Input file "+INPUT_FILE_NAME+" not found. ");
System.exit(1);
}
while (fileIn.hasNextLine())
{
String word = fileIn.next();
size++;
}
inputArray = new int [size];
//test to see that it gives correct size
System.out.println(size);
fileIn.close(); // close file
try { // open file
fileIn = new Scanner(new FileInputStream(INPUT_FILE_NAME));
} catch (FileNotFoundException e) {
System.out.println("Input file "+INPUT_FILE_NAME+" not found. ");
System.exit(1);
}
int i=0;
while (fileIn.hasNextLine())
{
inputArray[i] = fileIn.nextInt();
i++;
}
fileIn.close();
}
public int [] getinputArray()
{
return inputArray;
}
public void setinputArray(int [] inputArray)
{
this.inputArray = inputArray;
}
public int getSize()
{
return size;
}
public void setsize(int size)
{
this.size = size;
}
}
public class B
{
ReadInput in = new ReadInput();
int [] inputs;
public B()
{
}
//this method does not work and gives an error
public void method()
{
System.out.println("in FIFO: " + in.getSize());
for(int j=0; j< inputs.length; j++)
System.out.print(inputs[j] + " ");
}
}
In B's constructor, you need to call in.initializeArrays() and in.getJobs().
Right now, in.getSize() is 0 since that's the default value of ReadInput.size. In addition, in.getInputArray() will be null since that is the default value of ReadInput.inputArray.
Alternatively, you could remove ReadInput.initializeArrays() and ReadInput.getJobs() and simply move the code into a zero-argument constructor for ReadInput, like so:
class ReadInput {
// previous fields: size, inputArray, etc.
public ReadInput() {
// code for setting size and populating inputArray from the file
}
// other methods: getJobs, etc.
}
If you do this, then you should be set. You're already calling ReadInput's constructor through your ReadInput in = new ReadInput(); line, so that line should then populate in's data.
In B's constructor, I don't see you calling
in.initializeArrays
or
setinputArray(int [] inputArray)
anywhere to actually set the array before getting the size.
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
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;
}