This is my whole code, it's quite complex but please help me. It's taken me for 2 days but I failed:
public static ArrayList<DocGia> XuatDocGia() throws IOException {
ArrayList<DocGia> listDocGia = new ArrayList<>();
File fileDocGia = new File("fileDocGia.txt");
if(fileDocGia.exists() == false) {
System.out.println("Chưa có đọc giả nào trong thư viện");
} else {
BufferedReader br = new BufferedReader(new FileReader("fileDocGia.txt"));
if (br.readLine() == null) {
System.out.println("Chưa có đọc giả nào trong thư viện");
} else {
int soDong = DemSoDong("fileDocGia.txt");
int dongHienTai = 0;
Scanner fileScanner = new Scanner(fileDocGia);
for(int i = 0, z = 0;;i++, z++) {
DocGia docGia = null;
System.out.println("***Đọc giả thứ: " + (i+1));
docGia.tendocgia = fileScanner.nextLine();
if(i >= 1) {
docGia.tendocgia = fileScanner.nextLine();
}
docGia.maDocGia = fileScanner.nextLine();
docGia.soSachmuon = fileScanner.nextInt();
docGia.thoiGianMuonSach = fileScanner.nextInt();
listDocGia.add(docGia);
docGia.XuatDocGia();
dongHienTai += 4;
if(dongHienTai == soDong) {
fileScanner.close();
break;
}
}
}
for(DocGia docGia: listDocGia) {
docGia.XuatDocGia();
}
}
return listDocGia;
}
look at my code, when i run:
docGia.XuatDocGia();
-> the value of every single element is right at debug. it also means the value of the variable inside is right. but at the end of this function. i run
for(DocGia docGia: listDocGia) {
docGia.XuatDocGia();
}
this is XuatDocGia funtion:
public static void XuatDocGia(){
System.out.println(tendocgia);
System.out.println(maDocGia);
System.out.println(soSachmuon);
System.out.println(thoiGianMuonSach);
}
It just shows for me the last element in this ArrayList, repeat in 3 times( equal the number of elements).
I think a problem come from adding process of listDocGia.add(docGia);
You guys no need to bother everything else in my code, because i know it's really complex. I have tested carefully, just focus on my problem.
I'm so sorry because i'm Vietnamese and beginner at Java. The next time everything will be English. Thank you so much.
If this is the actual code, you are adding null references to your List, but since you are using a static method to print the values, you don't get a NullPointerException. Assuming your code passes compilation, this means all the members of the DocGia class are static, which explains why you get the same values in each iteration of your loop.
You should change
DocGia docGia = null;
to
DocGia docGia = new DocGia ();
and change all the members of DocGia (including the XuatDocGia method that prints them) to be non static.
Related
im starting my adventure with learning to code in Java. Im stuck on an example from book. It does compile but there is no effect when I run it. The output is just blank. Im using Visual studio code. The example says that all 3 separate files (ProstyPortal, ProstyPortalGra & PomocnikGry) should be in 1 folder. When i try to start a file with main also nothing happens. I decided to join them all into one file but still i do get no result. The code is basically one line battleship game example.
ftp://ftp.helion.pl/przyklady/javrg2.zip - in folder r05 there are files (ProstyPortal, ProstyPortalGra & PomocnikGry) from the example that should work when in the same folder but they dont.
Damn, its really hard to find whats wrong when you just start learning :P
Its an example from chapter nr 5.
I did follow all the rules and sugestions as in the book but even a straight copying the code does not help. the previous examples i did run without bigger issues.
import java.io.*;
class ProstyPortalGra {
public static void main(String[] args) {
int iloscRuchow = 0;
PomocnikGry pomocnik = new PomocnikGry();
ProstyPortal portal = new ProstyPortal();
int liczbaLosowa = (int) (Math.random() * 5);
int[] polozenie = {liczbaLosowa, liczbaLosowa+1, liczbaLosowa+2};
portal.setPolaPolozenia(polozenie);
boolean czyIstnieje = true;
while (czyIstnieje == true) {
String pole = pomocnik.pobierzDaneWejsciowe("Podaj liczbę");
String wynik = portal.sprawdz(pole);
iloscRuchow++;
if (wynik.equals("zatopiony")) {
czyIstnieje = false;
System.out.println(iloscRuchow + " ruchów");
} // koniec if
} // koniec while
} // koniec main
}
class ProstyPortal {
int [] polaPolozenia;
int iloscTrafien;
public void setPolaPolozenia(int[] ppol) {
polaPolozenia = ppol;
}
public String sprawdz(String stringPole) {
int strzal = Integer.parseInt(stringPole);
String wynik = "pudło";
for (int pole : polaPolozenia) {
if (strzal == pole) {
wynik = "trafiony";
iloscTrafien++;
break;
}
} // koniec pętli
if (iloscTrafien == polaPolozenia.length) {
wynik = "zatopiony";
}
System.out.println(wynik);
return wynik;
} // koniec metody
} // koniec klasy
class PomocnikGry {
public String pobierzDaneWejsciowe(String komunikat) {
String wierszWej = null;
System.out.print(komunikat + " ");
try {
BufferedReader sw = new BufferedReader(
new InputStreamReader(System.in));
wierszWej = sw.readLine();
if (wierszWej.length() == 0) return null;
} catch (IOException e) {
System.out.println("IOException: " + e);
}
return wierszWej;
}
}
So you want it to print something? If that's the problem, then you must make sure that the if-statement that tests whether the wynik is equal to "zatopiony" actually happens to be true. You program will only give an output, if this if-statement is true.
I separated the classes into separate files with proper names located in the same folder. Still doesnt workin and i do get this error : error: cannot find symbol.
this error occurs for every separated class. I checked all common errors from this thread:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
Files are saved with UTF-8 encoding if that means anyting. When i saves with BOM encoding i got a lot more errors
I am working on a JSF based Web Application where I read contents from a file(dumpfile) and then parse it using a logic and keep adding it to a list using an object and also set a string using the object. But I keep getting this error. I am confused where I am wrong. I am a beginner so can anyone be kind enough to help me?
List<DumpController> FinalDumpNotes;
public List<DumpController> initializeDumpNotes()
throws SocketException, IOException {
PostProcessedDump postProcessedDump = (PostProcessedDump) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("postProcessedDump");
List<DumpController> FinalNotes = new ArrayList<>();
if (postProcessedDump.getDumpNotes() == null) {
dumpNotes = new DumpNotes();
}
DumpListController dlcon = (DumpListController) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("dumpListController");
DumpInfo dumpinfo = dlcon.getSelectedDumpInfo();
String fileName = dumpinfo.getDate() + dumpinfo.getTime() + dumpinfo.getSeqNo() + dumpinfo.getType() + dumpinfo.getTape() + dumpinfo.getDescription() + ".txt";
if (checkFileExistsInWin(fileName)) {
postProcessedDump.setDumpnotescontent(getFileContentsFromWin(fileName));
String consolidateDumpnotes = getFileContentsFromWin(fileName);
String lines[];
String content = "";
lines = consolidateDumpnotes.split("\\r?\\n");
List<String> finallines = new ArrayList<>();
int k = 0;
for (int i = 0; i < lines.length; i++) {
if (!lines[i].equalsIgnoreCase("")) {
finallines.add(lines[i]);
k++;
}
}
for (int j = 0; j < finallines.size(); j++) {
if (finallines.get(j).startsWith("---------------------SAVED BY")) {
PostProcessedDump dump = new PostProcessedDump();
dump.setDumpMessage(content);
content = "";
FinalDumpNotes.add(dump);
} else {
content = content + finallines.get(j);
}
}
}
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("postProcessedDump", postProcessedDump);
return FinalDumpNotes;
}
I get the following error:
If you want to add instances of type PostProcessedDump to your List you should change it's type. Also, don't forget to initialize it. Something like,
List<PostProcessedDump> FinalDumpNotes = new ArrayList<>();
Also, Java naming convention is to start variable names with a lower case letter. FinalDumpNotes looks like a class, I would suggest something like
List<PostProcessedDump> processedList = new ArrayList<>();
Problems with your code:
List<DumpController> FinalDumpNotes;
You declare FinalDumpNotes to be a List of DumpController objects, but you never initialize it. In addition, your IDE is barfing on the following line of code:
FinalDumpNotes.add(dump);
because you are attempting to add a PostProcessedDump object to the List instead of a DumpController object.
For starters, you need to initialize your list like this:
List<DumpController> finalDumpNotes = new ArrayList<DumpController>();
Notice that I have made the variable name beginning with lower case, which is the convention (upper case is normally reserved for classes and interfaces).
I will leave it to you as a homework assignment to sort out the correct usage of this List.
I have verified that the entity I am looking for is in the datastore. I have verified that the list I pass as a method parameter contains this entity. I am trying to find all objects that have their 'userGmail' contained in the list of strings I pass.
Here is my code
#SuppressWarnings("unchecked")
#ApiMethod(name = "findFriendsByEmailList")
public CollectionResponse<ZeppaUser> findFriendsByEmailList(
#Named("emailsList") List<String> emailsList, User user)
throws OAuthRequestException {
if (user == null) {
throw new OAuthRequestException(
"Null User Authorization Exception, findFriendsByEmailList");
}
PersistenceManager mgr = null;
List<ZeppaUser> execute = null;
Query query = null;
try {
mgr = getPersistenceManager();
query = mgr.newQuery(ZeppaUser.class);
query.declareParameters("java.util.List emailListParam");
query.setFilter("emailListParam.contains( userGmail )");
execute = (List<ZeppaUser>) query.execute(emailsList);
query.closeAll();
} finally {
mgr.close();
}
return CollectionResponse.<ZeppaUser> builder().setItems(execute)
.build();
}
This is the stack trace I receive from it:
Something worth noting: I do not receive this error on lists I pass in that to not contain an element found in the datastore. Just when it does exist which leads me to believe that the Query has located the element but has not been closed or executed into a return parameter correctly. If it is preferable to return List that is more than ok. I have tried multiple variations of this with no success thus far. It is getting quite frustrating.
Ok so I found a way around it.
Lists cannot be passed into ApiEndpoints. That or I didn't figure out the correct way to do it and would LOVE an update on the proper way to do this.
Instead, in my client, I construct a String of emails seperated by a comma and send a string into the parameter as an 'encoded' string list then 'decode' it upon execution. Works well but seems hacky.
here are the methods I used. This is convenient though because it works with iOS as well.
public static String encodeListString(ArrayList<String> stringList){
StringBuilder stringbuilder = new StringBuilder();
stringbuilder.append(stringList.get(0));
if(stringList.size() > 1){
for( int i = 0; i < stringList.size(); i++){
stringbuilder.append(",");
stringbuilder.append(stringList.get(i));
}
}
return stringbuilder.toString();
}
public static List<String> decodeListString(String encodedString){
char[] characters = encodedString.toCharArray();
StringBuilder stringbuilder = new StringBuilder();
int position = 0;
ArrayList<String> stringList = new ArrayList<String>();
while(true){
try {
char character = characters[position];
if(character == ','){
String resultString = stringbuilder.toString();
stringList.add(resultString);
stringbuilder = new StringBuilder(); // clear it
} else {
stringbuilder.append(character);
}
position++;
} catch (ArrayIndexOutOfBoundsException aiex){
// List ended
String resultString = stringbuilder.toString();
if(!resultString.isEmpty())
stringList.add(resultString);
break;
}
}
return stringList;
}
Given the below code, is there some reason that when the final if-else statement steps into the else clause, if I un-comment the two lines of code and comment the "FOOZANAZABAR" and "TESTCAIRO" lines, that it would not add those lines into the LinkedHashSet? It appears to add
values.add(new BigDecimal(PEUNIT).multiply(new BigDecimal(1000)).toString());
correctly when the logic drops into the else clause, but will not add the BD.ZERO or the PEFAMT to that field DESPITE the fact they are strings.
As a note, the ZERO and PEFAMT are BigDecimal's that are converted to a string. These are the only two values that are giving me grief. Any direction would be greatly appreciated.
public static LinkedHashMap<String, LinkedHashSet<String>> convertTransactionTableData(ResultSet rs) {
LinkedHashMap<String, LinkedHashSet<String>> returnableMap = new LinkedHashMap<String, LinkedHashSet<String>> ();
try {
while (rs.next()){
String PEFAMT, PEPOLN, MCISST, PEBRCD, PEEFFY, PEPLAN;
String PEUNIT, PETRNC, PECO, PEITYP, ZERO;
PEPOLN = rs.getString("PEPOLN");
MCISST = rs.getString("MCISST");
PEBRCD = rs.getBigDecimal("PEBRCD").toString();
PEEFFY = rs.getBigDecimal("PEEFFY").toString();
PEPLAN = rs.getString("PEPLAN");
PEUNIT = rs.getBigDecimal("PEUNIT").toString();
PEFAMT = rs.getBigDecimal("PEFAMT").toString();
PETRNC = rs.getString("PETRNC");
PECO = rs.getString("PECO");
PEITYP = DataConverter.resetInsuranceType(rs.getString("PEITYP"));
ZERO = BigDecimal.ZERO.toPlainString();
String policyNumber = PEPOLN;
LinkedHashSet<String> values = new LinkedHashSet<String>();
values.add(MCISST);
values.add(PEBRCD);
values.add(PEEFFY);
values.add(PEPLAN);
values.add(PEUNIT);
if (PEPLAN.equalsIgnoreCase("HSRE")) {
values.add(new BigDecimal(PEUNIT).multiply(new BigDecimal(1000)).toString());
} else {
values.add(PEFAMT);
}
values.add(PETRNC);
values.add(PECO);
values.add(PEITYP);
if (DataConverter.testStringToInt(PETRNC)) {
if (Integer.valueOf(PETRNC) >= 20 && Integer.valueOf(PETRNC) <= 29) {
values.add(PEFAMT);
values.add(ZERO);
values.add(ZERO);
} else {
values.add("FOOZANZABAR");
values.add("TESTCAIRO");
// values.add(ZERO);
// values.add(PEFAMT);
values.add(new BigDecimal(PEUNIT).multiply(new BigDecimal(1000)).toString());
}
}
returnableMap.put(policyNumber, values);
}
} catch (SQLException sqlEx) {
logger.error("Problem converting the ResultSet. ", sqlEx);
}
return returnableMap;
}
Thank you in advance.
Josh
Please note that the underlying data structure you're using here is a SET which means it won't let you add duplicates. In all probability, the string values of BD.ZERO and PEFAMT must already be present in your values set and are hence getting ignored.
If this turns out to be the case simply switch to using LinkedList<String> that allows you to have duplicates.
DurationOfRun:5
ThreadSize:10
ExistingRange:1-1000
NewRange:5000-10000
Percentage:55 - AutoRefreshStoreCategories Data:Previous/30,New/70 UserLogged:true/50,false/50 SleepTime:5000 AttributeGet:1,16,10106,10111 AttributeSet:2060/30,10053/27
Percentage:25 - CrossPromoEditItemRule Data:Previous/60,New/40 UserLogged:true/50,false/50 SleepTime:4000 AttributeGet:1,10107 AttributeSet:10108/34,10109/25
Percentage:20 - CrossPromoManageRules Data:Previous/30,New/70 UserLogged:true/50,false/50 SleepTime:2000 AttributeGet:1,10107 AttributeSet:10108/26,10109/21
I am trying to parse above .txt file(first four lines are fixed and last three Lines can increase means it can be more than 3), so for that I wrote the below code and its working but it looks so messy. so Is there any better way to parse the above .txt file and also if we consider performance then which will be best way to parse the above txt file.
private static int noOfThreads;
private static List<Command> commands;
public static int startRange;
public static int endRange;
public static int newStartRange;
public static int newEndRange;
private static BufferedReader br = null;
private static String sCurrentLine = null;
private static List<String> values;
private static String commandName;
private static String percentage;
private static List<String> attributeIDGet;
private static List<String> attributeIDSet;
private static LinkedHashMap<String, Double> dataCriteria;
private static LinkedHashMap<Boolean, Double> userLoggingCriteria;
private static long sleepTimeOfCommand;
private static long durationOfRun;
br = new BufferedReader(new FileReader("S:\\Testing\\PDSTest1.txt"));
values = new ArrayList<String>();
while ((sCurrentLine = br.readLine()) != null) {
if(sCurrentLine.startsWith("DurationOfRun")) {
durationOfRun = Long.parseLong(sCurrentLine.split(":")[1]);
} else if(sCurrentLine.startsWith("ThreadSize")) {
noOfThreads = Integer.parseInt(sCurrentLine.split(":")[1]);
} else if(sCurrentLine.startsWith("ExistingRange")) {
startRange = Integer.parseInt(sCurrentLine.split(":")[1].split("-")[0]);
endRange = Integer.parseInt(sCurrentLine.split(":")[1].split("-")[1]);
} else if(sCurrentLine.startsWith("NewRange")) {
newStartRange = Integer.parseInt(sCurrentLine.split(":")[1].split("-")[0]);
newEndRange = Integer.parseInt(sCurrentLine.split(":")[1].split("-")[1]);
} else {
attributeIDGet = new ArrayList<String>();
attributeIDSet = new ArrayList<String>();
dataCriteria = new LinkedHashMap<String, Double>();
userLoggingCriteria = new LinkedHashMap<Boolean, Double>();
percentage = sCurrentLine.split("-")[0].split(":")[1].trim();
values = Arrays.asList(sCurrentLine.split("-")[1].trim().split("\\s+"));
for(String s : values) {
if(s.startsWith("Data")) {
String[] data = s.split(":")[1].split(",");
for (String n : data) {
dataCriteria.put(n.split("/")[0], Double.parseDouble(n.split("/")[1]));
}
//dataCriteria.put(data.split("/")[0], value)
} else if(s.startsWith("UserLogged")) {
String[] userLogged = s.split(":")[1].split(",");
for (String t : userLogged) {
userLoggingCriteria.put(Boolean.parseBoolean(t.split("/")[0]), Double.parseDouble(t.split("/")[1]));
}
//userLogged = Boolean.parseBoolean(s.split(":")[1]);
} else if(s.startsWith("SleepTime")) {
sleepTimeOfCommand = Long.parseLong(s.split(":")[1]);
} else if(s.startsWith("AttributeGet")) {
String[] strGet = s.split(":")[1].split(",");
for(String q : strGet) attributeIDGet.add(q);
} else if(s.startsWith("AttributeSet:")) {
String[] strSet = s.split(":")[1].split(",");
for(String p : strSet) attributeIDSet.add(p);
} else {
commandName = s;
}
}
Command command = new Command();
command.setName(commandName);
command.setExecutionPercentage(Double.parseDouble(percentage));
command.setAttributeIDGet(attributeIDGet);
command.setAttributeIDSet(attributeIDSet);
command.setDataUsageCriteria(dataCriteria);
command.setUserLoggingCriteria(userLoggingCriteria);
command.setSleepTime(sleepTimeOfCommand);
commands.add(command);
Well, parsers usually are messy once you get down to the lower layers of them :-)
However, one possible improvement, at least in terms of code quality, would be to recognize the fact that your grammar is layered.
By that, I mean every line is an identifying token followed by some properties.
In the case of DurationOfRun, ThreadSize, ExistingRange and NewRange, the properties are relatively simple. Percentage is somewhat more complex but still okay.
I would structure the code as (pseudo-code):
def parseFile (fileHandle):
while (currentLine = fileHandle.getNextLine()) != EOF:
if currentLine.beginsWith ("DurationOfRun:"):
processDurationOfRun (currentLine[14:])
elsif currentLine.beginsWith ("ThreadSize:"):
processThreadSize (currentLine[11:])
elsif currentLine.beginsWith ("ExistingRange:"):
processExistingRange (currentLine[14:])
elsif currentLine.beginsWith ("NewRange:"):
processNewRange (currentLine[9:])
elsif currentLine.beginsWith ("Percentage:"):
processPercentage (currentLine[11:])
else
raise error
Then, in each of those processWhatever() functions, you parse the remainder of the line based on the expected format. That keeps your code small and readable and easily changed in future, without having to navigate a morass :-)
For example, processDurationOfRun() simply gets an integer from the remainder of the line:
def processDurationOfRun (line):
this.durationOfRun = line.parseAsInt()
Similarly, the functions for the two ranges split the string on - and get two integers from the resultant values:
def processExistingRange (line):
values[] = line.split("-")
this.existingRangeStart = values[0].parseAsInt()
this.existingRangeEnd = values[1].parseAsInt()
The processPercentage() function is the tricky one but that is also easily doable if you layer it as well. Assuming those things are always in the same order, it consists of:
an integer;
a literal -;
some sort of textual category; and
a series of key:value pairs.
And even these values within the pairs can be parsed by lower levels, splitting first on commas to get subvalues like Previous/30 and New/70, then splitting each of those subvalues on slashes to get individual items. That way, a logical hierarchy can be reflected in your code.
Unless you're expecting to be parsing this text files many times per second, or unless it's many megabytes in size, I'd be more concerned about the readability and maintainability of your code than the speed of the parsing.
Mostly gone are the days when we need to wring the last ounce of performance from our code but we still have problems in fixing said code in a timely manner when bugs are found or enhancements are desired.
Sometimes it's preferable to optimise for readability.
I would not worry about performance until I was sure there was actually a performance issue. Regarding the rest of the code, if you won't be adding any new line types I would not worry about it. If you do worry about it, however, a factory design pattern can help you separate the selection of the type of processing needed from the actual processing. It makes adding new line types easier without introducing as much opportunity for error.
The younger and more convenient class is Scanner. You just need to modify the delimiter, and get reading of data in the desired format (readInt, readLong) in one go - no need for separate x.parseX - calls.
Second: Split your code into small, reusable pieces. They make the program readable, and you can hide details easily.
Don't hesitate to use a struct-like class for a range, for example. Returning multiple values from a method can be done by these, without boilerplate (getter,setter,ctor).
import java.util.*;
import java.io.*;
public class ReadSampleFile
{
// struct like classes:
class PercentageRow {
public int percentage;
public String name;
public int dataPrevious;
public int dataNew;
public int userLoggedTrue;
public int userLoggedFalse;
public List<Integer> attributeGet;
public List<Integer> attributeSet;
}
class Range {
public int from;
public int to;
}
private int readInt (String name, Scanner sc) {
String s = sc.next ();
if (s.startsWith (name)) {
return sc.nextLong ();
}
else err (name + " expected, found: " + s);
}
private long readLong (String name, Scanner sc) {
String s = sc.next ();
if (s.startsWith (name)) {
return sc.nextInt ();
}
else err (name + " expected, found: " + s);
}
private Range readRange (String name, Scanner sc) {
String s = sc.next ();
if (s.startsWith (name)) {
Range r = new Range ();
r.from = sc.nextInt ();
r.to = sc.nextInt ();
return r;
}
else err (name + " expected, found: " + s);
}
private PercentageLine readPercentageLine (Scanner sc) {
// reuse above methods
PercentageLine percentageLine = new PercentageLine ();
percentageLine.percentage = readInt ("Percentage", sc);
// ...
return percentageLine;
}
public ReadSampleFile () throws FileNotFoundException
{
/* I only read from my sourcefile for convenience.
So I could scroll up to see what's the next entry.
Don't do this at home. :) The dummy later ...
*/
Scanner sc = new Scanner (new File ("./ReadSampleFile.java"));
sc.useDelimiter ("[ \n/,:-]");
// ... is the comment I had to insert.
String dummy = sc.nextLine ();
List <String> values = new ArrayList<String> ();
if (sc.hasNext ()) {
// see how nice the data structure is reflected
// by this code:
long duration = readLong ("DurationOfRun");
int noOfThreads = readInt ("ThreadSize");
Range eRange = readRange ("ExistingRange");
Range nRange = readRange ("NewRange");
List <PercentageRow> percentageRows = new ArrayList <PercentageRow> ();
// including the repetition ...
while (sc.hasNext ()) {
percentageRows.add (readPercentageLine ());
}
}
}
public static void main (String args[]) throws FileNotFoundException
{
new ReadSampleFile ();
}
public static void err (String msg)
{
System.out.println ("Err:\t" + msg);
}
}