toString Not Following Correct Format - java

I am having trouble when I call my toString method and my code isn't following the correct format like it should, this is how I've been trying to call it.
public static void loadQueue(Queue<String> queue, String str) {
String elementArray[] = str.split(",");
for(int i = 0; i < elementArray.length; i++){
queue.push(elementArray[i]);
queue.toString();
}
}
Here is the toString that I want to format it to:
#Override
public String toString() {
String str = "[ ";
if ( !isEmpty() ) {
for (int i = 0; i < queue.length - 1; i++){
str += queue[i] + ", ";
}
str += queue[queue.length - 1] + " ";
}
str += "]";
return str;
Is there a better way to be calling this so that it prints out the correct out put?
Correct format should be [ a, b, c, d ] but all I'm getting is [ abcd ].
Edit, added toString method

If you're trying to use the values between commas in the str as the values to push onto the queue then you don't need to call toString().
Does this work for you?
public static void loadQueue(Queue<String> queue, String str) {
if (null == queue) throw new IllegalArgumentException("Expected non-null queue");
if (null == str) throw new IllegalArgumentException("Expected non-null str");
String elementArray[] = str.split(",");
for(int i = 0; i < elementArray.length; i++){
queue.push(elementArray[i]);
}
}

I can't tell which class your toString override is on, but it wouldn't be on string or queue.
Queue.toString will probably not be what you want. Is there some reason you want to override toString rather than just have a method by another name?
Technique #1
Put all the methods in your existing class
public String queueToString(Queue<String> queue) {
String str = "[ ";
if ( !isEmpty() ) {
for (int i = 0; i < queue.length - 1; i++){
str += queue[i] + ", ";
}
str += queue[queue.length - 1] + " ";
}
str += "]";
return str;
}
...
public static void loadQueue(Queue<String> queue, String str) {
String elementArray[] = str.split(",");
for(int i = 0; i < elementArray.length; i++){
queue.push(elementArray[i]);
}
System.out.println( queueToString(queue) );
}
Technique #2
Create a custom class for your queue and modify the behavior.
public class MyStringQueue extends Queue<String>
{
#Override
/* override the toString method here */
}
...
/* in your class, create an use a MyStringQueue instead of Queue<String> */
public static void loadQueue(MyStringQueue queue, String str) {
String elementArray[] = str.split(",");
for(int i = 0; i < elementArray.length; i++){
queue.push(elementArray[i]);
}
System.out.println( queue.toString() );
}

Related

Why does the following code extract characters instead of blanks?

I saw a code segment as follows:
public class Practice
{
public static void main( String[] args )
{
String i = new String("I love you");
System.out.println(doSomething(i));
}
public static String doSomething( String s )
{
final String BLANK = " ";
String str = "";
String temp;
for ( int i = 0; i < s.length(); i++)
{
temp = s.substring(i, i + 1);
if (!(temp.equals(BLANK)))
{
str += temp;
}
}
return str;
}
}
I am very confused by the code here. I believe that whenever the for loop runs, one of the characters of the String will be extracted out. For example, when i = 0, temp should be "I", and i = 1, " ", i = 2, "l", etc. And when temp = " ", the if statement states that the blank will be adding to the String str. So whenever for-loop is run, the temp will change accordingly and hence cannot store the value unless its value is " ".
The output is Iloveyou.
Here is the problem:
if (!(temp.equals(BLANK)))
{
str += temp;
}
IF temp IS NOT (the ! means NOT) BLANK,
then do: str += temp;

how to print all of arrays with for loop in java

I have array in String. I want to use for loop to print all of the objects. I was under the impression this would be done by making for loop then returning the String. I am not sure what I need to change to accomplish this.
Following is my effort:
public class SolarSystem {
private Planet[] planets;
private int position = 0;
public SolarSystem(int size) {
planets = new Planet[size];
}
public void add(Planet planet) {
planets[position] = planet;
position++;
}
public String toString(){
for(int i = 0; i < planets.length; i++){
}
return toString();
}
}
ADDED PLANET CLASS
public class Planet {
String name;
int moons;
public Planet(String name, int moons)
{
this.moons = moons;
this.name = name;
}
public String toString() {
return "The Planet " + name + " Has " + moons + " Moon(s) \r\n ";
}
}
You can try using a StringBuilder:
public String toString() {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < planets.length; i++){
sb.append(planets[i].getName()); // getName() or toString()
sb.append("\n");
}
return sb.toString();
}
Override toString() method in Planet class, and use below code :
public String toString(){
String result = "";
for(int i = 0; i < planets.length; i++){
result += planets[i].toString(); // append comma if you need to separate it,
// and most of all handle nulls
}
return result;
}
public String toString() {
StringBuilder mainresult = new StringBuilder();
for(int i = 0; i < planets.length; i++){
StringBuilder result = new StringBuilder();
String newLine = System.getProperty("line.separator");
result.append( planets[i].getClass().getName() );
result.append( " Object {" );
result.append(newLine);
//determine fields declared in this class only (no fields of superclass)
Field[] fields = this.getClass().getDeclaredFields();
//print field names paired with their values
for ( Field field : fields ) {
result.append(" ");
try {
result.append( field.getName() );
result.append(": ");
//requires access to private field:
result.append( field.get(this) );
} catch ( IllegalAccessException ex ) {
System.out.println(ex);
}
result.append(newLine);
}
result.append("}");
//if it is the first one then no new line added
if(i==0)
{
mainresult.append(result.toString());
continue;
}
mainresult.append(newLine);
mainresult.append(result.toString());
}
return mainresult.toString();
}
Override toString() Method
#Override
public String toString() {
return "SolarSystem [te=" + Arrays.toString(te) + ", position=" + position + "]";
}
If you have this overidden method in your planet class
public String toString(){
StringBuilder result = new StringBuilder();
String NEW_LINE = System.getProperty("line.separator");
result.append(" planetProperty1: ").append (planetProperty1).append(NEW_LINE);
result.append(" planetProperty2: ").append (planetProperty2).append(NEW_LINE);
return result.toString();
}
then from the calling class you can iterate over the collection calling
System.out.println (planets[i].toString());

using a method to print an array in java

From my current code how would i print the array{10,20,30,40,50,60,70,88,99,100} using a method display and calling it using System.out.println(myobject.display()) in my main.
public TestA(){
index = -1;
iA = new int[]{10,20,30,40,50,60,70,88,99,100};
}
public static String display(){
String str = "";
for(int i = 0; i < 10; i++){
str= str+ " ";
}//for
return str;
}//display
My current method display does not display anything.
public TestA()
{
index = -1;
iA = new int[]{10,20,30,40,50,60,70,88,99,100};
System.out.println(display(iA));
}
public static String display(int[] myData)
{
String str = "";
for(int i = 0; i < myData.length; i++){
str += myData[i]+ " ";
}
return str;
}
You need to call the method and print the result. Also use the array iA in your method.
System.out.println(display());
Your for loop is just adding an empty string to an empty string 10 times. You are never adding in the text from your array based on the index i. During your loop, you should be adding the space as well as the value at the current array position.
Your method display() is indeed doing something. It is returning 10 spaces, which are being printed out in your main method. You need to actually use the array at some point. Try something like:
public TestA(){
index = -1;
iA = new int[]{10,20,30,40,50,60,70,88,99,100};
}
public static String display(int[] iA){
String str = "";
for(int i = 0; i < 10; i++){
str= str + Integer.toString(iA[i]) + " ";
}//for
return str;
}//display

Return an array of Pairs which have the same length as the input array of Strings. (Java)

I want to create a class that would return an array of pairs that have the same length as the input array of strings.
In addition, the pair should have the first letter of the string and length of the string.
for example;
create(new String[] {"clue", "yay", "neon", "halala"})
should return the array of Pairs
{[’c’,4],[’y’,3],[’n’,4],['h',6]}
So, my input and output would both be arrays. But the output has to be in the form of a pair. Here's what i tried:
import java.util.Arrays;
public class Couple {
public static Couple[] create(String[] source){
for (int i = 0; i < source.length; i++) {
System.out.print("["+","+source.length+"]") ;
}
return null;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(create(new String[] {"clue", "yay", "neon", "halala"})));
}
}
as it's obvious there are a few errors+ i dont want it to return null. But just for the sake of testing this code, i had to do it.
Any ideas?
public class Couple {
private char firstChar;
private int length;
public Couple(char firstChar, int length) {
this.length = length;
this.firstChar = firstChar;
}
public static Couple[] create(String[] source) {
Couple[] couples = new Couple[source.length]; // create the array to hold the return pairs
for (int i = 0; i < source.length; i++) {
String entry = source[i];
if (entry != null) {
couples[i] = new Couple(entry.charAt(0), entry.length());
} else {
// What do you want to do if there's a null value?
// Until you answer this we'll just leave the corresponding Couple null aswell
}
}
return couples;
}
#Override
public String toString() {
return "Couple{" +
"firstChar=" + firstChar +
", length=" + length +
'}';
}
}
You are on the right track:
Rather than returning null, you should create an array of pairs, and populate it in the loop. You know the length of the result, because you have the length of the source
To look at an individual word, use source[i]
To chop off the initial letter of the word use source[i].charAt(0)
To get the length of the word use source[i].length()
The Couple class needs two data members - a char and an int; they should be set in the constructor
The data members should have getters - public char getChar() and public int getLength() returning their respective members
Printing should be done in the main, in a loop that walks the returned array of pairs
You should be able to complete the rest.
The hint you probably need it this:
Couple[] result = new Couple[source.length];
and code a loop to create the Couple instances and put them into the result array.
Use this code:
import java.util.Arrays;
public class Couple {
public static String[] create(String[] source) {
String[] temp = new String[source.length];
for (int i = 0; i < source.length; i++) {
if (source[i].length() > 0) {
String newString = "[" + source[i].charAt(0) + ","
+ source.length + "]";
//System.out.print(newString);
temp[i] = newString;
} else {
String newString = "[" + " " + "," + 0 + "]";
//System.out.print(newString);
temp[i] = newString;
}
}
return temp;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(create(new String[] { "clue", "yay",
"neon", "halala"})));
}
}

Java: Printing / returning array from a class

I created a class for a bingo game. I get an error saying "'class' expected". How could I return the values in the array to the main starter?
Any other comments would also be helpful.
Thank you.
import java.util.Random;
public class Card
{
Random generator = new Random();
private final int BOARDMAX = 4;
private final int NUMMAX = 59;
int i, j, m, n;
private int [][] ArrayBoard = new int[BOARDMAX][BOARDMAX];
String [][] StrArrayBoard = new String [BOARDMAX][BOARDMAX];
public void RandomNumGenerator()
{
for (i = 0; i<BOARDMAX; i++)
{
for (j = 0; j<BOARDMAX; j++)
{
ArrayBoard[i][j] = generator.nextInt (NUMMAX+1);
}
}
}
public String ShowBoard()
{
for (i = 0; i<BOARDMAX; i++)
{
for (j = 0; j<BOARDMAX; j++)
{
m=i;
n=j;
if (j != BOARDMAX)
StrArrayBoard[m][n] = ArrayBoard[m][n] + " ";
else
StrArrayBoard[m][n] = ArrayBoard[m][n] + " \n";
}
}
return StrArrayBoard[i][j];
}
public void ShowMark()
{
for (i = 0; i<BOARDMAX; i++)
{
for (j = 0; j<BOARDMAX; j++)
{
if (CardCheck [i][j] == 1)
StrArrayBoard[i][j] = ArrayBoard[i][j] + "* ";
else
StrArrayBoard[i][j] = ArrayBoard[i][j] + " ";
if (j == BOARDMAX)
ArrayBoard[i][j] = ArrayBoard[i][j] + "\n";
}
}
}
public String toString()
{
return ArrayBoard[][];
}
}
With toString() you need to return a String object but actually you try to return an int[][]. The same is true for ShowBoard, you try to return an array of Stringarrays which is not a compatible type.
Here's the fix:
public String ShowBoard() {
// your code to populate StrArrayBoard
StringBuilder boardBuilder = new StringBuilder();
for (String[] row:StrArrayBoard)
for (String cell:row)
sb.append(cell);
return boardBuilder.toString();
}
public String toString() {
return ShowBoard();
}
I suggest to refactor the code and rename methods and fields:
ShowBoard() --> getBoardAsString()
ArrayBoard --> arrayBoard
StrArrayBoard --> strArrayBoard
And there's no need to declare StrArrayBoard as a field (class member) just because you only need it inside the ShowBoard method. Declare it there as a local variable.
Adding to the bugs others have pointed:
You have if (CardCheck [i][j] == 1), but the array CardCheck is not declared anywhere.
You have ArrayBoard[i][j] = ArrayBoard[i][j] + "\n"; but ArrayBoard is an int array, you cannot add a string "\n" to it's member.
The compiler will complain because of the error on your code:
public String toString()
{
return ArrayBoard[][];
}
It can't convert int[][] (which is your ArrayBoard) to String. My suggestion is that you populate all values stored in StrArrayBoard in a StringBuffer and return the StringBuffer.toString() in the toString() method.
The toString() method requires a String.
Hope this helps.
public String toString()
{
return ArrayBoard[][];
}
This method expects to return a String but you are returning a 2D Integer array, what you need is a String. the toString() method returns a string representation of the object, so in this case, what you can do is to use a StringBuilder to build the string representation of the array and then, use the .toString() of the StringBuilder to return the string representing the 2D Array.
Also, as noted by Alois Cochard, you variable naming does not follow convention. Variable names in Java use a camel case notation.
I for one don't really understand your question but I've got a couple of comments.
The class variables i and j should be local variables in each method.
Your naming convention is nonstandard, seems like a more C# convention. Start variable and method names with a lower case.
CardCheck isn't defined anywhere. I presume it is meant to indicate if a number on a square has been checked, in which case it should be a boolean and not an int.
toString doesnt return a string. You can use Arrays.toString to help you.
Similarily, ShowBoard just returns one element of an array, you probably wanted to show the entire board there.
For your toString and ShowBoard methods you probably want to use a StringBuilder to build up the string representation.
StringBuilder builder = new StringBuilder();
for (int i=0; i<BOARDMAX; i++) {
for (int j=0; j<BOARDMAX; j++) {
builder.append(StrArrayBoard[i][j]);
}
builder.append('\n');
}
return builder.toString();
Here's a version of your class that compiles (and I changed some field names and modifiers to adhere to standard conventions). Try this:
public class Card{
private final Random generator = new Random();
private static final int BOARDMAX = 4;
private static final int NUMMAX = 59;
int i, j, m, n;
private final int[][] arrayBoard = new int[BOARDMAX][BOARDMAX];
private final String[][] strArrayBoard = new String[BOARDMAX][BOARDMAX];
// do something here please
private int[][] CardCheck;
public void RandomNumGenerator(){
for(i = 0; i < BOARDMAX; i++){
for(j = 0; j < BOARDMAX; j++){
arrayBoard[i][j] = generator.nextInt(NUMMAX + 1);
}
}
}
public String ShowBoard(){
for(i = 0; i < BOARDMAX; i++){
for(j = 0; j < BOARDMAX; j++){
m = i;
n = j;
if(j != BOARDMAX){
strArrayBoard[m][n] = arrayBoard[m][n] + " ";
} else{
strArrayBoard[m][n] = arrayBoard[m][n] + " \n";
}
}
}
return strArrayBoard[i][j];
}
public void ShowMark(){
for(i = 0; i < BOARDMAX; i++){
for(j = 0; j < BOARDMAX; j++){
if(CardCheck[i][j] == 1){
strArrayBoard[i][j] = arrayBoard[i][j] + "* ";
} else{
strArrayBoard[i][j] = arrayBoard[i][j] + " ";
}
if(j == BOARDMAX){
// this is probably what you mean:
strArrayBoard[i][j] = arrayBoard[i][j] + "\n";
}
}
}
}
#Override
public String toString(){
// this is probably what you mean:
return Arrays.deepToString(strArrayBoard);
}
}

Categories