Use returned array to another operation - java

I've read a text from file into an array. I'd like to iterate through this array in another class (to reverse an array and find every 5th element). I have a problem with use this array in another class - this class cannot see array. Could anyone help me?
package iterators;
import java.util.*;
import java.io.*;
import iterators.*;
public class Dunno{
int i = 1;
String[] something() throws IOException {
BufferedReader read = new BufferedReader(new FileReader("file.txt"));
StringBuilder sb = new StringBuilder();
String text = read.readLine();
while (text != null) {
sb.append(text);
sb.append("\n");
text = read.readLine();
}
String all = sb.toString();
String film = all;
String znak = ",";
String[] tab;
tab = film.split(znak);
for (i = 0; i < tab.length; i++) {
System.out.println(tab[i]);
}
return tab;
}
}
And 2nd class:
public class Dunno1{
Dunno dunn=new Dunno();
dunn.something();
public String dunn(){
//Iterate
}
}

In your second class you're calling the first class method in class scope, you're not calling it in a method or in main. Here is how you should do it:
public class Dunno1 {
public static void main(String[] args) throws IOException {
Dunno1 d1 = new Dunno1();
Dunno dunn = new Dunno();
String[] d = dunn.something();
d1.dunn(d);
}
public String dunn(String [] d) {
return null;
// Iterate
}
}
You need to construct an object of your second class as well so that you can call the dunn method and pass it the String array you're getting from your first class (That's why the signature of the method in my answer is different).

public class Dunno1{
Dunno dunn=new Dunno();
dunn.something();
public String dunn(){
//Iterate
}
}
The above doesn't compile, because you can't execute instructions directly inside classes. Classes must contain field declarations, constructors and methods. But not instructions.
The following would compile:
public class Dunno1{
public void foo() {
Dunno dunn = new Dunno();
String[] array = dunn.something();
// iterate over the array.
}
}
This is realy basic stuff that you should learn by reading a Java book, or a tutorial. Not by asking questions on StackOverflow.

Related

How to remove a string from arrayList ending with another string?

Question : How to remove all Strings in rayList that end with the same Last Letter as lastLetter?
I write my code like this so i remove all string from ArrayList that has same end character as lastLetter
import java.util.*;
public class LastLetter
{
public static ArrayList<String> go(ArrayList<String> rayList, char lastLetter)
{
ArrayList<String> result = new ArrayList<String>();
for(int i = 0; i<rayList.size(); i++)
{
char last = rayList.set(i, rayList.get(raylist.size() - 1));
if(lastLetter == last)
result.add(rayList.remove(i));
}
return result;
}
}
I do not know if it is working or not and i do not understand how to make runner for this code please correct any problems from my code and make a runner so we can run this code properly.
My try to make runner:
import java.util.*;
class Runner
{
public static void main(String[] args)
{
ArrayList<String> list = new ArrayList<String>();
list.add("fred");
list.add("at");
list.add("apple");
list.add("axe");
list.add("bird");
list.add("dog");
list.add("kitten");
list.add("alligator");
list.add("chicken");
LastLetter h = new LastLetter();
System.out.println(h.go(list),"m");
}
}
Please make a proper runner for this code.
Thank you
You should not remove elements while iterating the ArrayList, for more information read this post the simplest solution will be using removeif
rayList.removeIf(val-val.endsWith(String.valueOf(lastLetter)));
I would also suggest to take string as argument instead of char
public static ArrayList<String> go(ArrayList<String> rayList, String lastLetter) {
rayList.removeIf(val-val.endsWith(lastLetter));
return result;
}
And since go is static method in LastLetter class you can call it by using class name
LastLetter.go(Arrays.asList("My name is faheem"), "m");

How do I access an array within an array?

Say I have a .txt file that has information being split by a comma as such:
IN,Indiana,6634007
While this is a snippet which accesses that file and splits it:
for(int i=0; i < count; i++) {
line = bufferedReader2.readLine();
String space[] = line.split(",");
String abb = space[0];
String nme = space[1];
int pop = Integer.parseInt(space[2]);
states[i] = new State(abb, nme, pop);
}
The purpose of that was so that all the information in the txt file could be accessed, so for example this code would print exactly whats present on the .txt file:
System.out.println(states[0]);
would print:
IN,Indiana,6634007
My question is, how would I have it so that I can access the specific part of the array as in how would I print lets say just the name "Indiana" or the population "6634007"?
P.S I'm sorry if the title of my question did not make sense, I did not exactly know how to word it.
Somewhere, you have a class called State. states is an Array of this class. So you can add a getter to State:
public int getPop() {
return pop;
}
And call it on your Object like this:
System.out.println(states[0].getPop());
as states[0] is simply a State object.
Add more getters to access different fields.
if you just want to print every single line, you can try this like below:
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new FileReader("data.txt"));
String line = null;
List<String> list = new ArrayList<String>();
while((line = reader.readLine()) != null ) {
list.add(line);
}
System.out.println(list.get(0));
// TODO realease resources
}
From your question what i can realise is, you are using State class to store the information. In such case, check the state class where the first parameter value is stored. Later to print the corresponding information, access its object variable as SapuSeven mentioned.
For eg.
public class State{
public String a;
public String b;
public int c;
public State(String x, String y, int z){
a=x;
b=y;
c=z;
}
}
now u can access like
System.out.println(states[0].b);
for printing the name of city
OR
you can simply print the value using index like this
System.out.println(states[0].split(",")[2]);

How to pass a String value to another class in Java

Currently, I am running into a problem in my Java code. I am somewhat new to Java, so I would love it if you kept that in mind.
My problem is with passing a String value from one class to another.
Main Class:
private static void charSurvey()
{
characterSurvey cSObj = new characterSurvey();
cSObj.survey();
System.out.println();
}
Second:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class characterSurvey
{
public void survey(String character)
{
Scanner s = new Scanner(System.in);
int smartChina = 0,smartAmerica = 0,dumbAmerica = 0;
String answer;
System.out.println("Are you good with girls?");
System.out.println("y/n?");
answer = s.nextLine();
if(answer.equalsIgnoreCase("y"))
{
smartChina = smartChina - 3;
smartAmerica = smartAmerica + 2;
dumbAmerica = dumbAmerica + 4;
}
//...
//ASKING SEVERAL OF ABOVE ^
List<Integer> charSelect = new ArrayList<Integer>();
charSelect.add(smartChina);
charSelect.add(smartAmerica);
charSelect.add(dumbAmerica);
Collections.sort(charSelect);
Collections.reverse(charSelect);
int outcome = charSelect.get(0);
if(smartChina == outcome)
{
character = "smartChina";
}
else if(smartAmerica == outcome)
{
character = "smartAmerica";
}
else if(dumbAmerica == outcome)
{
character = "dumbAmerica";
}
System.out.println(character);
s.close();
}
}
When I call the first class I am trying to grab the value of the second.
Disclaimer* the strings in this class were not meant to harm anyone. It was a joke between myself and my roommate from China, thanks.
It seems as if you want to obtain the character in your main class after the survey has completed, so it can be printed out in the main method.
You can simply change your void survey method to a String survey method, allowing you to return a value when that method is called:
class CharacterSurvey {
public String takeSurvey() {
//ask questions, score points
String character = null;
if(firstPerson == outcome) {
character = "First Person";
}
return character;
}
}
Now, when you call this method, you can retrieve the value returned from it:
class Main {
public static void main(String[] args) {
CharacterSurvey survey = new CharacterSurvey();
String character = survey.takeSurvey();
System.out.println(character);
}
}
There are several mistakes here.
First off, in your main class as you write you call the method survey() on the CharacterSurvey object but the survey itself the way it is implemented needs a String parameter to work
public void survey(String character)
Also this method returns void. If you want somehow to grab a string out of that method you need to declare the method as
public String survey() {}
this method returns a string now.
If i were to give a general idea, declare a String variable in the second class which will be manipulated inside the survey method and once the survey is declared as a String method return the value at the end inside the method.
By doing that you'll be able to receive the String value by calling the method on the characterSurvey object (and of course assign the value to a string variable or use it however).
Hope this helped

NullPointerException error, converting string[] to int[]

I'm running out of patience and needs this problem fixed. This program is intended to retrieve data from two text files as two string arrays, then use a mergesort algorithm to sort the results. My issue is during the conversion to an integer array. I return the array I created, and see that there is data stored. However, when running an loop and checking if any index is null, I find that the program believes them all to be null.
import java.io.IOException;
import java.nio.file.Files;
import java.io.File;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.*;
public class MergeInventories
{
public static File inv1 = new File("H:\\Senior Year\\CompSci\\Projects\\storeOneInv.txt");
public static File inv2 = new File("H:\\Senior Year\\CompSci\\Projects\\storeTwoInv.txt");
//the two text files I'm retrieving data from
public static String[] store1; //string array in question
public static String[] store2;
public static void header()
{
System.out.println("Keenan Schmidt");
System.out.println("AP Computer Science");
System.out.println("Merge Inventories");
System.out.println("...finally...");
}
public static void main() throws FileNotFoundException
{
header();
readFiles(inv1,store1); //converts file to string array
sort(); //converts string[] to int[]
//System.out.print(readFiles(inv1,store1));
//System.out.print(readFiles(inv2,store2);
}
public static String[] readFiles(File file, String[] store)
{
try {
Scanner scanner = new Scanner(file);
int i = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner = new Scanner(file);
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
i++;
}
store = new String[i];
i = 0;
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
store[i] = line;
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return store;
}
public static int[] sort()
{
int[] items = new int[store1.length];
for(int i = 0; i < store1.length; i++)
{
if(store1[i] != null) //this is the line where the error occurs
{
try{
items[i] = Integer.parseInt(store1[i].replaceAll("[^0-9]"," "));
} catch (NumberFormatException nfe) {};
}
}
return items;
}
private void mergeSort(String[] arr1, String[] arr2)
{
}
private void merge(int low, int med, int hi)
{
}
}
As azurefrog mentions in a comment, Java arrays are pass by value (the reference to the array) so that when you reassign the store variable in the method, the original array you passed in doesn't get the new reference assignment.
Since you want to re-use this method multiple times to make different arrays, I would suggest making a new array everytime inside the method. No need to pass it in.
static String[] readFiles(File file){
String[] store =null;
//rest of method this same
}
Then in your calling code:
store1 = readFiles(inv1);
store2 = readFiles(inv2);
You are getting a NullPointerException when trying to access store1 because you never give store1 a value other than null, because Java is pass-by-value.
You create a new array, but you only assign it to store, which is a local variable in readFiles(), and that assignment has no effect on the store1 variable.
You do return that value from your method, but you neglected to assign it in the invoking code.
Replace
readFiles(inv1,store1); //converts file to string array
with
store1 = readFiles(inv1,store1); //converts file to string array and saves it in store1
so that the created array is assigned to store1.
As dkatzel points out, this means that there is no longer any point in passing store1 into the method in the first place. It would be a good idea to follow his advice on cleaning up the method.
You can use a List at first because the file could be of unknown size, then convert the List to an Array (using toArray), and then you will know the length to which you should initialize the int array and your code can proceed as expected.
either change to this: store1 = readFiles(inv1,store1);
or in readFiles() use this.store1 instead

How to create two object reference variables in seperate classes in java

I have a class called AgendaFunctions, a class called Main, and a class called ReadFiles. Main has a reference variable for Agenda Functions and ReadFiles. AgendaFunctions has an array of reference variables. I have code to instantiate the array, but i need to instantiate it from ReadFiles. If I instantiate it from main, it works fine. But if i call the method from ReadFiles, it doesn't work. I get a java.lang.NullPointerException error.
Here is the code for Main:
public class Main {
public static void main(String[] args) throws Exception {
ReadFiles fw = new ReadFiles(); fw.read();
agendafunctions link = new agendafunctions();
AgendaFunctions:
public class agendafunctions {
int amount = 20;
public void setamount(int data) {
}
static String input = "true";
agendaitem item[] = new agendaitem[amount];
int counter = 0;
public void instantiate() {
item[1] = new agendaitem();
item[2] = new agendaitem();
item[3] = new agendaitem();
}
public void createobject(String name, Boolean complete, String Comments) {
item[counter].name = name;
item[counter].complete = complete;
item[counter].comments = Comments;
counter++;
}
ReadFiles:
public class ReadFiles {
public void read() throws IOException {
agendafunctions af = new agendafunctions(); af.instantiate();
int readitem = 1;
BufferedReader data = new BufferedReader(new FileReader("C:/Agenda Dev Docs/data.txt"));
int filestoread = Integer.parseInt(data.readLine());
while (readitem <= filestoread) {
String name;
String complete;
String comments = null;
String line;
Boolean bc = null;
BufferedReader read = new BufferedReader(new FileReader("C:/Agenda Dev Docs/"+readitem+".txt"));
readitem++;
name = read.readLine();
complete = read.readLine();
comments = "";
while((line = read.readLine()) != null) {
comments = comments + line;
}
if(complete.equals("Complete")) {
bc = true;
} else if(complete.equals("Incomplete")) {
bc = false;
}
af.createobject(name, bc, comments);
}
}
If I call the method instantiate from ReadFiles, i get a NullPointerException. If I call it from Main, everything works. But further development requires me to call the method from ReadFiles. How would i fix this? Thanks.
You have this
int counter = 0;
public void instantiate() {
item[1] = new agendaitem();
item[2] = new agendaitem();
item[3] = new agendaitem();
}
public void createobject(String name, Boolean complete, String Comments) {
item[counter].name = name;
item[counter].complete = complete;
item[counter].comments = Comments;
counter++;
}
where item is an array with 20 indices, ie 20 elements, but your instantiate method only initializes elements at indices 1 through 3, missing 0 and 4 through 19.
In your ReadFiles#read() method, you do
agendafunctions af = new agendafunctions(); af.instantiate();
which instantiates one agendafunctions object and calls instantiate() which initializes elements at indices 1, 2, and 3 in your item array.
You then loop in the while and call
af.createobject(name, bc, comments);
a bunch of times on the same object.
The reason it fails the first time is because you haven't initialized the element in item at index 0. Arrays always start at 0, not 1.
Another cause for error (which you'll see if you fix the above problem), is that if your while loop loops more than 3 times, you'll again get a bunch of NullPointerExceptions because counter keeps growing, but you aren't initializing the elements that you'll then try to access at counter index.
item[counter].name = name; // if counter is 4, you'll get NullPointerException because
// the element there hasn't been initialized as 'new agendaitem();'
#SotiriosDelimanolis explained why you are getting NPE, to fix that you just can get rid of the instantiate() method and add item[counter] = new agendaitem(); as first line in your createobject method. Also you have to make sure your while loop does not exceed amount. To avoid these worries better use an ArrayList for agendaitem

Categories