Java, Passing a String from one method to another - java

I hope someone could help me please, I need to pass a String from the method below to the method below that. I have looked on the interent and got it working on test programs but can't seem to get it working on mine, it's been 3 hours, 3 pages of google and a book lol. Sorry if this is easy but I really have no idea.
What I need to do... I need to pass the variable "Hex" from the method "WMDBAudio" to the method "hexConverter". I hope this makes sense, thanks for your help in advance it's is apperciated!
public class WMDBAudio{
public String WMDBAudio1(String fileInfo) throws IOException{
//code removed as there is quite a lot
int m = 0;
while (m != 1){
for (int count = 0; count < 3; count++){
hexIn = in.read();
s = Integer.toHexString(hexIn);
if(s.length() < 2){
s = "0" + Integer.toHexString(hexIn);
}
temp = temp + s;
}
if ("000000".equalsIgnoreCase(temp)){
m = 1;
hex = entry;
}
entry = entry + temp;
temp = "";
}
}
}
//Hex Converter method
public class hexConverter{
public static void hexConverter(String t){
WMDBAudio w = new WMDBAudio();
String hex = "";
StringBuilder output = new StringBuilder();
for (int i = 0; i < hex.length(); i+=2){
String str = hex.substring(i, i+2);
output.append((char)Integer.parseInt(str, 16));
}
System.out.println(output);
}
}

By convention you name Java classes starting with upper cases. So hexConverter should be renamed to HexConverter.
You generally invoke another class from a class in this format:
MyClass myClass = new MyClass();
after that you can use myClass object to access methods (not private) of MyClass.
Make the following 2 lines change as I have commented.
public class WMDBAudio{
public String WMDBAudio1(String fileInfo) throws IOException{
//code removed as there is quite a lot
int m = 0;
while (m != 1){
for (int count = 0; count < 3; count++){
hexIn = in.read();
s = Integer.toHexString(hexIn);
if(s.length() < 2){
s = "0" + Integer.toHexString(hexIn);
}
temp = temp + s;
}
if ("000000".equalsIgnoreCase(temp)){
m = 1;
hex = entry;
}
entry = entry + temp;
temp = "";
}
//add these 2 lines
hexConverter hexConv = new hexConverter();
hexconv.hexConverter(hex);
}
}

You could set hex as a private attribute of the class, thus being acessible to both methods (and all others of the same class).
This assuming that calling the first one doesn't necessarily require calling the second one. If that's the case then you could just call hexConverter from WMDBAudio with an extra parameter for the hex String.
EDIT: Nvm that just saw they are two different classes. Well, you could save the hex as a private variable on both classes and have a GetHex() method on the WMDBAudio class. You then use the value returned by that method to create a hexConverter class that takes Hex as a parameter to its constructor thus allowing something of the sort:
WMDBAudio audio = new WMDBAudio()
...
hexConverter hexconv = new hexConverter(audio.GetHex())
Or just supply an additional parameter to the hexConverter function allowing you to write something like this:
WMDBAudio audio = new WMDBAudio()
...
hexConverter hexconv = new hexConverter()
hexconv.hexConverter(audio.GetHex())

Since hexConverter is a static method in hexConverter class,
you can access the method as
hexConverter.hexConverter(hex);
You need not create a new object to access the method. The method performs a common operation and does not change the state of the object. Hence, you can use it as above, pass the String and get the result.
You might also need to import hexConverter class if it is in a different package.

Related

I'm trying to give the value of an array of a class to another array with the same class, is there something I'm missing here?

The class is called Exposicion and has a String and an INT value, so I used it as an array to grab some input from the user.
class Exposicion {
public String nombreExpo;
public int duracionExpo;
Exposicion(String nombreExpo, int duracionExpo) {
this.nombreExpo = nombreExpo;
this.duracionExpo = duracionExpo;
}
}
With the Function SortExpo I plan to copy only the values of the array as long as the INT values don't add up to 180, but java flags an error when doing:
arrExpoT[posHor].nombreExpo = arrExpoS[k].nombreExpo;
This is the whole function
void SortExpo(Exposicion[] arrExpoS,int posicion,Exposicion[] arrExpoT){
int poshor=0;
int total=0;
for (int k = 0; k < posicion; k++) {
if ( total < 180 || arrExpoS[poshor].nombreExpo != "TOMADO123") {
arrExpoT[poshor].nombreExpo = arrExpoS[k].nombreExpo;
arrExpoT[poshor].duracionExpo = arrExpoS[k].duracionExpo;
arrExpoS[poshor].nombreExpo = "TOMADO123";
total = total + arrExpoS[k].duracionExpo;
poshor++;
} else {
k = posicion;
}
}
}
Error
I've added the .java file in this link
Also Main.java if this helps
You are getting a NullPointerException because "expo1" and "sala1" variables are both null. You have to pass a reference to an object on both variables. Something like this:
class SalaExpo(){
Exposicion[] expo1=new Exposicion[100];
}
public class ConsoleMenu {
private SalaExpo sala1;
void execute(){
sala1 = new SalaExpo();
}
}
Also you should poblate the sala1.expo1 array, like this (don't know if this is what you are intending but you should do this in order not to get a NullPointerException) :
void GuardarExpo(Exposicion[] arrExpoG,int posicion,Exposicion[] arrSala) {
/*
Bunch
of
code
*/
arrExpoG[posicion] = new Exposicion(inputNombre,inputDuracion);
arrSala[posicion]=arrExpoG[posicion];
}
Finally, you should use the variable "posicion" instead of "sala1.expo1.length" to pass as argument to the "imprimirExpo" method, since the array "sala1.expo1" has a length of 100, that means a lot of null elements since you are not poblating it all:
ImprimirExpo(sala1.expo1,posicion);
instead of:
ImprimirExpo(sala1.expo1,sala1.expo1.length);

Why does my compiler say that my return statement is missing?

I put in the return statement for both cases, if and else
but it's still says that the return statement is missing
What's wrong with my code?
public static getNext(){
ArrayList<String> copy = new ArrayList<String>();
Random dice = new Random();
int rolls;
for(int x=0; x<i.length; x++){
copy.add(i[x]);
}
if(copy.size() < 1){
return "NONE";
}
else{
rolls = dice.nextInt(copy.size());
return copy.get(rolls);
copy.remove(rolls);
}
}
else{
rolls = dice.nextInt(copy.size());
return copy.get(rolls);
copy.remove(rolls); <--- UNREACHABLE
}
Your compiler probably missed the return statement due to unreachable line of code after the return.
Also, you haven't declared the returned class. There should be:
public static <return type> methodName(<parameters>) {
<body>
}
Q: How could I remove the copy.get(rolls) after returning it? Is there a way?
A: Basically the question is about the concept of functions. Function is a piece of code which performs some logic and then, based on it returns something. Return statement is the last thing that happens in the function.
You can also have a block of code which doesn't return anything, but takes parameters. These are called procedures. Anyway, in Java we call both of them: functions and procedures methods.
You have some misunderstood in your code :
First when you make return the method should return something
Second you can't specify any kind of statement after your return
Third you have to store your return value that you want to remove it and return it in a separate variable
Your code should look like this :
public static String getNext() {
//-------------^^------------return type
ArrayList<String> copy = new ArrayList<String>();
Random dice = new Random();
int rolls;
for (int x = 0; x < i.length; x++) {
copy.add(i[x]);
}
if (copy.size() < 1) {
return "NONE";
} else {
rolls = dice.nextInt(copy.size());
String s = copy.get(rolls);//<<----------put the val you want in separate variable
copy.remove(rolls);//<<-----------remove your val
return s;//<<-----------return your val
}
}
Note
Like #BackSlash mention in comment, it is useless to remove your val from your list, because it will not used after you get out of your method, so if you are using this List in another place you have to declare it outside your method for example :
private static ArrayList<String> copy = new ArrayList<String>();
public static String getNext() {
//ArrayList<String> copy = new ArrayList<String>();//<<<-------------useless position
....

Java: I keep getting an error when trying to call the shooterExperiments method. I'm not sure what I'm doing wrong or exactly how to call a method

The problem I'm having is with the last line. I get an error at this section that says "cannot find symbol". This is not my entire program, only the first section.
public class Chap6Project
{
public double shooterExperiment(int dualsPerExperiment, String[] shooters, double[] accuracies, ProbabilitySupplier p)
{
shooters[0] = "aaron";
shooters[1] = "bob";
shooters[2] = "charlie";
String aaron = shooters[0];
String bob = shooters[1];
String charlie = shooters[2];
accuracies[0] = 0.33;
accuracies[1] = 0.5;
accuracies[2] = 1.0;
int duelCount = 0;
boolean aaronAlive = true;
boolean bobAlive = true;
boolean charlieAlive = true;
Chap6Project project = new Chap6Project();
ProbabilitySupplier random = new ProbabilitySupplier();
double rateOfSuccess = project.shooterExperiment(1000, shooters, accuracies, random);
while (duelCount < 1000)
{
int aaronKills = 0;
int aaronWin = 0;
double aaronAccuracy = random.getAsDouble();
if (aaronAccuracy == 0.33)
{
if (charlieAlive != true)
{
aaron.shooterExperiment(1000, bob, accuracies[1], random);
You declare the aaron variable like so:
String aaron = shooters[0];
and then try to use it like so:
aaron.shooterExperiment(1000, bob, accuracies[1], random);
and do this all within this method:
public double shooterExperiment(int dualsPerExperiment, String[] shooters,
double[] accuracies, ProbabilitySupplier p)
The aaron variable is a String and Strings have no shooterExperiment(...) method. Perhaps you meant to call this method on a different variable? Given what you've posted it's very hard to say. It looks like you're trying to call the shooterExperiment method from within itself, meaning making a recursive call, and doing so with incorrect method parameters and on the wrong object, a String object, none of which makes sense.
You'll want to clarify your problem and what your code is supposed to be doing greatly.
Other issues:
Your code suffers from the parallel array anti-pattern, a program structure that makes it very easy to create bugs. Instead create a class to encapsulate your shooter, including its name, health, accuracy, etc. and use a single collection of Shooter objects.

NullPointerException while indexing variable String parameters

I'm new to the idea of using an ellipsis. I'm almost certain my error is caused by improperly declaring or initializing "String[] authors", but I don't know how to do this an still have my setAuthors method work.
import java.util.*;
public class Book {
private String[] authors; //I'm guessing this line should end with "= new String..."
//but not sure how to w/o specifying an array dimension
private int authorsSize;
//Receives variable # of String parameters and indices them into String[] "authors"
public void setAuthors(String... authors) {
authorsSize = authors.length;
for(int i=0;i<authorsSize;i++)
this.authors[i] = authors[i];
}
//getAuthors method:
public String getAuthors(){
String s = "";
authorsSize = authors.length;
for(int i=0;i<authorsSize;i++)
s = s+authors[i] + ", ";
printAuthors = s;
return s;
}
The simplest approach would just be to clone the array:
public void setAuthors(String... authors){
this.authors = (String[]) authors.clone();
}
After all, you're overwriting the previous data anyway, and you can't know the size before the method call. You don't need the authorsSize variable at this point - you've got the authors array which knows its own length.
(If you were able to use immutable collections, you wouldn't even need to bother cloning, of course.)
EDIT: As noted in comments, this method will throw an exception if you pass in a null reference. You shouldn't automatically decide that this is a situation you should "handle" - it's entirely legitimate to document that the parameter must not be null. I would suggest documenting the behaviour around nullity either way.
Indeed, if you do this you might also want to initialize your instance field like this:
private String[] authors = new String[0];
That way you always know you'll have a non-null reference in that field, so you can use it with impunity. I would prefer this over having to check for null on every use.
you never initialized authors your array .
you need to initialize it before you use it .
String[] authors = new String[size];
//but not sure how to w/o specifying an array dimension
The best way is to use an List implementing classes as they are dynamic Arrays. i.e., you dont need to specify the size.
List<String> authors = new ArrayList<String>();
You have to currect your setAuthors method as described below
public void setAuthors(String... authors) {
if (authors != null && authors.length > 0) {
authorsSize = authors.length;
authors = new String[authorsSize];
for (int i = 0; i < authorsSize; i++)
this.authors[i] = authors[i];
}else{
this.authors = null;
}
}
Because the declaration of "private String[] authors" is before that of "public void setAuthors(String... authors)", you can not use the format like "String[] authors = new String[authorsSize]". This will make the size of authors always be 0.
The better way is to use the dynamic initialization:
List authors = new ArrayList();
Then use this.authors.add(authors[i]) to pass parameters.
you could also adjust your code like so:
import java.util.*;
public class Book{
private String[] authors;
private int authorsSize;
public void setAuthors(String... authors){
//check for null, you could also set this.authors = new String[] if you prefer.
if(authors == null){
this.authors = null;
}else{
authorsSize = authors.length;
//also add this line...
this.authors = new String[authorsSize];
for(int i=0;i<authorsSize;i++)
this.authors[i] = authors[i];
}
}
public String getAuthors(){
if(authors == null){
return ""; //could also return null here if you would prefer
}
StringBuilder s = new StringBuilder();
authorsSize = authors.length;
for(int i=0;i<authorsSize;i++){
if(i > 0)
s.append(",");
s.append(authors[i]);
}
//printAuthors = s;
return s.toString();
}
}

Problem using Array[] in Do-While Loop

Here is a method called placeShips() that I am calling via another method (which is called by a ButtonListener). But when all are called, I get a NullPointerException on the deepest nested line - System.out.println(ships[i]);. The array has been declared and initialized above this code in the constructor. It is set to be equal to a constant integer which equals 3. I've put a simple string in that printout and it works. But whenever the array gets involved, it becomes messy. What is going wrong?
NUM_SHIPS, NC_EMPTY, NC_SHIP, and all the labels/buttons have been made as well.
private Ships ships[];
*-----Constructor begins here-----*
Ships[] ships = new Ships[NUM_SHIPS];
*-----Constructor ends here-----*
ships[0] = new Ships("Aircraft Carrier", 5, false);
ships[1] = new Ships("Battleship", 4, false);
ships[2] = new Ships("Cruiser", 3, false);
public void placeShips()
{
statusLabel.setText("Press [Play]");
int shipsPlaced = 0;
do
{
int randomRow = (int)(Math.random()*ROWS);
int randomCol = (int)(Math.random()*COLS);
if (gameBoard[randomRow][randomCol] == NC_EMPTY)
{
gameBoard[randomRow][randomCol] = NC_SHIP;
shipsPlaced = shipsPlaced + 1;
for (int i = 0; i < NUM_SHIPS; i++)
{
System.out.println(ships[i]);
}
}
}while (shipsPlaced < NUM_SHIPS);
}
You have a class level array variable : private Ships ships[];, yet you define in your constructor Ships[] ships = new Ships[NUM_SHIPS];. Are you ever assigning to the class level variable? you could try
/* Class Level */
private Ships _ships[];
/* In constructor */
_ships = new Ships[NUM_SHIPS];
/* In PlaceShips() */
for (int i = 0; i < _ships.Length; i++)
{
if(_ships[i] != null)
{
System.out.println(_ships[i].toString());
}
}
If that doesn't work then debug the code to find which object is actually throwing the exception
It looks like your constructor is only initializing a local variable named ships. You say you have:
-----Constructor begins here-----*
Ships[] ships = new Ships[NUM_SHIPS];
*-----Constructor ends here-----*`
But it seems like you really want
ships = new Ships[NUM_SHIPS];

Categories

Resources