toString() implementation for Array - arrays

Before I state my question, I would like to thank everyone who helped me on my previous question. Anywho, I am currently getting the memory offsets as result even when I place it to the to a toString method. I've read most of the questions regarding the toString method and have somewhat of a understanding, I just wanted to make sure if I'm implementing this correctly. If you feel that this is a redundant question, I understand. Thanks for the help in advance.
Ship class
import java.util.Scanner;
public class Ship{
int type;
public String [][] shipPiece = new String[11][11];
Scanner in = new Scanner(System.in);
//Coordinate xy = new Coordinate();
//private Coordinate[] bawdPiece = {new section()};
public Ship(){
}
public String[][] placeShip()
{
System.out.println();
for(int x = 1; x<10; x++)
{
for(int y = 1; y<10; y++)
{
shipPiece[x][y] = "0";
System.out.print("|" + shipPiece);
}
}
return shipPiece;
}
public String toString()
{
StringBuilder temp = new StringBuilder();
temp.append(shipPiece);
return temp.toString();
}

public String toString()
{
StringBuilder temp = new StringBuilder();
for(int x = 0; x < 10; x++)
{
for(int y = 0; y < 10; y++)
{
temp.append(String.valueOf(shipPiece[x][y]);
}
temp.append("\n");
}
return temp.toString();
}
Also another thing I would like to point out is your array initialization. You initialize it with 11 x 11 indices, but your loop is only adding 9 values to each row and column Loop starts at 1 and ends at 9. You may want to fix your initialization to 10 x 10 and make your loop start at 0.

If I understand the question correctly, you are trying to get the index of the shipPiece as a string?
If that's the case try String.ValueOf(index), you'll obviously have to do this twice as you have a 2-dimensional array.
Ex:
String s = String.ValueOf(xIndex) + "," + String.ValueOf(yIndex);

Related

Java method returning blank array

I'm new to java and having trouble basically passing an array through to a method in another class, using the values to compute a new array, and then passing that back again to print. The problem is that when it prints the array it always prints the empty string. When I step through in debug mode I can see that the values are getting passed in and the array gets generated, but then when it prints it is always empty. It seems like somehow to code is failing to return the correct array maybe. Here is my code
public static void main(String[] args) {
double[] rnoDivs;
double[] rnoEarnings;
Company rno = new Company();
rnoDivs = new double[] {355, 355, 315, 240, 190};
rno.yearlyDividendsGrowth(rnoDivs);
rnoEarnings = new double[] {0.019, 3.451, 5.210, 3.543, 2.960};
rno.yearlyEarningsGrowth(rnoEarnings);
This is passed through to my other class
public class Company {
double[] yearlyEarningsGrowth = {};
public double[] getYearlyEarningsGrowth(){return yearlyEarningsGrowth;}
public double[] yearlyEarningsGrowth(double[] yearlyEarnings){
double[] yearlyEarningsGrowth = new double[yearlyEarnings.length];
for (int x = 0; x <= yearlyEarnings.length; x++) {
if (x < yearlyEarnings.length - 1) {
yearlyEarningsGrowth[x] = (yearlyEarnings[x] / yearlyEarnings[x + 1]) * 100;
}
}
return yearlyEarningsGrowth;
}
}
And then I try to print this statment
Company[] companies = {rno};
for(int i=0; i < companies.length; i++) {
double[] array = companies[i].getYearlyEarningsGrowth();
System.out.println("Yearly earnings growth: " + Arrays.toString(array));
}
But then I just get the array "[]". Any help with this would be appreciated! I seem to be going in circles because everything looks correct.

How can I check for equality within a row, amongst all indexes?

I'm lost and don't know where to begin. I'm testing the following condition, L=W=H on Package1's method and I want to call it into the Class Runtime's main method.
I created an array of objects already. But after that, I don't know how to utilize it or even if I have to. Again I'm completely lost!...thanks for your help.
I feel as if Coding is a young man's world!, Damn you Marine Corps!
public class Package1
{
double length;
double width;
double height;
Package1(double a,double b, double c)
{
length=a;
width=b;
height=c;
}
public void isCube()
{
if(length==width && width==height)
System.out.println("The box is a cube.");
else
System.out.println("Box is not a cube. ");
}
public class Runtime{
public static void main(String[] args){
Package1[] boxes = new Package1[rows];
for(int j = 0; j < boxes.length; j++)
{
boxes[j] = new Package1(arr[j][0], arr[j][1], arr[j][2]);
}
}
}
Like this.
for(int j = 0; j < boxes.length; j++)
{
boxes[j] = new Package1(arr[j][0], arr[j][1], arr[j][2]);
boxes[j].isCube(); // this is the line that you need
}
Any element in an array can be accessed by passing the index of the item into the brackets. For instance boxes[0] is the first element in the array. boxes[ boxes.length - 1 ] is the last element in the array.

String to Character Array

I have a problem with my code below:
public class stringToChar {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
char[] sCharArr;
String[] odd = new String[n];
String[] even = new String[n];
for(int i = 0; i < n; i++) {
sCharArr = in.next().toCharArray();
for(int j = 0; j < sCharArr.length; j++) {
if(j % 2 == 0)
even[i] += sCharArr[j];
else
odd[i] += sCharArr[j];
}
}
for(int i = 0; i < n; i++) {
System.out.println(even[i] + " " + odd[i]);
}
}
}
My issue is on the output it has a Null in the result. Here is a sample scenario:
2
John
Cena
Answer should be:
Jh on
Cn ea
But my code answer is:
NullJh Nullon
NullCn Nullea
Your problem is that the new arrays are initialized with all null Strings. Then your code is not assigning values to all array elements, but just to some of them!
Finally you print your array, and surprise, those values that were null and that have not been changed - are still null (and when you print a null string ... it prints "null" [ yes, null, not Null; you got a little mistake there in your output example ]
You see, you iterate from 0 to the length of your two arrays. And if the number is even, you put a value in the even[i]; and if the value is odd, it goes to odd[i]. Lets take even - in that case, odd[i] simply stays null!
One way to fix that:
List<String> even = new ArrayList<>();
List<String> odd = new ArrayList<>();
And now, instead of setting a certain index in even/odd; you simply do:
even.add(some new value);
and to add those single characters:
even.add(new String(sCharArr));
Doing so, even and odd will (in the end) contain exactly the values that you added to each list; but no "residual" nulls. For the record: the way how you split up strings, to then pull them back into a String array isn't exactly the most simple/straight forward way to solve the problem.
But I leave "further" simplifications" as exercise to the user.

get position of 2D array of JLabels

First post here but long time reader, been searching through but cant find a post that exactly helps my problem.
I am trying to create 2D grid of JLabels with mouselisteners and retrieve the X / Y position of the clicked JLabel but cant find a way to do it. I have tried a few ways I found out on this site but nothing is working.
currently I have the following....
pcenter.setLayout(new GridLayout(game.getXSize(), game.getYSize()));
pcenter.setBorder(new EmptyBorder(8,8,8,8));
pcenter.setPreferredSize(new Dimension((game.getXSize() * 30), (game.getYSize() * 30)));
gamegrid = new JLabel[game.getXSize()][game.getYSize()];
for ( int i = 0; i < game.getXSize(); i++) {
for (int j = 0; j < game.getYSize(); j++) {
gamegrid[i][j] = new JLabel();
gamegrid[i][j].setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
gamegrid[i][j].addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
}
});
pcenter.add(gamegrid[i][j]);
}
}
'game' is an object that houses a 2D array of objects for which i want to pass in the same co-ordinates of the JLabel clicked. E.G clicking on gamegrid[2][5] will contact game.plots[2][5].
whenever i try and make a variable to store 2 and 5 it wants to make the method FINAL, and if I put the method inside the MouseAdapter() it wants to make 'i' or 'j' FINAL.
please help :) thanks in advance.
Just figured it out! I'll post here just encase someone else would like to know.
I created 3 other variables in the class:
private static Object source;
private static int currentX, currentY;
then the current MouseListener, where it is now, I added the following:
for ( int i = 0; i < game.getXSize(); i++) {
for (int j = 0; j < game.getYSize(); j++) {
gamegrid[i][j] = new JLabel();
gamegrid[i][j].setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
gamegrid[i][j].addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
source = e.getSource(); //added this to get the mouseevent object.
XYsource(); // this is a method to turn the object source
into X and Y coords.
}
});
pcenter.add(gamegrid[i][j]);
}
}
and finally the following method to turn the Object source into the X and Y co-ordinates
public static void XYsource() {
int maxX = game.getXSize();
int maxY = game.getYSize();
for(int i = 0; i < maxX; i++) {
for(int j = 0; j < maxY; j++){
if (gamegrid[i][j] == source) {
currentX = i;
currentY = j;
}
}
}
updateXY(); // this is just a method to set text on the screen showing
the X and Y coordinates to test the MouseListener
}

Calculate the number of different digits in the integer

I'm practicing learning Java and I found this exercise online to input a long integer (ex 2827) and then calculate how many different digits there is in the integer (2,8 and 7) = 3 in this case.
I'm considering using a for loop and then with subString, comparing if the number equals each others and they (tutorial) suggest that I should use an array "used" to register which numbers appear, nonetheless
This is what I've got so far:
import java.util.Scanner;
public class UniqueInteger {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean[] used = new boolean[10];
int uniqueNbr = 0;
System.out.print("Input an integer: ");
String nbrString = String.valueOf(scan.nextLong());
for (int i = 0; i < nbrString.length(); i++) {
String bigI = String.valueOf(i);
if(nbrString.substring(i,(i+1)).equals(bigI)){
uniqueNbr++;
}
}
System.out.println("Amount of unique digits: " + uniqueNbr);
}
}
My problem is now that this code does not work, and I'm not sure I'm taking the right approach here. I've also not found a reason or purpose to include the boolean array "used".
What's wrong with my code?
How do I in a smart way use the boolean array and make my code more efficient?
You need to check if the current number in the string has been used (using your boolean array). If it hasn't been used, set used[num] to true and increment uniqueNbr.
import java.util.Scanner;
public class UniqueInteger {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean[] used = new boolean[10];
int uniqueNbr = 0;
System.out.print("Input an integer: ");
String nbrString = String.valueOf(scan.nextLong());
for (int i = 0; i < nbrString.length(); i++) {
int num = Character.getNumericValue(nbrString.charAt(i));
if(!used[num]) {
uniqueNbr++;
used[num] = true;
}
}
System.out.println("Amount of unique digits: " + uniqueNbr);
}
}

Resources