Can't append char to a StringBuffer 2-dimensional array - java

Does anybody know why i can't append a char to this StringBuffer array (in my example below) and can somebody please show me how i needs to be done?
public class test {
public static void main(String args[]){
StringBuffer[][] templates = new StringBuffer[3][3];
templates[0][0].append('h');
}
}
My output to this code is:
output: Exception in thread "main" java.lang.NullPointerException
at test.main(test.java:6)
It would help me so much so if you know any solution, please respond to this

Below statement will just declare an array but will not initalize its elements :
StringBuffer[][] templates = new StringBuffer[3][3];
You need to initialize your array elements before trying to append the contents to them. Not doing so will result in NullPointerException
Add this initialization
templates[0][0] = new StringBuffer();
and then append
templates[0][0].append('h');

You need to initialize the buffers before you append something
templates[0][0] = new StringBuffer();

Others correctly pointed out the correct answer, but what happens when you try to do something like templates[1][2].append('h');?
What you really need is something like this:
public class Test { //<---Classes should be capitalized.
public static final int ARRAY_SIZE = 3; //Constants are your friend.
//Have a method for init of the double array
public static StringBuffer[][] initArray() {
StringBuffer[][] array = new StringBuffer[ARRAY_SIZE][ARRAY_SIZE];
for(int i = 0;i<ARRAY_SIZE;i++) {
for(int j=0;j<ARRAY_SIZE;j++) array[i][j] = new StringBuffer();
}
return array;
}
public static void main(String args[]){
StringBuffer[][] templates = initArray();
templates[0][0].append('h');
//You are now free to conquer the world with your StringBuffer Matrix.
}
}
Using the constants are important, as is is reasonable to expect your matrix size to change. By using constants, you can change it in only one location rather then scattered throughout your program.

Related

Eclipse JAVA String reverse - reversing 1 word which is pre-declared [duplicate]

This question already has answers here:
Reverse a string in Java
(36 answers)
Closed 5 years ago.
Like to know how to reverse a string value (1 word) which is pre-declared in the program. I mean not using user input or scanner.
Like to reverse a word "TRAIN" which is pre-declared in the program.
Have tried the below program but no results and no error also.
// QUERY PROGRAM NOT RUNNING - NO RESULT, NO ERROR.
// STRING REVERSE PROGRAM USING ARRAY
package abnpackage;
class Play {
void REVERSE (){
String [] INPUT_WORD = {"T","R","A","I","N"};
int Q;
for(Q=INPUT_WORD.length-1; Q>=0; Q=Q--);
System.out.print ("REVERSE VALUE" + INPUT_WORD[Q]);
}
public static void main(String[]args){
Play PL = new Play();
PL.REVERSE();
}
}
Problem in Q=Q-- and ; symbol after for cylce. Try this:
class Play{
void REVERSE (){
String [] INPUT_WORD = {"T","R","A","I","N"};
int Q;
for(Q=INPUT_WORD.length-1; Q>=0; Q--) {
System.out.print(INPUT_WORD[Q]);
}
}
public static void main(String[]args){
Play PL = new Play();
PL.REVERSE();
}
}
I'd like to offer a few suggestions.
Indent your code. It not only makes it easier for you to follow, but makes it easier for others to read your code.
Naming conventions. Use Title case for classes, camelCase for both variables and methods, and UPPER_CASE for constants.
Strings and characters. A String can be decomposed into an array of characters with the built-in method, String.toCharArray(). A character array is mutable, so is often used as an intermediate structure when converting a String from one state to another for tasks like ciphers or interview problems.
Encapsulation. If you can make your methods use only what is submitted to them through their method signature, and only output their return value, it's usually best. Prefer passing values over referencing constants in your utility methods to make them easier to follow.
package abnpackage;
class Play {
private static final String INPUT_WORD = "TRAIN";
private String reverse(String word) {
char[] letters=word.toCharArray();
StringBuilder sb=new StringBuilder();
for (int q=letters.length-1; q>=0; q--) {
sb.append(letters[q]);
}
return sb.toString();
}
public static void main(String[]args) {
Play play = new Play();
System.out.println("REVERSE VALUE: " + play.reverse(INPUT_WORD));
}
}
class Play {
void REVERSE() {
String[] INPUT_WORD = {"T", "R", "A", "I", "N"};
String[] OUTPUT_WORD =new String[INPUT_WORD.length];
int length = INPUT_WORD.length;
int i = 0;
while(--length>=0){
OUTPUT_WORD[i++] = INPUT_WORD[length];
}
System.out.println(Arrays.toString(OUTPUT_WORD));
}
public static void main(String[] args) {
Play PL = new Play();
PL.REVERSE();
}
}
Your code is entering an endless loop because of the assignment "Q=Q--"
for(Q=INPUT_WORD.length-1; Q>=0; Q=Q--);
It should instead be
Q--
without a semicolon at the end.
If the code runs successfully, it will print the words "REVERSE VALUE" repeatedly prior to printing each character in reverse.
System.out.print ("REVERSE VALUE" + INPUT_WORD[Q]);
So you will want to keep the text in reverse prior to printing the whole statement at the end of the execution of the for loop.
What is the reason to use array of String instead of just String? Since it's not mentioned as a requirement, I'm suggesting the following as an alternative solution:
public class Play {
static void reverse(){
String inputWord = "TRAIN";
char[] toStrArray = inputWord.toCharArray();
char[] revisedInput = new char[inputWord.length()];
int i = 0;
for(int q=toStrArray.length-1; q>=0; q--){
revisedInput[i]=toStrArray[q];
i++;
}
System.out.print ("REVERSE VALUE: " + new String(revisedInput));
}
public static void main(String[]args){
//Play PL = new Play();
//PL.REVERSE();
reverse();
}
}
Note: You can declare the method reverse as a static method. By doing this you don't have to create an object before calling it. Hope this helps.

Null Pointer Exception / Arrays

I get a NPE in the 2 lines I commented "NPE HERE"
import javax.swing.*;
import java.awt.*;
public class Project1{
static TextArea preSort, postSort;
static String[] Array = new String[20];
public static void main(String[] args) {
Project1GUI myFrame = new Project1GUI("Project1GUI");
readStringFromFile("filename.txt");
enterFirst(Array); // NPE HERE
selectionSort(Array);
enterSecond(Array);
}
public static void enterFirst (String[] name){ // NPE HERE
for(int i=0;i<name.length&&name[i]!=null;i++)
preSort.append(name[i]+" ");
}
public static void enterSecond (String[] name){
for(int i=0;i<name.length&&name[i]!=null;i++)
postSort.append(name[i]+" ");
}
public static void selectionSort (String[] name){
for(int i=0; i<name.length-1&&name[i]!=null;i++){
int indexLowest=i;
for (int j=i+1; j<name.length&&name[j]!=null;j++)
if(name[j]<name[indexLowest])
indexLowest=j;
if(name[indexLowest]!=name[i]){
String temp = name[indexLowest];
name[indexLowest]=name[i];
name[i]=temp;
}//if
}//for
}//method selectionSort
public static boolean isOkay (String name){
char[] chars = name.toCharArray();
for(int i=0; i<chars.length; i++){
if(!Character.isLetter(chars[i])){
return false;
}
}
return true;
} //isOkay
public static void readStringFromFile(String fileName){
TextFileInput inFile = new TextFileInput(fileName);
String line;
line = inFile.readLine();
int index = 0;
while (line!=null) {
if(isOkay(line))Array[index++]=line;
else System.out.println(line);
line = inFile.readLine();
}//while
inFile.close();
}
} //Project1
I have 2 other classes in my directory, TextFileInput and my GUI class (do you guys need to see the code there too?).
I probably have more mistakes in my code, not sure as I'm still not very familiar with Java and am trying my best to learn. Any other advice will be appreciated.
Anyways, what is causing the NPE? From my understanding, my string array has null values that cause a NPE when I try to access the array with name[i].
I've tried filling up the rest of my array with dummies (strings with value of "antinull") but that didn't solve anything and would clearly not be an elegant solution even if it was one.
I just need to have a project1 class and a GUI class. The objective is to take in a file with strings, check if a string is all letters, and send the actual words to a text area in the GUI. Then sort by size and send the ordered version to the other text area. The strings that aren't words are sent to be output to the console. Project1 should have a constructor which takes one string parameter.
When you call preSort.append(...), you're calling a method from a variable (preSort), which is not initialized and thus null, this causes a NullPointerException. If you initialize preSort in your main method for instance, things will work better.
You should also look into indenting your code properly and use proper Java naming standards. Variables should be camelCased, not starting with a capital letter.
I don't think you are getting a Null Pointer Error on calling enterFirst(Array). The loop shouldn't even execute since the first value of Array is a null. But you might get a Null Pointer Error because preSort variable doesn't refer to any object.
Try:
static TextArea preSort = new TextArea(5, 20); and
static TextArea postSort = new TextArea(5, 20);

How to use a for loop to set String variable mixed with numbers to ""?

I have inherited a Java program which I need to change. In one part of the code, I see I have created over 1000 String variables such as:
String field01
String field02
...
String field1000
I want to make a for loop to set all of the mentioned variables to "", but I am having issues with building a correct format for the for loop.
How do I create field+(i) in the for loop to set field01 to "" and the rest?
A for loop... Well, you could make this an array, but there's not really any way to make this into a for loop without an array.
Here's an example with one:
String[] test = new String[1000];
for (int number; numer < 1000; number++){
test[number] = "";
}
You have to use Reflection for doing the same.
class Test {
String field1
String field2
...
String field1000
}
public class FieldTest {
public static void main(String args[]) {
Test t = new Test();
Class cls = t.getClass();
for(int i=0 ; i<=1000; i++){
Field f1 = cls.getField("field"+i);
f1.set(t, "");
}
}
}
You can't really do this in Java. An alternative is to make a String array where the index of the array is the number of the variable that you want. So field01 would be stored in your string array at index 1.
First, create an array. Second, use Arrays.fill:
String[] fields = new String[1000];
Arrays.fill(fields, "");
Later you can access or modify individual variables by indices like fields[index].
Creating 1000 variables with similar names is not how people program in Java.
I know it is not the exact answer, but may help you.or you will need to use reflection.
Map<String, String> container = new HashMap<String, String>();
for (int i = 0; i <1000; i++) {
container.put("field"+ i, "\"\" ");
}

How come the array of objects I'm creating is a set of nulls?

So I'm creating a class called dicegame. Here's the constructor.
public class dicegame {
private static int a, b, winner;
public dicegame()
{
a = 0;
b = 0;
winner = 2;
}
And now in the main, I'm creating an array of this object (I called it spaghetti for fun).
public static void main(String[] args)
{
dicegame[] spaghetti = new dicegame[10];
spaghetti[1].roll();
}
But when I try to do anything to an element in the array, I'm getting the NullPointerException. When I tried to print one of the elements, I got a null.
You created an array, but you have to assign something (e.g. new dicegame()) to each element of the array.
My Java is slightly rusty, but this should be close:
for (int i=0; i<10; i++)
{
spaghetti[i] = new dicegame();
}
new dicegame[10]
just creates an array with 10 empty elements. You still have to put a dicegame in each element:
spaghetti[0] = new dicegame();
spaghetti[1] = new dicegame();
spaghetti[2] = new dicegame();
...
You need spaghetti[1]=new dicegame() before you call roll() on it.
Right now you are allocating an array,but don't. Place any objects in this array, so by default java makes them null.
1.you have just declared the array variable but not created the object yet. try this
2.you should start index with zero not with one.
dicegame[] spaghetti = new dicegame[10]; // created array variable of dicegame
for (int i = 0; i < spaghetti.length; i++) {
spaghetti[i] = new dicegame(); // creating object an assgning to element of spaghetti
spaghetti[i].roll(); // calling roll method.
}
Firstly,you should create object for every spaghetti input of yours.
You can start with whatever value you want. Just be sure that the size of array is matched accordingly so that you won't get ArrayIndexOutOfBounds Exception.
So,if you wanted to start with 1 and have 10 objects of the class dicegame,you will have to assign the size of the array as 11(since it starts from zero).
your main function should be like :
public static void main(String[] args)
{
dicegame[] spaghetti = new dicegame[11];
//the below two lines create object for every spaghetti item
for(int i=1;i<=11;i++)
spaghetti[i]=new dicegame();
//and now if you want to call the function roll for the first element,just call it
spaghetti[1].roll;
}

Java bug or feature?

Ok, here is the code and then the discussion follows:
public class FlatArrayList {
private static ArrayList<TestWrapperObject> probModel = new ArrayList<TestWrapperObject>();
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] currentRow = new int[10];
int counter = 0;
while (true) {
for (int i = 0; i < 10; i++) {
currentRow[i] = probModel.size();
}
TestWrapperObject currentWO = new TestWrapperObject(currentRow);
probModel.add(counter, currentWO);
TestWrapperObject testWO = probModel.get(counter);
// System.out.println(testWO);
counter++;
if (probModel.size() == 10) break;
}
// Output the whole ArrayList
for (TestWrapperObject wo:probModel) {
int [] currentTestRow = wo.getCurrentRow();
}
}
}
public class TestWrapperObject {
private int [] currentRow;
public void setCurrentRow(int [] currentRow) {
this.currentRow = currentRow;
}
public int [] getCurrentRow() {
return this.currentRow;
}
public TestWrapperObject(int [] currentRow) {
this.currentRow = currentRow;
}
}
What is the above code supposed to do? What I am trying to do is load an array as a member of some wrapper object (TestWrapperObject in our case). When I get out of the loop,
the probModel ArrayList has the number of elements it is supposed to have but all have the same value of the last element (an array of size 10 with each item equal to 9). This is not the case inside the loop. If you perform the same "experiment" with a primitive int value everything works fine. Am I missing something myself regarding arrays as object members? Or did I just encounter a Java bug? I am using Java 6.
You are only creating one instance of the currentRow array. Move that inside the row loop and it should behave more like you expect.
Specifically, the assignment in setCurrentRow does not create a copy of the object, but only assigns the reference. So each copy of your wrapper object will hold a reference to the same int[] array. Changing the values in that array will make the values appear to change for all other wrapper objects that hold a reference to the same instance of the array.
i don' t want to sound condescending, but always try to remember tip #26 from the excellent pragmatic programmer book
select isn't broken
it is very rare to find a java bug. keeping this in mind often helps me to look over my code again, turn it around, and shake out the loose bits until i finally discover where i was wrong. of course asking for help early enough is very encouraged, too :)

Categories

Resources