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);
Related
I am trying to get the value of string in the first class and use it to another class. Below is my code :
public class Add extends driver {
public static String reportV1;
#Test
public String export() throws InterruptedException, IOException {
// Report Name
WebElement report1 = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#nReportName")));
reportV1 = report1.getAttribute("value");
if (reportV1.equals(reportV)) {
System.out.println(" PASSED - Report Name: " + reportV1);
} else {
System.out.println(" FAILED - Report Name: " + reportV1);
soft.assertTrue(false);
}
soft.assertAll();
return reportV1;
I'm new to java, so can someone help me to get the value of string?
Thank you in advance.
I think you should read about static fields first to get clear picture about this thing.
Anyway, static variables can be accessed by calling with the class name ClassName.VariableName.
Add.reportV1 in your case. Btw in your example reportV1 is not initialized yet, fyi.
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
Problem (small concise version): I have a jar file that I can edit, but I want to make a method, in a specific class in that jar to call another class that will be under another jar.
The idea is that the existing.jar would only have the method call the external.jar and the external.jar would return a value to the existing.jar in order to continue its processing.
Problem (long detailed version): I use p6spy to capture the sqls that my application generates but I need to filter that sql to a very specific level, not only the function "sqlExpression" of p6spy does not work as even if it did it would not be sufficient.
I currently have decompiled (I did not find the sources of the project, and yes, it is an open source project) p6spy and edited the formattedlogger.class in order to suit my need.
My problem is, this is a "solution" that many people will have to use and the filter that I applied is not enough to some and to other simply doesnt work because they need something I need excluded.
I did a bit of research and decided that I should take the adapter route, I decided that the p6spy.jar will remain untouched, but it will call a class from another jar file which will then contain the specificity of the filter.
But I do not know how to do that. :(
Scenario:
OS: CentOS release 6.4 (Final)
Which most likely is a virtual machine.
Application Server: jboss-4.3.0.GA
Which contains multiple instances under the server folder.
I have the p6spy.jar under the app_server/server/instance/lib
I understand that I will have to have the adapter under the same folder.
Does anyone have any idea how this should be done, where I could read about such things or how I should proceed, maybe a different solution or perhaps another idea.
I'm open to suggestions.
*Edit 1:
I have a p6spy.jar file which contains a class that I edit to suit my needs. (FormattedLogger.class)
the class is at it follows:
package com.p6spy.engine.logging.appender;
public abstract class FormattedLogger
{
protected String lastEntry;
public void logSQL(int connectionId, String now, long elapsed, String category, String prepared, String sql)
{
String logEntry = now + "|" + elapsed + "|" + ((connectionId == -1) ? "" : String.valueOf(connectionId)) + "|" + category + "|" + prepared + "|" + sql;
logText(logEntry);
}
public abstract void logText(String paramString);
public void setLastEntry(String inVar)
{
this.lastEntry = inVar;
}
public String getLastEntry() {
return this.lastEntry;
}
}
I need it to look something like this:
package com.p6spy.engine.logging.appender;
public abstract class FormattedLogger
{
protected String lastEntry;
public void logSQL(int connectionId, String now, long elapsed, String category, String prepared, String sql)
{
sql = method_in_another_class_and_in_other_jar_file(sql);
logText(sql);
}
public abstract void logText(String paramString);
public void setLastEntry(String inVar)
{
this.lastEntry = inVar;
}
public String getLastEntry() {
return this.lastEntry;
}
}
this "method_in_another_class_and_in_other_jar_file(sql)" would, as the name says, be outside this jar, in order to be easly edited and such.
The issue has not been solved (yet) but the replies have been of great help.
Jim Harrison suggested bytecode modification as a solution, unfortunately that is not the path I'll take.
markbernard got the source files # sourceforge.net/projects/p6spy/files/p6spy and I'll re-write the driver/software to fit my scenario.
Thank you all for the help. :D!
I have a question regarding structuring of code.
I have let us say three types of packages A,B and C.
Now, classes in package A contains classes which contain the main() function. These classes
need some command line arguments to run.
In package B, there are classes which contains some public variables, which need to be configured, at different times. For example before calling function A, the variable should be set or reset, the output differs according to this variable.
In package C, uses the classes in package B to perform some tasks. They do configure their variables as said before. Not only when the object is created, but also at intermediate stage.
Package A also has classes which in turn use classes from package B and package C. In order to configure the variables in classes of B and C, class in package A containing the main() function, reads command line arguments and passes the correct values to respective class.
Now, given this scenario, I want to use Apache Commons CLI parser.
I am unable to understand how exactly I should write my code to be structured in an elegant way. What is a good design practice for such scenario.
Initially I wrote a class without Apache to parse the command line arguments.
Since I want a suggestion on design issue, I will give an excerpt of code rather than complete code.
public class ProcessArgs
{
private String optionA= "default";
private String optionB= "default";
private String optionC= "default";
public void printHelp ()
{
System.out.println ("FLAG : DESCRIPTION : DEFAULT VALUE");
System.out.println ("-A <Option A> : Enable Option A : " + optionA);
System.out.println ("-B <Option B> : Enable Option B : " + optionB);
System.out.println ("-C <Option C> : Enable Option C : " + optionC);
}
public void printConfig()
{
System.out.println ("Option A " + optionA);
System.out.println ("Option B " + optionB);
System.out.println ("Option C " + optionC);
}
public void parseArgs (String[] args)
{
for (int i=0;i<args.length;i++)
{
if (args[i].equalsIgnoreCase ("-A"))
optionA = args[++i];
else if (args[i].equalsIgnoreCase ("-B"))
optionB = args[++i];
else if (args[i].equalsIgnoreCase ("-C"))
optionC = args[++i];
else
throw new RuntimeException ("Wrong Argument : " + args[i] + " :: -h for Help.");
}
}
}
Points to note -
I already have 50+ command line options and they are all in one place.
Every class uses only a group of command line options.
I tried to write an interface, somehow but I am unsuccessful. I am not sure if this is a good way to do it or not. I need some design guidelines.
Here is the code which I wrote -
public interface ClassOptions
{
Options getClassOptions();
void setClassOptions(Options options);
}
public class Aclass implements ClassOptions
{
private String optionA="defaultA";
private String optionB="defaultB";
public Options getClassOptions()
{
Options options = new Options();
options.addOption("A", true, "Enable Option A");
options.addOption("B", true, "Enable Option B");
return options;
}
public void setClassOptions(Options options, String args[])
{
CommandLineParser parser = new BasicParser();
CommandLine cmd=null;
try
{
cmd = parser.parse( options, args);
} catch (ParseException e)
{
// TODO Auto-generated catch block
// e.printStackTrace();
System.out.println("ignored option");
}
if(cmd.hasOption("A"))
optionA = "enabled";
if(cmd.hasOption("B"))
optionB = "enabled";
}
}
I think the problems in such writing of code are -
There are different types of arguments like int, double, string, boolean. How to handle them all.
getClassOption() and setClassOption() both contain the arguments "A", "B" for example. This code is prone to errors made while writing code, which I would like to eliminate.
I think the code is getting repetitive here, which could be encapsulated somehow in another class.
Not all the arguments are required, but can be ignored.
Thank You !
I would recommend to you JCommander.
I think it's a really good Argument Parser for Java.
You define all the Argument stuff within annotations and just call JCommander to parse it.
On top of that it also (based on your annotations) can print out the corresponding help page.
You don't have to take care about anything.
I believe you will love it! :)
Take a look at it: http://jcommander.org/
There are a lot of examples and such!
Good Luck! :)
simple example for command line argument
class CMDLineArgument
{
public static void main(String args[])
{
int length=args.length();
String array[]=new String[length];
for(int i=0;i<length;i++)
{
array[i]=args[i];
}
for(int i=0;i<length;i++)
{
System.out.println(array[i]);
}
I am creating a prison system where I need to store the names and because I need to print out all the prisoner information in one of the methods. I want to make it remember and store information such as name, id and crimes etc. How can I go about doing this?
About the posted answers, I don't think it needs to be something that complicated because I haven't learnt any of this for the assignment. All I want is for my program to print out the prisoner ID, name, starting and ending date, crime with just one run of the program after I am prompted to enter the information.
INPUT/OUTPUT
New Prisoner
Enter Name:
Enter crime:
Enter Name:
Enter crime:
Prisoner information
(name) has committed (crime)
(name) has committed (crime)
The short answer is "a database."
Your question indicates that the following could be overwhelming but it could be worth some effort to read about "Macto," an end-to-end sample Ayende Rahein has been writing about.
You haven't made particularly clear in your question as to whether you just want to store the prisoner details in memory while the program is running, or if you want to persist the prisoners to disk, so that you can close your program and load them again next time you start it.
If its the former, you can just store the prisoners in an array or a list. For example assuming your prisoner class looks something like this:
public class Prisoner {
private String name;
private String crime;
public Prisoner(String name, String crime) {
this.name = name;
this.crime = crime;
}
public String getName() {
return name;
}
public String getCrime() {
return crime;
}
}
You can then store the prisoners in a list...
List<Prisoner> prisoners = new LinkedList<Prisoner>();
prisoners.add(new Prisoner("Bob", "Murder"));
prisoners.add(new Prisoner("John", "Fraud"));
...and then iterate over the list and print the details out...
for(Prisoner p : prisoners) {
System.out.println(p.getName() + " committed " + p.getCrime());
}
If you're looking for a way to persist the prisoner details between runs of the program there are a number of possible approaches, most of which have already mentioned. In most cases a database is the best solution for storing records with JDBC being the simplest way of connecting to and interacting with a database.
For simplicity however, I would suggest storing the details in a CSV (comma separated value) file. A CSV file is simply a plain text file that stores each record on a new line, with a comma separating each field. For example:
Bob, Murder
John, Fraud
There are a number of CSV reading libraries around (see here), however its quite easy to read + write to a CSV file with no external libraries. Below is an example:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
public class PrisonerStore {
/**
* The file the prisoners are stored in
*/
private File store;
public PrisonerStore(File store) {
this.store = store;
}
/**
* Saves the specified prisoner to the file
* #param prisoner
*/
public void savePrisoner(Prisoner prisoner) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter(store, true));
writer.write(prisoner.getName() + "," + prisoner.getCrime());
writer.newLine();
writer.close();
}
/**
* Reads all prisoners from the file and returns a list of prisoners
* #return
*/
public List<Prisoner> loadPrisoners() throws IOException{
List<Prisoner> prisoners = new LinkedList<Prisoner>();
BufferedReader br = new BufferedReader(new FileReader(store));
//Read each line of the file and create a Prisoner object from it
String line = null;
while((line = br.readLine()) != null) {
String[] parts = line.split(",");
Prisoner p = new Prisoner(parts[0], parts[1]);
prisoners.add(p);
}
br.close();
return prisoners;
}
}
In your code you can then do something like the following:
PrisonerStore store = new PrisonerStore(new File("C:\\myFile.csv"));
Prisoner p1 = new Prisoner("Bob", "Murder");
Prisoner p2 = new Prisoner("John", "Fraud");
try {
store.savePrisoner(p1);
store.savePrisoner(p2);
List<Prisoner> list = store.loadPrisoners();
for(Prisoner p : list) {
System.out.println(p.getName() + " committed " + p.getCrime());
}
} catch (IOException e) {
System.out.println("Error storing prisoners");
}
If these informations need to persist beyond the life of the VM, you'll have to write them on a physical storage (actually, persistence is the mechanism that allow to pass from a physical storage to an in memory representation).
There are several solutions for this purpose:
Java Object Serialization
A prevalent system with a library like Prevalayer
XML serialization with a library like XStream
A database (relational or not)
Serialization is Java built-in persistence mechanism but is very fragile. Prevalence is based on serialization but I have no experience with it and I'm not sure it solves the weakness of serialization. XML serialization is interesting and quite fast to put in place, especially with a library like XSteam. Finally, a database is the most "standard" solution but introduces some complexity. Depending on your needs, use straight JDBC or JPA for the data access.
My advice: If you don't need a database, go for XML serialization and use XStream. See the Two Minute Tutorial on XStream web site to get started. If you don't need persistence at all (beyond the life of the VM), just store the prisoners in a List.
Where do you want store information ?
If you want store information in program (memory), you can use a static member variables,like this:
// Prisoner.java
class Prisoner {
public String Name;
public int Age;
}
// Prisoners.java
class Prisoners {
public static Prisoner[] GetAll() {
Prisoner[] _data;
// Load from database to _data;
return _data;
}
}
// test.java
class test() {
public static void out() {
System.out.println(main.allPrisoner.getLength());
}
}
// main.java
public class main{
public static Prisoner[] allPrisoner;
public static main(String args[]){
public allPrisoner = Prisoners.GetAll();
// From now all prisoners will be stored in program memory until you close it
}
}
So, If you are Web Development, you can use WebCache
If you are looking to use a database, one place to start is with Hibernate. Its a java library that can provide java object to relational database table mapping.
If you want to persist to a file system using an object serialization routine, I'd recommend XStream to serialize XML or JSON text.
Based on the added text to the question, I'd recommend having a look at XStream just because it is so simple to use if you need to get the data structures to a file on the disk. However, more basically...
You probably just need to make a Prisoner class that has the stuff you need Prisoner to have, such as a name, identifier, etc, etc.
public class Prisoner
{
private String name;
private int identifier;
public Prisoner(String aName, int anId)
{
name = aName;
identifier = anId;
}
public String toString()
{
return "Prisoner[ name = " + name + ", id = " + identifier + " ]";
}
}
Then you can store them in a Map<String, Prisoner> to make finding them easier.
Map<String, Prisoner> prisonMap = new HashMap<String, Prisoner>();
To enter them in from the command line, you'll probably need to use System.in
Sun provides a good tutorial for it.
If you just want to print them back out on the command line, you'll iterate over the Map's keyset and get each value or just iterate over the values and just use System.out.println() to print them out.
for(Prisoner p : prisonMap.values())
{
System.out.println(p);
}
Or, use XStream to print out the XML to file or the System.out stream.