Calling method from main throws NullPointerException - java

I try to call the method ss from my main method, but it throws the following exception
Exception in thread "main" java.lang.NullPointerException
at teste1.exp.ss(exp.java:16)
at teste1.Main.main(Main.java:64)
Java Result: 1
public class Main {
public static void main(String[] arguments) {
...................
private static String[] ff;
exp mega = new exp();
mega.ss(ff);
}
class exp {
public void ss (String gvanswer[]){
String answer[] = new String[3];
answer[0] = "pacific ";
answer[1] = "everest";
answer[2] = "amazon ";
if (gvnswer[0].equals("pacific"))
{System.out.println("eeeeeeeeeeeeee ");}
if (gvanswer[1].equals(answer[1])){System.out.println("l ");}
}

you call mega.ss(ff) but ff has never been initialited with somthing like:
ff = new String[1];
ff[0] = "foo";

You haven't populated the the array called ff which you are passing into the ss method.

You pass the ss method an uninitialized String[] array (ff) hence the NullPointerException.

Related

Use return of a method for string compare in a main if statement [duplicate]

This question already has answers here:
How do I call a non static method from a main method? [duplicate]
(7 answers)
Closed 3 years ago.
I created a method (apiType) that executes a command on a linux server. The result of the method should be used in my main class for executing a class or other class, depending if the result is "app2" or "app3".
The result of the linux command (cat /opt/pcu/bin/version | grep PRODUCT | cut -d' ' -f2) is either "app2" or "app3"
So my question is how can I call and use the result of the method in my main class?
OR what I do wrong or I miss in the code?
public class Api {
private final static String version = "v2";
private final static String path = FileSystems.getDefault().getPath(".").toAbsolutePath().getParent().toString();
public String apiType() throws Exception {
try {
Exec exec = new Exec();
exec.setCommand("cat /opt/pcu/bin/version | grep PRODUCT | cut -d' ' -f2");
exec.setLogPath(path);
exec.run("apiType");
exec.join(200);
Vector<String> output = exec.getOutput(false);
return output.get(0); //this should return "app2" or "app3"?!
} catch (Exception e) {
System.out.println("Failed to run command");
throw e;
}
}
public static void main(String[] args) {
if (args.length == 0) {
Date date = new Date();
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy/hh:mm:ss");
System.out.println(
"\n\n==================================== TestAPI program ====================================\n");
System.out.println("Date: " + dateFormat.format(date.getTime()) + " " + version);
System.out.println(
"\n==============================================================================================\n\n");
Console console = System.console();
String user = console.readLine("Username: ");
String password = new String((console.readPassword("Password: ")));
String testID = console.readLine("TestID: ");
String pattern = "[Tt]?(\\d+)";
Pattern pat = Pattern.compile(pattern);
Matcher m = pat.matcher(testID);
if (!m.matches()) {
System.out.println("Test ID doesn't have a valid format");
return;
}
testID = m.group(1);
String csvFilePath = console.readLine("CSV Test File: ");
if (????.equals("app2")) {
TestApi2 test = new TestApi2(user, password, testID, csvFilePath);
test.runTest();
} else if (????.equals("app3")) {
TestApi3 test2 = new TestApi3(user, password, testID, csvFilePath);
test2.runTest();
} else {
System.out.println("Unknown");
}
} else if (args.length == 1 && args[0].equalsIgnoreCase("--help")) {
}
}
}
You need to intstantiate an Api
Api api = new Api();
then call the method and assign its returned value to a string
String apiType = api.apiType();
At that point you can use your newly created string apiType to check for the returned value
if (apiType.equals("app2")) {
// ...
} else if (apiType.equals("app3")) {
// ...
}
I'm assuming that the main method is only meant for testing the class itself, so I will assume you actually don't want to make apiType itself static.

I want to use a stringtokenizer to store strings into an object User array but get an error message

I am getting an error that says Exception in thread "main" java.lang.NullPointerException at Members. init (Members.java:23) at Main.main(Main.java:9)
And what I'm trying to do is to use StringTokenizer to store strings from a file input into and object array.
In main, line 9 just initiates the object and the code is: Members members = new Members("users.txt");
Line 23 is class Members is: users[nm].setId(st.nextToken());
I can't figure out what the error is.
import java.io.*;
import java.util.*;
public class Members {
int nm = 0; //Number of members
User [] users = new User[100]; //Assuming max
number of user is 100
StringTokenizer st;
Scanner s1;
File f1;
String var1; //this string determines if it a standard or admin user;
String var2;
public Members(String fn) throws FileNotFoundException {
f1 = new File(fn);
s1 = new Scanner(f1);
while(s1.hasNext()) {
//System.out.println("true");
st = new StringTokenizer(s1.nextLine(),"/");
while(st.hasMoreTokens())
{
//System.out.print(((String)st.nextToken()));
users[nm].setId(st.nextToken());
users[nm].setPw(st.nextToken());
var1 = st.nextToken();
users[nm].setFn(st.nextToken());
users[nm].setLn(st.nextToken());
users[nm].setEmail(st.nextToken());
//System.out.print(st.nextToken() + " ");
if(var1.equals("Admin")) {
users[nm].setAdmin(true);
((Admin)users[nm]).setRank(st.nextToken());
}
if(var1.equals("Standard")) {
users[nm].setStandard(true);
while(st.hasMoreTokens())
{
((Standard)users[nm]).addCar(st.nextToken());
}
}
}
nm++;
System.out.println();
}
s1.close();
System.out.println("Number of members: " + nm);
}
You're creating an array that can hold Users, but as far as I can tell you aren't creating any instances of User. When you first try to reference users[nm] its value is going to be null.
You could do something like this:
users[nm] = new User();
users[nm].setId(st.nextToken());
The main culprit is User [] users = new User[100]; //Assuming max
This is creating a array of size 100 only. Not Creating any object. You are setting Id to a null object. Before setting the Id you have to initialize your user object.

pass the argument of array from command line instead of scanner in java

I write the code in Java to get the arguments by scanner. I have several classes : ChartToHtml.java, ExecutionProperties.java, ExecutionV2.java, TestCase.java, TestCaseList.java, Section.java and all of them will be called from ImplTest.java.
They are working fine when I execute either from eclipse or command line by scanner. The problem is when I want to execute them via program arguments and pass the arguments in one single line. It considers the input as single String but I have to use a String[] as input for Section class.
Here are my Section class and ImplTest classes
public class Section {
Ini.Section root;
ArrayList<String> StringList = new ArrayList<String>();
ArrayList<TestCase> TCList = new ArrayList<TestCase>();
String sectionSearched;
String section;
String filenameSearched;
public Section (){
}
public Section (String filenameSearched, String sectionSearched) {
this.sectionSearched = sectionSearched;
this.filenameSearched = filenameSearched;
}
public ArrayList<String> findSection(String filename, String... wanted) throws IOException, IOException {
Ini myIni = new Ini(new File (filename));
for (String d : wanted) {
root = myIni.get(d);
for (String name : root.keySet()){
StringList.add(root.get(name));
}
}
return StringList;
}
public ArrayList<TestCase> convertStringToTestCase(ArrayList<String>StringList){
for ( int i = 0; i < StringList.size(); i++) {
String name = StringList.get(i) ;
TestCase tc = new TestCase (name);
TCList.add(tc);
}
return TCList;
}
public String[] getSection(int NumOfSec){
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Input section name:");
section = scanner.nextLine();
for (int i =0; i<NumOfSec; i++){
String token[]= section.split(" ");
System.out.println(Arrays.toString(token));
return token;
}
}
}
}
My Main class
public class ImplTest {
public static void main(String[] args) throws IOException, ConfigurationException, TemplateException {
ExecutionV2 ex = new ExecutionV2();
TestCaseList tc = new TestCaseList();
Section s = new Section();
ChartToHtml chr= new ChartToHtml();
ExecutionProperties ep = new ExecutionProperties();
ImplTest imp = new ImplTest();
String filename = ex.getcfg();
String []sec = ex.getSection();
int it = ex.getIterationMax();
String runTCpath =ex.getRunTCdir();
String dir = chr.getChartDir();
ArrayList<TestCase> TClist = s.convertStringToTestCase(s.findSection(filename, sec));
ex.executeTestCaseList(TClist, it , runTCpath);
ex.getTCAttribute(TClist);
ep.setConfigProperties(tc.getTCPassed(), tc.getTCFailed());
chr.generateHistoryTable();
chr.generateChartAndTableTemplate(tc.getTCPassed(), tc.getTCFailed(),ex.getNameList(), ex.getPassedList().toString(), ex.getItList().toString(),dir);
}
}
Then I modified the main class to pass the arguments via run configuration and pass this single line:
ArrayList<TestCase> TClist = s.convertStringToTestCase(s.findSection(**args[0]**, **args[1]**));
ex.executeTestCaseList(TClist, Integer.parseInt(**args[2]**) , **args[3]**);
ex.getTCAttribute(TClist);
ep.setConfigProperties(tc.getTCPassed(), tc.getTCFailed());
chr.generateHistoryTable();
chr.generateChartAndTableTemplate(tc.getTCPassed(), tc.getTCFailed(),ex.getNameList(), ex.getPassedList().toString(), ex.getItList().toString(), **args[4]**);
and pass this singe line into program arguments
C:\\Users\\syuniyar\\.EasyTest\\4\\ccl\\config\\test2.cfg 12346 5 C:\\EasyTest\\4\\bin\\runTC.exe C:\\Users\\syuniyar\\EclipseWS\Test3\\chart.html
it is working fine. However, when I modify the input from ...12346... to ...12346 12345..., I get such error:
Exception in thread "main" java.io.IOException: Cannot run program "5": CreateProcess error=2, The system cannot find the file specified
I also try with VM arguments but the option of System.getProperty() is only for single string.
I know why I get this error because it reads 12345 as 'it' which is not correct. What I wanna ask :
Is it possible to have an array as single argument in main method?
To directly answer your question, "Is it possible to have an array as [a] single argument in [a] main method?", no. The main method accepts arguments in the form of one array of String objects (usually called "args"). Each of these strings is considered an argument.
When executing the main method from the command line, these arguments come after the program name and are delimited by spaces. They are loaded into an array and passed into the main method.
As mentioned in the comments (esp. #Ismail Kuruca), if it is important to you to pass in several strings as one argument, you can concatenate the strings to make your arguments technically one String, and thereby treated as one argument.

identifier error when declaring object array for file

public static Vehicle[] fillArray(inputString) throws exception {
while(readRecords.ready()) {
Vehicle newVehicle;
checkType = readRecords.readLine();
if(checkType.equals("vehicle")) {
String ownersName = readRecords.readLine();
String address = readRecords.readLine();
String phone = readRecords.readLine();
String email = readRecords.readline();
newVehicle = new Vehicle(ownersName,address,phone,email);
list.add(newVehicle);
}
I am getting an <identifier> expected error. Signals at the inputString within the parenthesis.
any suggestions?
You need to tell what type the parameter is:
public static Vehicle[] fillArray(String inputString) throws Exception
Otherwise the compiler doesn't know if inputString is a string, an int, or some other object. It won't guess by the name.
You should specify a type for your parameter. Try this :
public static Vehicle[] fillArray(String inputString) throws exception

Variable g may not have been initialized

I have many questions about this project that I'm working on. It's a virtual database for films. I have a small MovieEntry class (to process individual entries) and a large MovieDatabase class that keeps track of all 10k+ entries. In my second searchYear method as well as subsequent methods I get the error "variable g (or d or whatever) might not have been initialized."
I also get a pop-up error that says Warnings from last compilation: unreachable catch clause. thrown type java.io.FileNotFoundException has already been caught. I'm positively stumped on both. Here's the code:
public class MovieDatabase
{
private ArrayList<MovieEntry> Database = new ArrayList<MovieEntry>();
public MovieDatabase(){
ArrayList<MovieDatabase> Database = new ArrayList<MovieDatabase>(0);
}
public int countTitles() throws IOException{
Scanner fileScan;
fileScan = new Scanner (new File("movies.txt"));
int count = 0;
String movieCount;
while(fileScan.hasNext()){
movieCount = fileScan.nextLine();
count++;
}
return count;
}
public void addMovie(MovieEntry m){
Database.add(m);
}
public ArrayList<MovieEntry> searchTitle(String substring){
for (MovieEntry title : Database)
System.out.println(title);
return null;
}
public ArrayList<MovieEntry> searchGenre(String substring){
for (MovieEntry genre : Database)
System.out.println(genre);
return null;
}
public ArrayList<MovieEntry> searchDirector (String str){
for (MovieEntry director : Database)
System.out.println(director);
return null;
}
public ArrayList<String> searchYear (int yr){
ArrayList <String> yearMatches = new ArrayList<String>();
for (MovieEntry m : Database)
m.getYear(yr);
if(yearMatches.contains(yr) == false){
String sYr = Integer.toString(yr);
yearMatches.add(sYr);
}
return yearMatches;
}
public ArrayList<MovieEntry> searchYear(int from, int to){
ArrayList <String> Matches = new ArrayList<String>();
for(MovieEntry m : Database);
m.getYear();
Matches.add();
return Matches;
}
public void readMovieData(String movies){
String info;
try{
Scanner fileReader = new Scanner(new File("movies"));
Scanner lineReader;
while(fileReader.hasNext()){
info = fileReader.nextLine();
lineReader = new Scanner(info);
lineReader.useDelimiter(":");
String title = lineReader.next();
String director = lineReader.next();
String genre = lineReader.next();
int year = lineReader.nextInt();
}
}catch(FileNotFoundException error){
System.out.println("File not found.");
}catch(IOException error){
System.out.println("Oops! Something went wrong.");
}
}
public int countGenres(){
ArrayList <String> gList = new ArrayList<String>();
for(MovieEntry m : Database){
String g = m.getGenre(g);
if(gList.contains(g) == false){
gList.add(g);
}
return gList.size();
}
}
public int countDirectors(){
ArrayList <String> dList = new ArrayList<String>();
for(MovieEntry m : Database){
String d = m.getDirector(d);
if(dList.contains(d) == false){
dList.add(d);
}
return dList.size();
}
}
public String listGenres(){
ArrayList <String> genreList = new ArrayList<String>();
}
}
catch(IOException error){
System.out.println("Oops! Something went wrong.");
}
Its telling you that the FileNotFoundException will deal with what the IOException is catching, so the IOException becomes unreachable as in it will never catch an IO exceltion, why just not catch an Exception instead
As for the initialization
public int countDirectors(){
ArrayList <String> dList = new ArrayList<String>();
for(MovieEntry m : Database){
String d = m.getDirector(d); //THIS LINE
if(dList.contains(d) == false){
dList.add(d);
}
return dList.size();
}
The line String d = m.getDirector(d); might be the problem, d wont be initialised unless there is something in the MovieEntry and as far as i can see there will never be anything because you are initialising it to an empty array list
ArrayList<MovieDatabase> Database = new ArrayList<MovieDatabase>(0);
Maybe you should be passing a array of movies to the constructor and then add these movies to the Database variable ?
Seems like there are a number of issues with this code.
What parameter does MovieEntry.getGenre() expect? You may not use g in that case because it has not been defined yet.
The exception issue you mentioned means that the exception was already caught, or possibly never thrown. I believe that in this case the IOException is never thrown out from the code within the try block.
There are a number of methods that are supposed to return a value but do not, example:
public String listGenres(){
ArrayList <String> genreList = new ArrayList<String>();
}
Also, it is a java naming convention to use lower case first characters (camel case) for values:
private ArrayList<MovieEntry> database = new ArrayList<MovieEntry>();
Oh, and do you need to re-initialize the database variable in the constructor?:
public MovieDatabase(){
ArrayList<MovieDatabase> Database = new ArrayList<MovieDatabase>(0);
}
Hope this is helpful.

Categories