Convert array to string using an object from a different class - java

Hello I'm very new to Java and currently I'm trying to convert an array, that is a playfield, into a string through using a method(object) I created in a different class . This is what I have tried:
public class Testing
{
public static void main(String[] args) {
//create an empty playfield that is 10x10
Board emptyBoard = new Board(10,10);
//convert playfield to string and save it in new variable
String newBoard = convertToString(emptyBoard); // this throws an error saying "cannot resolve method 'convertToString(...)'
//now show the playfield as a string
System.out.println(newBoard);
}
}
The method convertToString lies in another class called ArrayToString, if that matters for any reason and "convertToString" should take in a Board and return a String. Any ideas on how to solve this kind of problem? :)

package foo;
// add static import to not write it before method name
import static foo.ArrayToString;
public class Testing {
public static void main(String[] args) {
// method should be static, because you don't use new ArrayToString().convertToString(emptyBoard)
String newBoard = convertToString(emptyBoard);
}
}
package foo;
public class ArrayToString {
// should be static method
public static String convertToString(Board board) {}
}

Related

Passing variable from another file and then use variable within to another method within same class

I am trying to call a variable from another class in another to the second java file
public class selectFile {
public void hdrFile(){
String hdrName = "directory";
readImage sendVari = new readImage();
sendVari.setprintHDR(hdrName);
}
}
public class readImage {
private String hdr_dir;
public static void main(String[] args){
selectFile call_vari = new selectFile();
call_vari.hdrFile();
}
public void setprintHDR(String hdr_dir){
this.hdr_dir = hdr_dir;
}
public String getprintHDR(){
return hdr_dir;
}
public void anotherMethod(){
System.out.println(getprintHDR());
}
}
I am doing this because I want to use "anotherMethod" Method in second in the third file, but when I am testing in the second java file by printing it to the terminal "anotherMethod" cannot print any hdr_dir even I return hdr_dir. But if I check "setprintHDR" by printing it to the command everything seem fine, it returns "directory"
public class Main {
public static void main(String[] args){
readImage call_vari = new readImage();
call_vari.anotherMethod();
}
}
Since you want to use the updated value in another object( basically trying to share the value between multiple objects), you should keep your variable hdr_dir as static. Static vs Instance Variables: Difference?
You were currently using the variable as instance one due to which if one object updates the value, it will remain specific to that object only.
For your main class,
public class Main {
// private String hdr_dir;
public static void main(String[] args){
int res = 0;
selectFile call_var = new selectFile();
call_var.hdrFile();
readImage call_vari = new readImage();
// call_var.anotherMethod();
// call_vari.setprintHDR("printHDR");
call_vari.anotherMethod();
}
}
and the output is
value of hdr_dir is passed is -------directory // doing some console logging
value of hdr_dir assigned is -------directory
directory

Creating multiple objects using the same instance

I just saw this tutorial creating multiple objects using the same instance by applying the DAO pattern and tried it in a simple console, but I always get this message java.lang.NullPointerException I'm now confused, as far as I know, a constructor can be used once only, and the object will be immutable. Kindly look at this:
Fighter.java
public class Fighter {
private String style;
public Fighter() {}
public String getStyle() {
return style;
}
public void setStyle(String style) {
this.style = style;
}
}
FightersDAO.java
public class FightersDAO {
public List<Fighter> getFighters(){
List <Fighter> fighter = new ArrayList<>();
String [] styles= { "Karate", "Sumo", "Pro-Wrestling" };
for(int i=0; i < styles.length; i++) {
Fighter temp = new Fighter();;
temp.setStyle(styles[i]);
fighter.add(temp);
}
return fighter;
}
}
Demo.java
public class Demo {
private static FightersDAO fighterDAO;
public static void main (String [] args) {
List <Fighter> fighters = fighterDAO.getFighters();
for(Fighter e: fighters) {
System.out.println(e.getStyle()); //this should output the objects, but nothing shows
}
}
}
Why is it null? What part did went wrong
The variable fighterDAO is never initialized. Therefore you get a NPE here:
List <Fighter> fighters = fighterDAO.getFighters();
To fix that use:
private static FightersDAO fighterDAO = new FightersDAO();
private static FightersDAO fighterDAO;
I think there is a problem because it is not initialized.
Change it:
private static FightersDAO fighterDAO = new FightersDAO();
In your code
private static FightersDAO fighterDAO;// here is not initialized. its just a declaration so fighterDAO = null;
while executing below code will throw exeption
List fighters = fighterDAO.getFighters();// means null.getFighters();
Below is the correct code
package aks;
import java.util.List;
public class Demo {
private static FightersDAO fighterDAO= new FightersDAO();
public static void main (String [] args) {
List <Fighter> fighters = fighterDAO.getFighters();
for(Fighter e: fighters) {
System.out.println(e.getStyle());
}
}
}
You can analyse this by just debuggin on eclise or any IDE
If you want same instance use below code
private static FightersDAO fighterDAO = new FightersDAO();

Return a string value to the pass-in varibale from the argument in a function

I want the pass-in variable "aaa" to be returned the value from the argument of the function. I really need my argument in the function to be defined as String, and want whatever change of the argument in the function to be return to the pass-in variable.
How do I make this happen in Java? If anyone could help I will appreciate!
public class DeppDemo {
private String aaa;
public void abc(String aaa) {
aaa = "123";
}
public static void main(String[] args) {
DeppDemo demo = new DeppDemo();
demo.abc(demo.aaa);
System.out.println(demo.aaa);
}
}
You cannot do it like this: String class in Java is immutable, and all parameters, including object references, are passed by value.
You can achieve the desired result in one of three ways:
Return a new String from a method and re-assign it in the caller,
Pass mutable StringBuilder instead of a String, and modify its content in place, or
Pass an instance of DeppDemo, and add a setter for aaa.
Here are some examples:
public class DeppDemo {
private String aaa;
private StringBuilder bbb = new StringBuilder();
public String abc() {
return "123";
}
public void def(StringBuilder x) {
x.setLength(0);
x.append("123");
}
public static void main(String[] args) {
DeppDemo demo = new DeppDemo();
demo.aaa = demo.abc(); // Assign
demo.def(demo.bbb); // Mutate
System.out.println(demo.aaa);
}
}
It's really unclear what you're asking, but it sounds like you're trying to change the content of a variable passed into a function. If so, you can't in Java. Java doesn't do pass-by-reference.
Instead, you pass in an object or array, and modify the state of that object or array.
public class DeppDemo {
public void abc(String[] aaa) {
aaa[0] = "123";
}
public static void main(String[] args) {
String[] target = new String[1];
DeppDemo demo = new DeppDemo();
demo.abc(target);
System.out.println(target[0]);
}
}
But if you're asking how to update the aaa field using the aaa argument, then you need to qualify your reference to the field using this., since you've used the same name for both. Or change the name of the argument.
public class DeppDemo {
private String aaa;
public void abc(String aaa) {
this.aaa = aaa;
}
public static void main(String[] args) {
DeppDemo demo = new DeppDemo();
demo.abc("New value");
System.out.println(demo.aaa);
}
}

Get String From Another Method?

I have two methods, the first one creates a string, then I want to use that string in the second method.
When I researched this, I came across the option of creating the string outside of the methods, however, this will not work in my case as the first method changes the string in a couple of ways and I need the final product in the second method.
Code:
import java.util.Random;
import java.util.Scanner;
public class yaya {
public static void main(String[] args) {
System.out.println("Enter a word:");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
Random ran = new Random();
int ranNum = ran.nextInt(10);
input = input + ranNum;
}
public void change(String[] args) {
//more string things here
}
}
Create an instance variable:
public class MyClass {
private String str;
public void method1() {
// change str by assigning a new value to it
}
public void method2() {
// the changed value of str is available here
}
}
You need to return the modified string from the first method and pass it into the second. Suppose the first method replaces all instances or 'r' with 't' in the string (for example):
public class Program
{
public static String FirstMethod(String input)
{
String newString = input.replace('r', 't');
return newString;
}
public static String SecondMethod(String input)
{
// Do something
}
public static void main(String args[])
{
String test = "Replace some characters!";
test = FirstMethod(test);
test = SecondMethod(test);
}
}
Here, we pass the string into the first method, which gives us back (returns) the modified string. We update the value of the initial string with this new value and then pass that into the second method.
If the string is strongly tied to the object in question and needs to be passed around and updated a lot within the context of a given object, it makes more sense to make it an instance variable as Bohemian describes.
Pass the modified string in the second method as an argument.
create a static variable used the same variable in both the method.
public class MyClass {
public string method1(String inputStr) {
inputStr += " AND I am sooo cool";
return inputStr;
}
public void method2(String inputStr) {
System.out.println(inputStr);
}
public static void main(String[] args){
String firstStr = "I love return";
String manipulatedStr = method1(firstStr);
method2(manipulatedStr);
}
}
Since you mentioned that both methods should be able to be called independently, you should try something like this:
public class Strings {
public static String firstMethod() {
String myString = ""; //Manipulate the string however you want
return myString;
}
public static String secondMethod() {
String myStringWhichImGettingFromMyFirstMethod = firstMethod();
//Run whatever operations you want here and afterwards...
return myStringWhichImGettingFromMyFirstMethod;
}
}
Because both of these methods are static, you can call them in main() by their names without creating an object. Btw, can you be more specific about what you're trying to do?

copying array values from one class to another

Im stuck with the following problem,
I've two classes, the first is readFromFile and the second class is newClass
readFromFile.java -
This reads a text file
Parses the lines of text into seperate strings
The values of these strings are stored in a String [ ] called dArray
For testing I've printed all values out and it works
newClass.java
This class is intended to copy the value of the string [ ] dArray into a new string and from there use the values ( for simplicity all I've included in the newClass is the code relating to copying the array)
What I'm doing wrong is that I'm returning dArray but its returning an array with nothing stored in it, so I either need a way to call main method from readFromFile.class / help creating a method in readFromFile that would do the same which I call from main
please help
import java.util.Scanner;
import java.io.*;
public class readFromFile
{
static String[] dArray = new String [30];
public static void main (String[] args) throws IOException
{
String part;
Scanner fileScan, partScan;
int i = 0;
int x = 0;
fileScan = new Scanner (new File("C:\\stuff.txt"));
// Read and process each line of the file
while (fileScan.hasNext())
{
part = fileScan.nextLine();
partScan = new Scanner (part);
partScan.useDelimiter(":");
while ( partScan.hasNext()){
dArray[i] = partScan.next();
i++;
}
}
for (x = 0;x<i;x++)
{ System.out.println(dArray[x]);
}
}
public String[] getArray()
{
return dArray;
}}
newClass.java
public class newClass {
readFromFile results = new readFromFile();// creating object from class readFromFile
public void copyArray() {
String[] dArray = results.getArray(); // Trying to return the values of String [] dArray from rr classs
//Method getArray in rr class is
// public String[] getArray()
// { return dArray; }
String[] arrayCopy = new String[dArray.length];
System.arraycopy(dArray, 0, arrayCopy, 0, dArray.length);
for (int i = 0; i < arrayCopy.length; i++)
System.out.println(arrayCopy[i]);
}
public static void main(String[] args) {
newClass.copyArray();
}
}
Your results generation is in readFromFile.main(), but you're expecting to call it in your readFromFile(). You need to make a constructor for readFromFile, and call that in your main method, as well.
The problem is that both classes have a main method. Only the class that you intend to run should have a main method, the other classes need only constructors. Assuming you want to run a unshown class it would be written like this.
public class ThirdClass{
public static void main(String[] args) {
readFromFile reader = new ReadFromFile();
newClass copy = new newClass();
reader.readFromFile();
String[] strings = reader.getArray();
copy.copyArray(strings)
}
For this to work you need to put all of the code in the main of readFromFile in a method called "readFromFile". and you need a method in newClass that accepts a string array as an argument. Or a constructor that accepts a string array.
Make sure that neither of them have main methods or it won't work.
Remove the static keyword before your dArray variable
Change public static void main(String[] args) throws IOException in your first class to public readFromFile() throws IOException. Keep the code inside it the same.
Change the line newClass.copyArray(); in your second class to (new newClass()).copyArray();
Move the line in your second class readFromFile results = new readFromFile(); into the public void copyArray() method.
Change public void copyArray() in your second class to public void copyArray() throws IOException
Put a try..catch block around your code in the second class's main method. i.e. change (new newClass()).copyArray(); to something like try { (new newClass()).copyArray(); } catch (IOException e) { e.printStackTrace(); }
The above should get your thing working, but a friendly note would be to experiment with the code (once it works) since it's an excellent example to understand how static keywords are used, how Exceptions are handled or thrown, and how IO is used. ;)

Categories

Resources