I'm trying to do an exercise from a java book. The code comes as is and I have not added anything to the code besides setting the path for the database. I'm on OSX, so I had to install Apache Derby. Everytime I build and run the program I get this:
Derby has been started.
Product list:
bvbn Murach's Beginning Visual Basic .NET $49.50
cshp Murach's C# $49.50
java Murach's Beginning Java $49.50
jsps Murach's Java Servlets and JSP $49.50
mcb2 Murach's Mainframe COBOL $59.50
sqls Murach's SQL for SQL Server $49.50
zjcl Murach's OS/390 and z/OS JCL $62.50
Exception in thread "main" java.lang.NullPointerException
First product:
at DBTesterApp.printProduct(DBTesterApp.java:117)
at DBTesterApp.printFirstProduct(DBTesterApp.java:66)
at DBTesterApp.main(DBTesterApp.java:16)
Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)
I'm confused as to why this exception keeps happening. I don't seem to find anything wrong with the 'main' code (see below) and I feel like I've tried everything. Any clue as to what could be causing this?
import java.sql.*;
public class DBTesterApp
{
private static Connection connection = null;
public static void main(String args[])
{
// get the connection and start the Derby engine
connection = MurachDB.getConnection();
if (connection != null)
System.out.println("Derby has been started.\n");
// select data from database
printProducts();
printFirstProduct();
printLastProduct();
printProductByCode("java");
// modify data in the database
Product p = new Product("test", "Test Product", 49.50);
insertProduct(p);
printProducts();
deleteProduct(p);
printProducts();
// disconnect from the database
if (MurachDB.disconnect())
System.out.println("Derby has been shut down.\n");
}
public static void printProducts()
{
try (Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT * FROM Products"))
{
Product p = null;
System.out.println("Product list:");
while(rs.next())
{
String code = rs.getString("ProductCode");
String description = rs.getString("Description");
double price = rs.getDouble("Price");
p = new Product(code, description, price);
printProduct(p);
}
System.out.println();
}
catch(SQLException e)
{
e.printStackTrace(); // for debugging
}
}
public static void printFirstProduct()
{
Product p = null;
// add code that prints the record for the first product in the Products table
System.out.println("First product:");
printProduct(p);
System.out.println();
}
public static void printLastProduct()
{
Product p = null;
// add code that prints the record for the last product in the Products table
System.out.println("Last product:");
printProduct(p);
System.out.println();
}
public static void printProductByCode(String productCode)
{
Product p = null;
// add code that prints the product with the specified code
System.out.println("Product by code: " + productCode);
printProduct(p);
System.out.println();
}
public static void insertProduct(Product p)
{
System.out.println("Insert test: ");
// add code that inserts the specified product into the database
// if a product with the specifed code already exists, display an error message
printProduct(p);
System.out.println();
}
private static void deleteProduct(Product p)
{
System.out.println("Delete test: ");
// add code that deletes the specified product from the database
// if a product with the specified code doesn't exist, display an error message
printProduct(p);
System.out.println();
}
// use this method to print a Product object on a single line
private static void printProduct(Product p)
{
String productString =
StringUtils.padWithSpaces(p.getCode(), 8) +
StringUtils.padWithSpaces(p.getDescription(), 44) +
p.getFormattedPrice();
System.out.println(productString);
}
}
This sequence of code will produce an NPE as Product phas not been instantiated:
Product p = null;
System.out.println("First product:");
printProduct(p);
private static void printProduct(Product p)
{
String productString =
StringUtils.padWithSpaces(p.getCode(), 8) + // <-- This guy is angry when the 'p' passed to it is null
StringUtils.padWithSpaces(p.getDescription(), 44) +
p.getFormattedPrice();
System.out.println(productString);
}
}
Then
public static void printFirstProduct()
{
Product p = null;
// add code that prints the record for the first product in the Products table
System.out.println("First product:");
printProduct(p); //<--- This 'p' is null when you pass it to it because you never assgin it after setting it to null.
System.out.println();
}
You are passing null here
public static void printFirstProduct()
{
Product p = null;
// add code that prints the record for the first product in the Products table
System.out.println("First product:");
printProduct(p);
System.out.println();
}
Another possible weakness:
connection = MurachDB.getConnection();
if (connection != null)
System.out.println("Derby has been started.\n");
If connection is null the code goes ahead anyway and later tries to invoke methods on null.
I'm not saying that it causes your problems now but definitely could at some point.
Related
I am currently working on a Java program that crawls a webpage and prints out some information from it.
There is one part that I can't figure out, and thats when I try to print out one specific String Array with some information in it, all it gives me is " ] " for that line. However, a few lines before, I also try printing out another String array in the exact same way and it prints out fine. When I test what is actually being passed to the "categories" variable, its the correct information and can be printed out there.
public class Crawler {
private Document htmlDocument;
String [] keywords, categories;
public void printData(String urlToCrawl)
{
nextURL=urlToCrawl;
crawl();
//This does what its supposed to do. (Print Statement 1)
System.out.print("Keywords: ");
for (String i :keywords) {System.out.print(i+", ");}
//This doesnt. (Print Statement 2)
System.out.print("Categories: ");
for (String b :categories) {System.out.print(b+", ");}
}
public void crawl()
{
//Gather Data
//open up JSOUP for HTTP parsing.
Connection connection = Jsoup.connect(nextURL).userAgent(USER_AGENT);
Document htmlDocument = connection.get();
this.htmlDocument=htmlDocument;
System.out.println("Recieved Webpage "+ nextURL);
int guacCounter = 0;
for(Element guac : htmlDocument.select("script"))
{
if(guacCounter==5)
{
//String concentratedGuac = guac.toString();
String[] items = guac.toString().split("\\n");
categories = processGuac(items);
break;
}
else if(guacCounter<5) {
guacCounter++;
}
}
}
public String[] processKeywords(String totalKeywords)
{
String [] separatedKeywords = totalKeywords.split(",");
//System.out.println(separatedKeywords.toString());
return separatedKeywords;
}
public String[] processGuac(String[] inputGuac)
{
int categoryIsOnLine = 6;
String categoryData = inputGuac[categoryIsOnLine-1];
categoryData = categoryData.replace(",","");
categoryData = categoryData.replace("'","");
categoryData = categoryData.replace("|",",");
categoryData = categoryData.split(":")[1];
//this prints out the list of categories in string form.(Print Statement 3)
System.out.println("Testing here: " + categoryData.toString());
String [] categoryList=categoryData.split(",");
//This prints out the list of categories in array form correctly.(Print statement 4)
System.out.println("Testing here too: " );
for(String a : categoryList) {System.out.println(a);}
return categoryList;
}
}
I cut out a lot of the irrelevant parts of my code so there might be some missing variables.
Here is what my printouts look like:
PS1:
Keywords: What makes a good friend, making friends, signs of a good friend, supporting friends, conflict management,
PS2:
]
PS3:
Testing here: wellbeing,friends-and-family,friendships
PS4:
Testing here too:
wellbeing
friends-and-family
friendships
I've got a class named "User" which has a method that makes the User type his name. This name is saved in an array that is empty at first.
Question is, how can I use this "stored" name in another class (I want to show the name in this other class)
Here's what I've got (Sorry for the spanish lol)
public class Usuario {
private Scanner entrada = new Scanner(System.in);
private String Usuario[] = new String[20];
private int Posicion = 0;
private int punteo;
public void Datos() {
System.out.println("Ingresa tu nombre");
if(Usuario[Posicion] == null) {
this.Usuario[0] = entrada.nextLine();
Posicion++;
}
}
public String Usuario() {
return Usuario[Posicion-1];
}
And I want to use the name (Usuario[Posicion-1]) for example in a class like this:
public class Score extends Usuario {
Usuario usr = new Usuario();
String[] Name = new String[20];
public void Score () {
Name[0]=usr.Usuario();
System.out.println("------------Scores ------------------");
System.out.println(" Name "+ " Score");
for(int i=0;i<11;i++) {
System.out.println(i+".- " + " "+Name[0] +" 200 ");
}
}
}
But Everytime I try to retrieve this data in this class I get a "null" value or an "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1" error, which makes me believe that I can't use the information from the array in another class :(
I'd appreciate any help. (also Sorry for the not-so-good english).
Each new version of a class or an object is not going to have the same values.
you will have to get the name from the object User.name then set it in your other object secondObject.name = User.name
This is actually a re-do of an older question of mine that I have completely redone because my old question seemed to confuse people.
I have written a Java program that Queries a database and is intended to retrieve several rows of data. I have previously written the program in Informix-4GL and I am using a sql cursor to loop through the database and store each row into a "dynamic row of record". I understand there are no row of records in Java so I have ended up with the following code.
public class Main {
// DB CONNECT VARIABLE ===========================
static Connection gv_conn = null;
// PREPARED STATEMENT VARIABLES ==================
static PreparedStatement users_sel = null;
static ResultSet users_curs = null;
static PreparedStatement uinfo_sel = null;
static ResultSet uinfo_curs = null;
// MAIN PROGRAM START ============================
public static void main(String[] args) {
try {
// CONNECT TO DATABASE CODE
} catch(Exception log) {
// YOU FAILED CODE
}
f_prepare(); // PREPARE THE STATEMENTS
ArrayList<Integer> list_id = new ArrayList<Integer>();
ArrayList<String> list_name = new ArrayList<String>();
ArrayList<Integer> list_info = new ArrayList<String>();
ArrayList<String> list_extra = new ArrayList<String>();
try {
users_sel.setInt(1, 1);
users_curs = users_sel.executeQuery();
// RETRIEVE ROWS FROM USERS
while (users_curs.next()) {
int lv_u_id = users_curs.getInt("u_id");
String lv_u_name = users_curs.getString("u_name");
uinfo_sel.setInt(1, lv_u_id);
uinfo_curs = uinfo_sel.executeQuery();
// RETRIEVE DATA FROM UINFO RELATIVE TO USER
String lv_ui_info = uinfo_curs.getString("ui_info");
String lv_ui_extra = uinfo_curs.getString("ui_extra");
// STORE DATA I WANT IN THESE ARRAYS
list_id.add(lv_u_id);
list_name.add(lv_u_name);
list_info.add(lv_ui_info);
list_extra.add(lv_ui_extra);
}
} catch(SQLException log) {
// EVERYTHING BROKE
}
// MAKING SURE IT WORKED
System.out.println(
list_id.get(0) +
list_name.get(0) +
list_info.get(0) +
list_extra.get(0)
);
// TESTING WITH ARBITRARY ROWS
System.out.println(
list_id.get(2) +
list_name.get(5) +
list_info.get(9) +
list_extra.get(14)
);
}
// PREPARE STATEMENTS SEPARATELY =================
public static void f_prepare() {
String lv_sql = null;
try {
lv_sql = "select * from users where u_id >= ?"
users_sel = gv_conn.prepareStatement(lv_sql);
lv_sql = "select * from uinfo where ui_u_id = ?"
uinfo_sel = gv_conn.prepareStatement(lv_sql)
} catch(SQLException log) {
// IT WON'T FAIL COZ I BELIEEEVE
}
}
}
class DBConn {
// connect to SQLite3 code
}
All in all this code works, I can hit the database once, get all the data I need, store it in variables and work with them as I please however this does not feel right and I think it's far from the most suited way to do this in Java considering I can do it with only 15 lines of code in Informix-4GL.
Can anyone give me advice on a better way to achieve a similar result?
In order to use Java effectively you need to use custom objects. What you have here is a lot of static methods inside a class. It seems that you are coming from a procedural background and if you try to use Java as a procedural language, you will not much value from using it. So first off create a type, you can plop it right inside your class or create it as a separate file:
class User
{
final int id;
final String name;
final String info;
final String extra;
User(int id, String name, String info, String extra)
{
this.id = id;
this.name = name;
this.info = info;
this.name = name;
}
void print()
{
System.out.println(id + name + info + extra);
}
}
Then the loop becomes:
List<User> list = new ArrayList<User>();
try {
users_sel.setInt(1, 1);
users_curs = users_sel.executeQuery();
// RETRIEVE ROWS FROM USERS
while (users_curs.next()) {
int lv_u_id = users_curs.getInt("u_id");
String lv_u_name = users_curs.getString("u_name");
uinfo_sel.setInt(1, lv_u_id);
uinfo_curs = uinfo_sel.executeQuery();
// RETRIEVE DATA FROM UINFO RELATIVE TO USER
String lv_ui_info = uinfo_curs.getString("ui_info");
String lv_ui_extra = uinfo_curs.getString("ui_extra");
User user = new User(lv_u_id, lv_u_name, lv_ui_info, lv_ui_extra);
// STORE DATA
list.add(user);
}
} catch(SQLException log) {
// EVERYTHING BROKE
}
// MAKING SURE IT WORKED
list.get(0).print();
This doesn't necessarily address the number of lines. Most people who use Java don't interact with databases with this low-level API but in general, if you are looking to get down to the fewest number of lines (a questionable goal) Java isn't going to be your best choice.
Your code is actually quite close to box stock JDBC.
The distinction is that in Java, rather than having a discrete collection of arrays per field, we'd have a simple Java Bean, and a collection of that.
Some examples:
public class ListItem {
Integer id;
String name;
Integer info;
String extra;
… constructors and setters/getters ellided …
}
List<ListItems> items = new ArrayList<>();
…
while(curs.next()) {
ListItem item = new ListItem();
item.setId(curs.getInt(1));
item.setName(curs.getString(2));
item.setInfo(curs.getInfo(3));
item.setExtra(curs.getString(4));
items.add(item);
}
This is more idiomatic, and of course does not touch on the several frameworks and libraries available to make DB access a bit easier.
I improved the structure after a good observation from [http://stackoverflow.com/users/1690199/v-k] I am still getting a token error even though the syntax looks correct to me. More comments and critiques will be useful and acknowledged here.
import de.bezier.data.sql.*;
PostgreSQL pgsql;
Float val;
void setup()
{
size( 100, 100 );
println(val);
}
Token error identified in Processing 2 at Class Database.
Class Database
{
String user = "user";
String pass = "pass";
String database = "db";
Float val;
Database (Float col) {
val = col;
}
void database_connection( col )
{
//sets up database
pgsql = new PostgreSQL( this, "127.0.0.1", database, user, pass );
if ( pgsql.connect() )
{
pgsql.query( "SELECT col FROM table ORDER BY col DESC LIMIT 1; " );
return( pgsql.getFloat("col") );
}
else
{
println ("failed to connect to the database");
}
}
}
OLD ISSUE: Class structure addressed after a great observation from [http://stackoverflow.com/users/1690199/v-k]
import de.bezier.data.sql.*;
.....
.....
Old code removed for clarity of this issue.
Classes don't take arguments. Also it is class not Class... Am i missing something? Look, a general sample:
class Database {
String user = "user";
String pass = "pass";
String database = "db";
float val; //by convention no Caps for vars...
// a constructor, which get partameters
Database (float v) {
val = v;
}
// a method
void database_setup() {
//whateverq
}
}//end of Database class
First, you should create a new question if you have a second question. Second, you never create the variable pgsql, you just start using it immediately. Move this line:
PostgreSQL pgsql;
to this group of lines:
String user = "user";
String pass = "pass";
String database = "db";
float val;
It's a variable that gets used in that class, so put it in that class. Also, use "float" with a lowercase "f" :)
I am using Eclipse. I am trying to make a program that doesn't contain a main function, but will still print Hello, World:
public class Q
{
static
{
System.out.println("Hello World");
System.exit(0);
}
}
But this program is not giving me expected result.An error is coming which says that main method is not found in class Q. Where I am making a mistake?
You still need to run the program for the static initialization block to execute, which you cannot do without an appropriate main method (as of Java 71). Now, that's not to say main needs to actually contain any code:
class Q {
static {
System.out.println("Hello World");
System.exit(0);
}
public static void main(String[] args) {}
}
1 Your code actually works in Java 6 and below - you don't need a main method. This is because the static initialization block executes before a main method is searched for. But, in your case, you exit the program at the end of that block with System.exit(0), and so Java never looks for main and you don't receive an error.
Every Java Application Program must contain a class with main method in it. So your error will persist until you declare a main method inside one of the classes in your program.
It is impossible. Your program MUST contain the main method, or the system doesnt know witch piece of code to run.
Your mistake is that you are trying to run class that does not have main method (exactly as you explained).
JVM is looking for public static void main method that accepts array o String as an argument as an entry point to any program.
"Java programs start executing at the main method, which has the
following method heading:
public static void main(String[] args)"
(http://en.wikipedia.org/wiki/Main_function#Java)
You should alter your class to be something similar to what I've put below.
public class Q
{
public static void main(String[] args)
{
System.out.println("Hello World");
System.exit(0);
}
}
import java.sql.*;
import java.io.*;
import javax.sql.*;
public class Emsa
{
public static void main(String args[])
{
int ch;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:orcl","hr","hr");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from Empdirc");
while(rs.next())
do
{
System.out.println("\n");
System.out.println("ENTER EMPLOYEE DETAILS:");
System.out.println("1.Insert Record into the Table");
System.out.println("2.Update The Existing Record.");
System.out.println("3.Display all the Records from the Table");
System.out.println("4.Check PRIVILAGE LEAVE and Casual Leaves");
System.out.println("5.Exit");
System.out.println("Enter your choice: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
System.out.println("1.INSERT EMPLOYEE ID.");
int num= Integer.parseInt(br.readLine());
System.out.println("2.INSERT EMPLOYEE NAME");
String ename=br.readLine();
System.out.println("3.INSERT EMPLOYEE DESIGNATION");
String desig=br.readLine();
System.out.println("4.INSERT EMPLOYEE DATEOFBIRTH");
String dob=br.readLine();
System.out.println("5.INSERT EMPLOYEE PHONE NO OR ANY CONTACT");
String mob= br.readLine();
System.out.println("6.INSERT EMPLOYEE EMAIL ID");
String email= br.readLine();
System.out.println("7.INSERT EMPLOYEE SALARY");
String sal=br.readLine();
System.out.println("8.INSERT EMPLOYEE paid LEAVES");
String pl=br.readLine();
System.out.println("9.INSERT EMPLOYEE CASUAL LEAVES");
String cl=br.readLine();
System.out.println("10.INSERT EMPLOYEE FINAL SALARY");
String fi= br.readLine();
System.out.println("11.STATUS");
String s=br.readLine();
String sql="insert into EmpDirc values(?,?,?,?,?,?,?,?,?,?,?)";
PreparedStatement p=con.prepareStatement(sql);
p.setInt(1,num);
p.setString(2,ename);
p.setString(3,desig);
p.setString(4,dob);
p.setString(5,mob);
p.setString(6,email);
p.setString(7,sal);
p.setString(8,pl);
p.setString(9,cl);
p.setString(10,fi);
p.setString(11,s);
public static boolean abcd(String str)
{
int x;
for(int mob= 0 ; mob < str.length() ; mob++)
{
x = (int)str.charAt(mob);
if( x < 10 || x > 0)
return false;
}
return true;
}
p.executeUpdate();
System.out.println("Record Added");
//p.close();
//con.close();
break;
case 2:
System.out.println("UPDATE EMPLOYEE id : ");
int emnum=Integer.parseInt(br.readLine());
System.out.println("UPDATE EMPLOYEE DESIGNATION : ");
String emdesig=br.readLine();
System.out.println("UPDATE EMPLOYEE PHONE: ");
String emphn=br.readLine();
System.out.println("UPDATE EMPLOYEE EMAIL: ");
String emmail=br.readLine();
System.out.println("UPDATE EMPLOYEE SALARY: ");
String emsal=br.readLine();
System.out.println("UPDATE EMPLOYEE PL: ");
String empl=br.readLine();
System.out.println("UPDATE EMPLOYEE CL: ");
String emcl=br.readLine();
System.out.println("UPDATE EMPLOYEE FINAL SALARY: ");
String emfi=br.readLine();
sql="update EmpDirc set Desig=?, Mob=? , Email=?, Sal=? , fi=? where Eid=?";
PreparedStatement ps=con.prepareStatement(sql);
ps.setString(1,emdesig);
ps.setString(2,emphn);
ps.setString(3,emmail);
ps.setString(4,emsal);
//ps.setString(5,empl);
//ps.setString(6,emcl);
ps.setString(5,emfi);
ps.setInt(6,emnum);
ps.executeUpdate();
System.out.println("Record Updated");
//p.close();
//con.close();
break;
case 3 : System.out.println("Displaying the Data ");
//Statement stmt=con.createStatement();
ResultSet res=stmt.executeQuery("select * from Empdirc");
while(res.next())
System.out.println("Eid"+res.getInt(1)+"Ename "+res.getString(2)+"Design "+res.getString(3)+"Dob "+res.getString(4)+"Mobile no."+res.getString(5)+"Email "+res.getString(6)+"Salary "+res.getString(7));
break;
case 4 : System.out.println("CALCULATING");
sql="update EmpDirc set Pl=?, Cl=? where Estatus=?";
PreparedStatement pes=con.prepareStatement(sql);
pes.setInt(1,15);
pes.setInt(2,07);
pes.setString(3,"permanent");
pes.executeUpdate();
System.out.println("Record Updated");
case 5:
System.exit(0);
break;
default:
System.out.println("Invalid Choice");
break;
}
}while(ch!=2);
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}