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);
Related
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.
I've done some looking around on here for a solution, but I can't find one. I tried these ones and many others, and I run into the same issue.
I am trying to make a simple text game, and I run into the issue where I have a main class, and a class called "gameboard" that I have as an array defined like this:
static GameBoard[] gameboard = new GameBoard[9];
Now, this works fine until I try to change the characteristics of a single one of these array objects. I will do:
gameboard[input].setState(2);
and the specific instance of gameboard that should change will not be the only one: all of them change when I do this. It's weird. Only gameboard[**input**] should change, not all 9 of the gameboard instances. EVERY variable and method I have is "static", but because of the main method (public static void main...), everything seems to have to be static. How do I get rid of all this static?
GameBoard Class
package com.name.tictactoe;
public class GameBoard {
char[] States = {'N','X','O'};
char state;
public void setState(int s){
state = States[s];
}
public char getState(){
return state;
}
}
Main class (called Game)
package com.name.tictactoe;
import java.util.Scanner;
public class Game {
static boolean turn, win;
static GameBoard[] gameboard;
static Scanner kb = new Scanner(System.in);
static int input;
public static void main(String[] args){
gameboard = new GameBoard[9];
reset();
displayStates();
askTurn();
displayStates();
askTurn();
}
public static void askTurn() {
System.out.println();
System.out.println();
System.out.println("Where do you want to go? Use the numbers shown, where the first segment is the top and the last is the bottom - left to right.");
input = kb.nextInt();
if(input > 8){
System.out.println("Input out of bounds. Game over by default.");
try {
Thread.sleep(1000000000);} catch (InterruptedException e) {e.printStackTrace();}
}
gameboard[input].setState(2);
}
public static void reset(){
for(int i = 0; i < 9; i++){
gameboard[i].setState(0);
}
}
public static void displayStates(){
for(int i = 0; i < 9; i++){
System.out.print(gameboard[i].getState() + " ");
if(i ==2 || i ==5){
System.out.print(" II ");
}
}
System.out.println();
for(int i = 0; i < 9; i++){
System.out.print(i + " ");
if(i ==2 || i ==5){
System.out.print(" II ");
}
}
System.out.println();
}
}
UPDATE: The current answers don't work. Although Eclipse doesn't realize this, making GameBoard non-static causes null pointer exceptions when any method in it is referenced.
A static variable belongs to the class, not the object, so of course all of your GameBoards are being affected!
Just because you're in a static method doesn't mean you can't manipulate instance variables. First, make everything in your GameBoard class non-static (unless you really do need some of the values shared across all instances). This includes your instance variables and your getter/setter methods.
If your program works exclusively from the main method, then keep your GameBoard[] object static. Then, when you make that method call:
gameboard[input].setState(2);
This will change only the state of the GameBoard at index input.
Edit:
To instantiate your GameBoard[] with basic GameBoard objects inside of it, you can do this at the beginning of your main method:
for(int x=0; x<gameboard.length; x++) {
gameboard[x] = new GameBoard(); //Assuming you want to use the default constructor
}
The other objects in your array should not change. Can you add some more code for more context?
As far as I can understand you, you are doing something like:
public class Main {
public static String[] strings = new String[2];
public static void main(String[] args) {
strings[0] = "test";
System.out.println(strings[1]);
}
}
In my example output is "null" as expected.
How do I get rid of all this static?
Just create instances of your objects in the main function.
GameBoard[] gameboard = new GameBoard[9];
For what you describe to happen all the elements of the gameboard array must be set to the same object (nothing to do with the array being static), check your code where you populate the gameBoard array with new instances of the GameBoard class for a bug that could cause the same instance to be written to all elements (or post that code here so people can see the problem).
Let me explain further. I have a String function (called stringReversal) that returns a reversed string, it has no errors in the function. But, when I try to print using System.out.println() from the main function, it gives me the error "Can not make a static reference to the non static method stringReversal (string s) from the type StringReverse".
I tried giving my stringReversal a static modifier, but after doing so, it gave me run time errors.
Here's what my code looks like:
public class StringReverse {
public String stringReversal(String s){
if(s == null){
return null;
}
else if(s.length()% 2 == 0){
int size = s.length();
for(int i =0; i<s.length(); i++){
s.replace(s.charAt(i), s.charAt(size));
size--;
if(i == (s.length()/2) || size==0)
break;
}
}
else{
for(int i =0; i<s.length(); i++){
int size = s.length();
s.replace(s.charAt(i), s.charAt(size));
size--;
if(i == ((s.length()/2) +1) || size==0 )
break;
}
}
return s;
}
public static void main(String[] args) {
String str = "Hello";
String rev = stringReversal(str);
System.out.println();
}
}
You have to instantiate your class to call object members, or you need to make your function static, indicating it's not part of object oriented paradigm
In your case you can do
StringReverse sr = new StringReverse();
String rev = sr.stringReversal("hello");
or declare your method differently
public static String stringReversal(String s)
In fact the class name StringReverse itself does not sound like some kind of object, so the second way is preferred impo
The deeper problem you have is the confusion on how Java handle OO and entrance function in general. Java is primarily an OO language so most of the time everything shall be an object or a member of a object. But when you telling the VM to run some java code, there got to be a place to start, which is the main method. There has to be one main method and it must be under some class, but it really has nothing to do with the class that contains it. Within the main method, you either start your OO life by instantiating objects and invoking their members (method 1) or stay in the spaghetti world for a bit longer, by calling other static members as procedures (method 2).
You have two options:
Keep the method non static and then create an instance of your class to call the method:
public static void main(String[] args) {
String str = "Hello";
StringReverse sr = new StringReverse(); // instance of class
String rev = sr.stringReversal(str);
System.out.println(); // just prints a blank line lol...
}
Make the method static (you should do this):
public static String stringReversal(String s) {
// ...
}
public static void main(String[] args) {
String str = "Hello";
String rev = stringReversal(str);
System.out.println(); // just prints a blank line lol...
}
Either way, you have to fix your "run time errors". You can't get around that. If your method doesn't work, keeping it not static won't make it work either.
By the way, I think you meant to do System.out.println(rev); instead of System.out.println();
For the record, here is how to easily reverse a string (both methods work):
public static String stringReversal(String s) {
StringBuffer reverseString = new StringBuffer();
// reverse the string
for (int i = s.length() - 1; i > -1; i--) {
reverseString.append(s.charAt(i));
}
return reverseString.toString();
}
/* using the reverse() method in the StringBuffer class
instead of reversing the string through iterations */
public static String stringReversal2(String s) {
return new StringBuffer(s).reverse().toString();
}
This is happening because your Main method is static, but the class that it's in is not. In order to call a non-static method, you need to create an instance of the class. Alternatively, the method can be made static, but in order to refer to it you need to include the class name in your call (as if to use the class itself like an object containing the method - see below).
There are three solutions to this problem:
Make an instance of the class and call the method from your object (recommended).
make the method static and use StringReverse.stringReversal().
Make the class AND the method static.
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.
I am working on a problem and I am very stuck because I am just starting to learn java. Any help I can get to understand this would be great. I have to write a program that has two classes. The main class will read from a file and uses the second class to find how may times the same words have been repeated in the file and add them to an array that contans the words and number of times the word repeated. I am ok with the reading the file part. I just can't seem to wrap my head around how to call a method from the second class to add the word into the array and increment the counter.
Here is my code so far if you run it you will see how new I am to this by how many errors you will get.
import java.io.*;
public class Words{
public static void main (String [] args)
{
ProcessInput();
System.out.println("\nprogram finished");
}
public static WordList ProcessInput( )
{
BufferedReader inputFile;
String inputLine;
String[] word;
WordList words;
try
{
inputFile=new BufferedReader(new FileReader ("inputFile.txt"));
inputLine = inputFile.readLine();
while (inputLine !=null)
{
word=inputLine.toLowerCase().split(" ");
for (int i=0; i<word.length; i++){
System.out.println (word[i]);
words=addWord(word[i]);
}
inputLine = inputFile.readLine();
}
inputFile.close();
}
catch (IOException ioe)
{
System.out.println (ioe.getMessage());
ioe.printStackTrace ();
}
return words;
}
}
class WordList {
String [] words;
int wordcount;
public WordList ( ){
words= new String [1000];
wordcount=0;
}
public String addWord (String word) {
words[wordcount]=word;
wordcount=+1;
return words[wordcount];
}
public void printList (){
for (int i=0; i<wordcount; i++){
System.out.println (words[i]);
}
}
}
You're very close. What you need to remember is when you're calling a method from another class you need to tell the compiler where to find that method.
So, instead of simply calling addWord("someWord"), you will need to initialise an instance of the WordList class (e.g. WordList list = new WordList();), and then call the method using that (i.e. list.addWord("someWord");.
However, your code at the moment will still throw an error there, because that would be trying to call a non-static method from a static one. So, you could either make addWord() static, or change the methods in the Words class so that they're not static.
My bad with the above paragraph - however you might want to reconsider ProcessInput() being a static method - does it really need to be?
You have to initialise the object (create the object itself) in order to be able to call its methods otherwise you would get a NullPointerException.
WordList words = new WordList();