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;
}
}
Related
I need your help.
I made an apex class which is giving output like (1,i,n,d,i,a,,1,2,3) and I would like to show output as a whole string format like(1india 123). I tried many different ways but couldn't get what I actually want.
Here is my apex class:-
public class Assign2{
public void testFunction(String str ,integer num){
integer rem,temp = 0;
integer sumOfDigit = 0;
List<String> stringCharacters = new List<String>();
List<String> inputStr = new List<String>();
stringCharacters = str.split('');
System.debug('stringCharacters::'+stringCharacters);
for(integer i=0; i<stringCharacters.size(); i++){
if(stringCharacters[i].isNumeric()){
temp = Integer.valueOf(stringCharacters[i]);
//System.debug('temp::'+temp);
rem = temp +num;
//System.debug('rem::'+rem);
sumOfDigit = math.mod(rem,10);
//System.debug('sumOfDigit::'+sumOfDigit);
stringCharacters[i] = sumOfDigit+'';
//System.debug('ans::'+stringCharacters);
}
}
System.debug('ans::'+stringCharacters);
}}
and I run the program by giving input:-
Assign2 obj = new Assign2();
obj.testFunction('2india 234',9);
help will be appreciable.
Thank You.
You've used split with empty string as parameter (meaning you want to cut it into 1-character strings). All you have to do is to reverse the process with join.
List<String> characters = new List<String>{'1','i','n','d','i','a',' ','1','2','3'};
String word = String.join(characters, '');
System.debug(word); // "1india 123"
My purpose is to get what a user types in and to store them in the array "info", then convert the info[0] into upper case. However, when I compile my code, I always got the message Exception in thread "main" java.lang.NullPointerException at the line "info[0]=info[0].toUpperCase();". But I totally have not idea what causes this exception. If anyone can tell me the cause, it would be great. Thank you!
public static void main(String[] args)
{
Scanner userScan = new Scanner(System.in);
String keyboard = userScan.nextLine();
StringTokenizer tokens = new StringTokenizer(keyboard, " ");
String[] info= new String[4];
for(int i=0; tokens.hasMoreTokens(); i++)
{
info[i] = tokens.nextToken();
}
info[0]=info[0].toUpperCase();
//other codes...
}
When you try to execute the code without any tokens, It would skip past the for loop, and try to perform
info[0].toUpperCase();
But since the for loop has been skipped info object is initialized to null.
Thus trying to access it would give you an Null Pointer Exception.
Just move the conversion inside the for loop to avoid this.
for(int i=0; tokens.hasMoreTokens(); i++){
info[i] = tokens.nextToken();
//converts only when value exists
info[i]=info[i].toUpperCase();
}
I have some TableView with two columns - name and size;
This Table works with File objects;
PropertyValueFactory for columns can take properties of object, trying search somenameProrperty, getSomename, isSomename;
I'm need to get length() method from File.
columnName.setCellValueFactory(new PropertyValueFactory<>("name"));
columnSize.setCellValueFactory(new PropertyValueFactory<>("length"));
This code view file names (getName() method), but length colums is empty.
Know anyone what i can do with factory to get length() from File?
You should implement the cell value factory directly, instead of using the convenience (and somewhat legacy) class PropertyValueFactory.
Assuming your columnSize is a TableColumn<File, Number>, you can do
columnSize.setCellValueFactory(cellData ->
new SimpleLongProperty(cellData.getValue().length()));
If you want to format the data in the column more elegantly, you can additionally set a cell factory:
columnSize.setCellFactory(col -> new TableCell<File, Number>() {
#Override
protected void updateItem(Number length, boolean empty) {
super.updateItem(length, empty);
if (empty) {
setText(null);
} else {
setText(formatFileLength(length.longValue()));
}
}
});
// ...
private String formatFileLength(long length) {
final String[] unitNames = {"bytes", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"};
int i ;
for (i = 0 ; length > 1024 && i < unitNames.length - 1 ; i++) {
length = length / 1024 ;
}
return String.format("%,d %s", length, unitNames[i]);
}
Found solution
columnSize.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<File, String>, ObservableValue<String>>() {
#Override
public ObservableValue<String> call(TableColumn.CellDataFeatures<File, String> param) {
long size = param.getValue().length();
size = size/1024;
return new ReadOnlyObjectWrapper(String.valueOf(size));
}
});
I've been learning OOP recently and have decided to take that paradigm shift into it (its not easy...at ALL) and in trying some of the concepts of it I'm having a bit of a problem inheriting from the Array class in ActionScript 3.0 (not that i have tried in AS 2.0)...sigh. Anyway I am trying to call the parent constructor to instantiate the ...rest arguments from within the child class like so
public class CustomArray extends Array{
public function CustomArray(...rest):void {
super(rest);
}
}
And I keep getting this Error from the output...
ReferenceError: Error #1056: Cannot create property 0 on classes.CustomArray.
...to my utter dismay :(.
I'm obviously doing something wrong but for the love of me can't seem to find out what it is. Really in need of help. Thanks.
Unfortunately in AS3 you can't call super constructor and pass parameters to it in Function::apply style, so in your Array implementation array with length=1 and one element (the passed rest parameter with the type of Array) will always be created.
If you want to implement the default AS3 Array constructor behavior:
Array Constructor
public function Array(... values)
Parameters
... values — A comma-separated list of one or more arbitrary values.
Note: If only a single numeric parameter is passed to the Array constructor,
it is assumed to specify the array's length property.
You have to add some code to the constructor of your CustomArray:
public dynamic class CustomArray extends Array
{
public function CustomArray(...rest)
{
super();
var i:int, len:int;
if(rest.length == 1)
{
len = rest[0];
for (i = 0; i < len; i++)
this[i] = "";
}
else
{
len = rest.length;
for (i = 0; i < len; i++)
this[i] = rest[i];
}
}
}
Also don't forget to make this class dynamic.
Declare this class as dynamic. Also constructor is a method which doesn't specify return type, remove :void from its declaration.
Sorry to revive this "old" thread. I felt compelled to improve the constructor proposed by fsbmain.
When one calls new Array("foo"), an Array object is created containing the String "foo" - ["foo"]. So I think the custom constructor must take that possibility into account ( only one parameter that is not a number).
Here's the code I propose:
package {
public dynamic class MyArray extends Array {
public function MyArray(...rest) {
// super();
// I think super() is not mandatory here since
// we are basically replacing the constructor...
var i: int, len: int;
if (rest.length == 1) {
if(rest[0] is Number){
len = rest[0];
for (i = 0; i < len; i++) {
this[i] = null; // empty values must be null, not ""
}
}else{
this[0]=rest[0];
}
} else {
len = rest.length;
for (i = 0; i < len; i++) {
this[i] = rest[i];
}
}
}
}
}
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