how to make getArray method - arrays

When I run a specific part of a code I have:
public String getWords (){
randomWord = words[randy.nextInt(words.length)];
return randomWord;
}
private String[] words = {"apple", "beret", "arose", "along", "beamy", "becks", "decks", "barks",
"stark", "start", "stabs", "baggy", "asked", "asset", "asses", "audit",
"bowls", "boxes", "seats", "balls", "boats", "boxer", "brick", "bound",
"brass", "caked", "braid", "caged", "essay", "fault", "dents", "dutch",
"ethos", "dunks", "pains", "faxes", "mummy", "mixer", "mills", "might",
"moral", "teeth", "wings", "works", "walls", "tolls", "crawl", "toxin",
"bangs", "tough"};
Hangman man = new Hangman();
man.mainScreen();
public void mainScreen (){
start();
while (guesses != maxGuesses){
continueGame();
checkBodyParts();
}
gameOver();
}
ERROR:
java.lang.NullPointerException
at Hangman.getWords(Hangman.java:43)
at Hangman.<init>(Hangman.java:28)
at GameApp.main(GameApp.java:9)
I get a runtime error of NullPointerException. I asked around and they said I should make a method to get the array words because I can't get to it at the moment. What should this method have in it?

I believe your problem is here:
private String myGeneratedRandomWord = getWords();
This method is trying to use the array "words" before it is created.
Move this line after the array "words" is created.
This should solve your NullPointerError.

Related

What does the error unexpected token 'public' mean?

I am a beginner in Apex and I need your help. What I am trying to do is creating a class that returns an array of formatted strings. The class has as a parameter the number of strings and it returns the array of strings formatted as:
Test 0, Test 1, ...Test n
The error I get is:
unexpected token 'public (line 1).
There might be more than one error in my code, if yes please feel free to let me know.
Thank you in advance!
public class StringArrayTest {
public static void generateStringArray(Integer n){
//List<String> stringArray = new List<String>();
for(Integer i=0; i<n; i++){
List<String>stringArray = new List<String>{'Test '+i};
}
return stringArray[];
}
}
There are a few things wrong with the code you have posted. When I tried this out I didn't get the error you mentioned, but here are the things to fix and get your code working:
The method should declare a return value of List<String>
Uncomment the line to initialize your list before the loop.
Return just the variable itself, no need to have the brackets. It's already a list.
Here is working code:
public class StringArrayTest {
public static List<String> generateStringArray(Integer n){
List<String> stringArray = new List<String>();
for(Integer i = 0; i < n; i++){
stringArray.add('Test ' + i);
}
return stringArray;
}
}

Pointers, functions and arrays in D Programming Language

I'm writing a method to output to several output streams at once, the way I got it set up right now is that I have a LogController, LogFile and LogConsole, the latter two are implementations of the Log interface.
What I'm trying to do right now adding a method to the LogController that attaches any implementation of the Log interface.
How I want to do this is as follows: in the LogController I have an associative array, in which I store pointers to Log objects. When the writeOut method of the LogController is called, I want it to then run over the elements of the array and call their writeOut methods too. The latter I can do, but the previous is proving to be difficult.
Mage/Utility/LogController.d
module Mage.Utility.LogController;
import std.stdio;
interface Log {
public void writeOut(string s);
}
class LogController {
private Log*[string] m_Logs;
public this() {
}
public void attach(string name, ref Log l) {
foreach (string key; m_Logs.keys) {
if (name is key) return;
}
m_Logs[name] = &l;
}
public void writeOut(string s) {
foreach (Log* log; m_Logs) {
log.writeOut(s);
}
}
}
Mage/Utility/LogFile.d
module Mage.Utility.LogFile;
import std.stdio;
import std.datetime;
import Mage.Utility.LogController;
class LogFile : Log {
private File fp;
private string path;
public this(string path) {
this.fp = File(path, "a+");
this.path = path;
}
public void writeOut(string s) {
this.fp.writefln("[%s] %s", this.timestamp(), s);
}
private string timestamp() {
return Clock.currTime().toISOExtString();
}
}
I've already tried multiple things with the attach functions, and none of them. The build fails with the following error:
Mage\Root.d(0,0): Error: function Mage.Utility.LogController.LogController.attach (string name, ref Log l) is not callable using argument types (string, LogFile)
This is the incriminating function:
public void initialise(string logfile = DEFAULT_LOG_FILENAME) {
m_Log = new LogController();
LogFile lf = new LogFile(logfile);
m_Log.attach("Log File", lf);
}
Can anyone tell me where I'm going wrong here? I'm stumped and I haven't been able to find the answer anywhere. I've tried a multitude of different solutions and none of them work.
Classes and interfaces in D are reference types, so Log* is redundant - remove the *. Similarly, there is no need to use ref in ref Log l - that's like taking a pointer by reference in C++.
This is the cause of the error message you posted - variables passed by reference must match in type exactly. Removing the ref should solve the error.

Exception in thread "main" java.lang.NullPointerException? What does this mean?

I have an error when trying to run this program. This is not the entire program just the few details I think where the problem is. The error points out
if(board[randSpace].isEmpty()) and
cl.makeChutes(5);"
Error is :
"Exception in thread "main" java.lang.NullPointerException
at ChutesAndLadders.makeChutes(ChutesAndLadders.java:29)
at ChutesAndLadders.main(ChutesAndLadders.java:67)"
This is my program:
import java.util.Random;
public class ChutesAndLadders{
Cell [] board = new Cell [100];
Random rand = new Random ();
public int chutes, ladders;
public void makeChutes (int a ){
int makeChutes = a;
for (int i = 0; i < a; i++){
int randSpace = rand.nextInt(99);
if(board[randSpace].isEmpty())
board[randSpace] = new Cell (-10,"C");
else
i--;
}
}
public static void main(String[] args) {
// Create an instance of ChutesAndLadders
ChutesAndLadders cl = new ChutesAndLadders(10,10);
// Randomly place 5 more chutes and 5 more ladders
cl.makeChutes(5);
cl.makeLadders(5);
Here is my isEmpty:
public boolean isEmpty(){
for(int i = 0; i < board.length; i++)
{
if (board[i].isEmpty())
return true;
}
return false;
}
I could be entirely wrong on my coding. I'm still learning so please be patient. Thank you!
Following on what Dewfy said, board is an array of Cell objects. That means it is a placeholder for Cell objects --a bunch of nulls waiting to be replaced by a Cell.
If say, the object at position 1 (board[1]) has not been assigned a Cell object (i.e. you haven't issued a command like board[1]=new Cell() or something like that) then board[1] is null. Therefore if you were to ask board[1].isEmpty() you would get a NullPointerException because you are trying to call a method on a null object.
Now, your error is likely to come from board[randSpace] being null. So, the question is: does it contain a Cell object? Have you initialized your array with Cell objects?
One way to check this would be to say:
if (board[randSpace]==null || board[randSpace].isEmpty()) .....
Problem appears with this line:
if(board[randSpace].isEmpty())
so it is supposed that obect at randSpace already exists, if not you create object (Cell). But object is not yet created, how you can ask it if null isEmpty(). Just check against null first

How can you reverse an Array without using the reverse method in AS3?

How can you reverse an array without using the reverse() method?
public class Main extends Sprite
{
private var _reversedList:Array = new Array();
public function Main()
{
var yourShoppingList:Array = ["Milk","Bread","Eggs","Cereal","Cheese","Ham"];
shoppingList(yourShoppingList);
trace("The original array was " + yourShoppingList + " and now it is reversed as " + _reversedList + ".");
}
private function shoppingList(items:Array):Array {
while(items.length){
var lastItem:String = items.pop();
_reversedList.unshift(lastItem);
}
return _reversedList;
}
}
This is what I have so far. I tried using _reversedList.unshift(items.pop()); but it was giving me an error, so I ended up creating a variable, and now it seems fine? But regardless, it's not reversing the Array, and I'm not sure why.
Thank you for your time and help. I really appreciate it.
*NOTE: For those of you who are Full Sail students, feel free to reference this, but don't copy / paste, as the teachers know about this post and you'll probably be penalized for cheating. Just a friendly warning.
Changing
_reversedList.unshift(lastItem);
to
_reversedList.push(lastItem);
works for me. Taking the last item and pushing it in as the first item on the new array.

String Arrays and Session

I am dealing one serious problem and seems i cannot find a logical solution.
Here it goes.
I have a string array in my code (jsp file). I want to pass the array in the same page , and i thought of making the array a session and call it again later in my code but it seems that i cannot take the session (with get.Attribute) and make it an array again. TO be more specise the following code might help you.
while (onomaq.next()) {
String onomatemp = onomaq.getString("one1");
String[] onoma = onomatemp.split(" ");
out.println(onoma[2]);
session.setAttribute("onoma", onoma);
}
} catch (Exception e) {
System.out.println("SQL Exception: " + e.toString());
}
%>
<%
try{
Object o = session.getAttribute("onoma");
String k=o.toString();
String[] name=k.split(",");
out.println(name[1]);
}
catch (Exception e)
{
System.out.println("SQL Exception: " + e.toString());
}
the out.println gives me a message lige [L.java.String and some characters.
Can anyone help me please?
Rather than calling toString() on your array object after obtainig it from session, just cast the object reference to an array (since your object IS an array) and use it.
This means, replace this code:
Object o = session.getAttribute("onoma");
String k=o.toString();
String[] name=k.split(",");
with
String[] name= (String[]) session.getAttribute("onoma");
p.s. purpose of toString() is somwhat different from what you seem to expect. See Javadoc.
String[] expected_array= (String[]) session.getAttribute("onoma");
Then run it inside a loop to retrieve. Example:
for(int i = 0; i < expected_array. length; i++)
{
String strings = expected_array[i] ;
}

Resources