Sorry about to ask for it, but I'm really noob at Java. When we call for showWindow...
public static String checkList;
public static String getCheckList(){
return checkList;
}
public static void setCheckList(String queryToSelect){
checkList = queryToSelect;
}
public static void showWindow(User user)
{
if (!checkConditions(user))
return;
String msg;
String queryToSelectshow;
if (user.getNetConnection().getBonus() > 0.)
{
msg = main(user);
queryToSelectshow = "SELECT * FROM prodlist WHERE canUse = 1 ORDER BY description ASC, id";
}
else
{
msg = main(user);
queryToSelectshow = "SELECT * FROM prodlist WHERE canUse = 2 ORDER BY description ASC, id";
}
setCheckList(queryToSelectshow);
showCommunity(user, msg);
}
If user has bonus then queryToSelectshow 1 else queryToSelectshow 2, but If I run this with user with bonus this set queryToSelectshow 1 and when I run with user with no bunus this still in queryToSelectshow 1 and need to be queryToSelectshow 2.
Is this caused by the "static" function? I tried to do without Static, but when I try to do It the eclipse shows me a lot of error messages!
Thank you for help and your time!
Well... there is a lot of code that we can't see, but I would recommend you to log the value from "user.getNetConnection().getBonus()" before getting in the if. Or if you don't have any loging system, just show it with System.out.println(user.getNetConnection().getBonus())
In that way, you can get sure from that the value that you are getting is really going to be more than 0.
Also, if you are using an IDE, learn to debug your code. Making a quick search, for Eclipse for example:
Debug Eclipse
Also... are you really needing all those methods to be static? I will suppose that you are doing it because, if not, you can't call them from the main method. In that case, you can create a new object from the same class:
MyObject object = new MyObject();
and then call the non static methods:
object.nonStaticMethod();
I would recommend you to try to understand what does it mean for a method to be static (and for variables also!!!) :
Understanding Class Members
Related
I am new to java and have been set a task to create a class called Manual along with some properties shown in the question below:
"1. Design a class Manual with the following properties:
serial number - string, - default:??????
title - string, - default: Untitled
author - string, - default: Unknown
Write a constructor and a method to print details of a Manual on the console.
"
I have been working on this task and so far I have this:
public class Manual {
String serialNumber, title, author;
public Manual(){
serialNumber = "??????";
title = "Untitled";
author = "Unknown";
}
}
Would anyone be able to let me know if my working so far is correct and also how I might be able to complete the last line referring to a constructor / print method.
Thank you
Other than that print, you need to have a main method to run.
public class Manual {
String serialNumber, title, author;
public Manual(){
serialNumber = "??????";
title = "Untitled";
author = "Unknown";
}
public void printDetails(){
System.out.println("S.no= " +serialNumber+" Title= "+ title+"author= "+author)
}
public static void main(String [] args){
Manual man= new Manual();
man.printDetails();
}
}
Edit after comment:
I just tried to give a mock code and , you must aware of the access modifiers to your members in the class. This is what your actual task. Learn them and experiment with them.
I wrote a small tutorial on the same, try to read and understand.
Default access modifier in Java (or) No access modifier in Java
Good luck.
You are correct so far. For the printing you should use
System.out.println("Manual details : ");
System.out.println("Serial Number : "+serialNumber);
System.out.println("Author : "+author);
System.out.println("Title : "+title);
I have to display the current user into the gui, but it keep saying the the hashset is empty, this has been bugging me for hours. What is the easiest way to fix this? There might be a lot of un used code as i was testing things trying to make it work.
Client.java
public class Client {
Server.names();
}
Server.java
public class Server {
public static HashSet<String> names = new HashSet<String>();
public static void main(String[] args) throws Exception{
while(true){
name = in.readLine();
if(name == null){
return;
}
if(!names.contains(name)){
names.add(name);
break;
}
}
}
}
Your Q is a bit unclear, but if you want to get the HashSet, names from your Server class, you need to get the reference to it by calling Server.name, not Server.name() as it is not a method.
Now names will be empty until you populate it. To populate it you need to call code that will read user input and store it in names. In this case you can call the main method of Server (see this related Q here) but unless you really want that to be your main method of Server, I would recommend renaming the method to populateNames() or something similar.
I have a java database successfully connected to my java code. Thats all fine as it works and all.
When I store a result from the database into a variable ... it works perfectly.
Now as I have to do this 8 times I used a loop and a array however by using a try catch tool it gives out a error of, Error is: java.lang.NullPointerException
Futher investigation shows that it seems to not like the loop strangely.
public String Title []; //in class but out of any methods
public void gettinginfo ()
{
try
{
int AB = 0; //array base starts from 0
//ID in database starts from 1
for (int i = 1; i<=8; i++)
{
String query = "SELECT * FROM students WHERE ID = " + i;
Rs = St.executeQuery(query);
while (Rs.next())
{
Title[AB] = Rs.getString("StudentName");
AB++;
}
}
}
catch (Exception ex)
{
System.out.println("Error is: " + ex);
}
}
What line is your NullPointerException occurring on? Likely your Title array has not been initialized. If you know how many rows the query will return, you can say:
Title = new String[numRows];
But if you don't, you'll need to either run a SELECT count(*) ... query or use an ArrayList or other resizable list, instead of an array.
Your code is also very poorly structured, which is no small part of why you're having trouble debugging this. I've cleaned up your code below, with comments explaining my changes:
public class YourClass
{
private static final int MAX_ID = 8; // or however you want to set the size
private String[] title; // [] after the type is easier to read, lower case variables
private Connection conn; // I'm assuming the class will be provided a DB connection
// Note the Statement and ResultSet objects are not defined in the class, to
// minimize their scope.
public void queryInfo() // name suggests a query (potentially expensive) will be run
{
title = new String[MAX_ID]; // **initialize title**
// We use a try-with-resources block to ensure the statement is safely closed
// even better would be to use a PreparedStatement here
try(Statement st = conn.statement())
{
// You're executing 8 separate queries here, where one will do
String query = "SELECT * FROM students WHERE ID >= 1 AND ID <= "+MAX_ID;
// Again, we need to close the result set when we're done
try(ResultSet rs = st.executeQuery(query))
{
int i = 0;
while (rs.next())
{
title[i++] = rs.getString("StudentName");
}
} // close our ResultSet
} // close our Statement
}
// provide a separate getter method, rather than making the array public
public String[] getTitles()
{
return title;
}
}
There's still more that could be improved - using an array seems like a poor design, as does calling a method which populates a class variable rather than simply having queryInfo() return a new array. You can also look into using PreparedStatement. Hopefully these suggestions help.
Make sure that Title array and Statement St objects are and not null. These are the only two reasons that I suspect. Give FULL stacktrace if it doesn't work.
Title array is NULL. "new" this array to the size equal to number of rows. If you don't know the rows, fire a count(*) query first, find out the no of rows and then intantiate Title array or use ArrayList<String> instead of String array.
I am assuming that you have not initialized your Title array, you have to set it equal to something or it will just be null which will cause a nullPointerException, but as others have stated there is no way to be sure since your haven't given us a full stack trace or even the line number of the exception. In this case the exception should be handled as such:
try{
//your code here
}catch(Exception ex){
ex.printStackTrace();
}
This code will give you the full stack trace making it much easier to track down the issue.
Also you may want to consider using an ArrayList instead of an array:
List<String> Title = new ArrayList<String>();
Then to add to it:
Title.add(Rs.getString("StudentName"));
If you need it as an array later then:
String[] title = Title.toArray(new String[Title.size()]);
You can read more about ArrayLists here.
i have created a custom console for a program. I have a method that adds a message to the console called toConsole this asks for the string where it checks and adds the time to the string. it then goes to my function addConsole which checks if existing text is present if so it will then add the pre-existing text to the new text, else it just puts the new text in. so here is the error. i may also point out that if i enter text manually on the consoles input text box it does not produce this error.
Exception in thread "main" java.lang.NullPointerException
at com.michael.tech.api.console.RunConsole.addConsole(RunConsole.java:188)
at com.michael.tech.api.console.RunConsole.toConsole(RunConsole.java:204)
at com.michael.tech.api.console.RunConsole.toConsole(RunConsole.java:223)
at com.michael.tech.api.testerFile.main(testerFile.java:25)
here is the addConsole method
private static void addConsole(String s){
console.setText( ( console.getText().isEmpty()) ? s : (console.getText() + "\n" + s) );
}
the toConsole method
public static void toConsole(String s, boolean timeStamp, boolean classPath, String className){
if(s.startsWith("/")){
doCommand(s);
return;
}
Time t = new Time();
t.getSYSPrint();
String time = "[" + t.toMilitary() + "] ";
if(EchoTime || timeStamp){
addConsole(time + s);
}
else if(classPath){
addConsole(className);
}
else{
addConsole(s);
}
}
and lastly the Main method in testerFile class
public static void main(String[] args) {
RunConsole.startConsole();
RunConsole.toConsole("test");
}
Thanks in advance for any help. I assume it is some small mistake i overlooked (I hope too).
EDIT:
paste bin to see line numbers
RunConsole class
http://pastebin.com/2yUAwQc5
testerFile class
http://pastebin.com/R5ViLekp
The problem is that the JTextArea console still has its default null value as it has not been instantiated. This is because there is no instance of RunConsole created — Instead, you are accessing the methods of this class in a static way:
RunConsole.startConsole();
RunConsole.toConsole("test");
Using static methods is poor design especially since your application needs to have state. Make all static methods in RunConsole instance methods and replace the above lines with:
RunConsole runConsole = new RunConsole();
runConsole.startConsole();
runConsole.toConsole("test");
Also, when you do this, don't forget to remove your instance created in startConsole, otherwise you will not see the initial message from toConsole. Change:
new RunConsole().setVisible(true);
to
setVisible(true);
hi
I have one class,and in that class I have one method as follows:
I am using java.
public class ABC{
some code here...
..................
PreparedStatement pre;
public void insertUser(String firstName,String lastName){
pre.setString(1,firstName);
pre.setString(2,lastName);
pre.execute();
}
}
for above method I want to write the test case,I have created the test class as follows:
public class ABCTest{
ABC abc=new ABC();
public void testInsertUser(){
now here I want to write the assert statement,I want test whether insert is successful,
I want to test the method variable using assert(). Please tell me how to write test case for this in java.
You need to do something like these:
Check the count of rows before and after the INSERT and assert that the after count is one greater than the before count.
Do a SELECT and see if your row made it into the database.
Check the number of rows affected that is returned by the call and see that it equals one.
probably you have along with your 'insertUser' method other methods like 'selectUser' and 'removeUser' so in your testCase you should use 'selectUser' method to be sure that your user appear in DB, also in the end you should call 'removeUser' cause after the tests you should keep your data clean as it was before (for tests to be able to run multiple times on same test data with same results).
do you mean something like:
public void testInsertUser(){
ABC.insertUser(User.firstname, user.lastname);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT firstname_Colname, lastname_Colname FROM Your_Table");
boolean found = false;
while (rs.next())
{
found = ((User.firstname = rs.getString("firstname_Colname")) and (User.lastname = rs.getString("lastname_Colname")));
if (found)
{
break;
}
}
assertEquals('test failed!', true, found);
}
if yes you are actually testing the PreparedStatement which doesnt make any sense for me!