This question already has answers here:
Checking if a string is empty or null in Java [duplicate]
(5 answers)
Closed 6 years ago.
Why does my if-else block not detect that gamma is null? Here is my code. It is a Spreadsheet application and this is the save function which loops through all of the cells in the table and writes it to a file. Here is my code:
public void Save () {
String FileName = JOptionPane.showInputDialog("Please enter the name for your file:");
if (FileName == null) {
System.err.println("You didn't enter anything");
} else {
int rows = Table.getRowCount();
int columns = Table.getColumnCount();
int alpha = 0;
int beta = 1;
choicer.setCurrentDirectory(new java.io.File("Desktop"));
choicer.setDialogTitle("Save Document");
choicer.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
choicer.setAcceptAllFileFilterUsed(false);
if (choicer.showSaveDialog(new JPanel()) == JFileChooser.APPROVE_OPTION) {
dir = String.valueOf(choicer.getSelectedFile());
}
File f = new File(dir + "\\" + FileName + ".txt");
try {
fos = new FileOutputStream(f);
osw = new OutputStreamWriter(fos);
w = new BufferedWriter(osw);
for (alpha = 0; alpha <= rows - 1; alpha++) {
for (beta = 1; beta < columns; beta++) {
String gamma = String.valueOf(Table.getValueAt(alpha, beta));
if (gamma != null) {
w.write("<%! " + gamma + " !%> ");
} else {
w.write(" <%! |^-^| !%> ");
}
}
w.write("\n");
}
} catch (IOException e) {
System.err.println("Some prob dude. Too big for me");
} finally {
try {
w.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I tried the link given by the duplicate thing but that doesn't solve my problem. If I do if(gamma != null && !(gamma.isEmpty)) then only null is written to the file as the value of gamma.
Maybe, gamma is empty but not null:
Change
if (gamma != null)
To
if (gamma != null && !gamma.isEmpty())
There are only three things that I can think of that would cause this. I will get to those in a second. First, what IDE are you using? Do you have the ability to set a breakpoint and watch variables? This will help you in troubleshooting the following.
1. Can you ensure that the first for loop hits?
2. Then, make sure you are getting in the second for loop.
3. Finally, what is the actual value of the string gamma? This is where you need a breakpoint and to inspect that variable when you are expecting it to be null. Likely you will see it is not. That is of course, assuming that your for loops are even letting you get there.
Hope this helps!
Related
We need to get below format
Redemption Reference Code|Status|Delivery company|Shipper Tracking Number|Comments
2006995040|Shipped|USPS|ABCD12345|Order SHIPPED
2006995042|Cancelled|||INVALID Address
2006995048|Ordered|USPS|ABCD12345|Order SHIPPED
I am using below code
private void accumulateOrdersFromPlacement(){
int count = 0;
for (int i = 0; i < orderIds.size(); i++) {
if (count == 0) {
outPutLineData.add(orderIds.get(i));
outPutLineData.add("Cancelled");
outPutLineData.add("");
outPutLineData.add(" ");
outPutLineData.add(" ");
cancelledStatusLineItems.add(orderIds.get(i));
count++;
} else if (count == 1) {
outPutLineData.add(orderIds.get(i));
outPutLineData.add("Shipped");
if (outPutLineData.contains("Shipped")) {
outPutLineData.add("USPS");
outPutLineData.add("order SHIPPED");
outPutLineData.add("");
}
shippedStatusLineItems.add(orderIds.get(i));
count++;
} else if (count == 2) {
outPutLineData.add(orderIds.get(i));
outPutLineData.add("No Longer Available");
outPutLineData.add("");
outPutLineData.add(" ");
outPutLineData.add(" ");
count++;
nlaStatusLineItems.add(orderIds.get(i));
} else if (count == 3) {
outPutLineData.add(orderIds.get(i));
outPutLineData.add("Ordered");
outPutLineData.add("");
outPutLineData.add(" ");
outPutLineData.add(" ");
orderedStatusLineItems.add(orderIds.get(i));
count = 0;
}
}
I am using below code for file creation. This is the detailed coding . This has more readability to understand code.Here i got confused about the code.We are taking order id count andbased on that this code is working.
private File createFile(final File directory) {
FileWriter fw = null;
File tempFile = null;
try {
directory.mkdir();
tempFile = new File(".//FidelityFulfillment//" + generateFileName(countyThreeLetterCode, "FidelityFulfillment", ".csv", date));
logReport(GenericConstants.NEW_LINE + "Fulfillment file creating:", tempFile.getName());
fw = new FileWriter(tempFile, true);
try (BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile, true))) {
writer.write(generateHeaderLine());
writer.newLine();
for (int y = 1; y < outPutLineData.size(); y++) {
if (y % 5 < 4) {
writer.write(outPutLineData.get(y-1) + fieldSeperator);
logReport(outPutLineData.get(y - 1) + fieldSeperator);
}
else {
writer.write(outPutLineData.get(y-1));
logReport(outPutLineData.get(y));
}
if (y % 5 == 0) {
writer.newLine();
logReport("newline");
}
}
writer.close();
} catch (final IOException e) {
e.printStackTrace();
final String err = "Unable to write file due to : " + e;
logReport(GenericConstants.NEW_LINE + "Unable to create temp local File");
} finally {
fw.close();
}
}catch (Exception e){
e.printStackTrace();
}
return tempFile;
}
Getting response as
Redemption Reference Code|Status|Delivery company|ShipperTrackingNumber|Comments
2006964032|Cancelled|| |
newline
2006964034|Shipped|USPS||
newline
2006964036|No Longer Available||
Last line one pipline is getting missing
First, you loop in a strange way :
for (int y = 1; y < outPutLineData.size(); y++) {
In general, we start at 0.
But you tried to correct that with the condition :
if (y % 5 < 4) {
//System.out.print("size:"+y);
writer.write(outPutLineData.get(y-1) + fieldSeperator);
logReport(outPutLineData.get(y - 1) + fieldSeperator);
}
else {
//System.out.print("size noseperator:"+y);
writer.write(outPutLineData.get(y-1));
logReport(outPutLineData.get(y));
}
Instead, simply use an iterator to read the values, then on read the correct amount of values :
Iterator<String> it = outPutLineData.iterator();
while(it.hasNext()){
for (int j = 0; j < columnCount; ++j) {
writer.write(it.next());
if( j < columnCount - 1)
writer.write(fieldSeperator);
}
writer.newLine();
}
Example with a StringBuilder to print in console :
int columnCount = 2;
String fieldSeperator = "|";
List<String> list = Arrays.asList("foo", "1", "bar", "2");
Iterator<String> it = list.iterator();
//Safe guard !
if(list.size() % columnCount != 0)
throw new RuntimeException("The list does have the correct amount of data");
while(it.hasNext()){
for (int j = 0; j < columnCount; ++j) {
sb.append( it.next() );
if( j < columnCount - 1)
sb.append(fieldSeperator );
}
System.out.println(sb.toString());
sb.setLength(0);
}
foo|1
bar|2
Use a POJO
You are using a List<String> to hold the values, you need to know how many column you need to read to get the value. Instead, use a POJO :
public class Redemption{
String redemptionReference;
String code;
String status;
String deliveryCompany;
String shipperTrackingNumber;
String comments;
}
And create the instance in your first loop :
List<Redemption> list...
That way, you just need to iterate each instance to build your row :
for(Redemption r: list){
writer.write(r.getRedemptionReference() + fieldSeperator);
...
writer.write(r.getComments());
writer.newLine();
}
Of course, you need to use getter and setter but this is just to show what you should do.
CSV API
Big warning, writing your own CSV writer is dangerous. If you have a comment like "This is a | character". You will end up with a line like :
2006995040|Shipped|USPS|This is a | character|Order SHIPPED
That one column to many... because you should have
2006995040|Shipped|USPS|"This is a | character"|Order SHIPPED
But you are not checking that case, and this is only one case. Using a CSV API is safer and simpler.
See Any good library to read and write csv files?
I'm currently working on a "big" project, and I'm facing a incomprehensible bug. This one is just beyond my competence.
I will try to be as clear as possible, because there is a lot of code, I'll try to show you some screenshots of the debug intereface (breakpoint).
Basically, this is a program about surveys, admins can create surveys, users can answer them.. basic.
I'm doing it in java, using a HttpServer which creates a lot of contexts, (html pages) using the createContext method .
I'm also using a RMI object to manage the surveys and the results.
I have written a form for an admin to create a new survey, using the post method, i post it to another page so as to process the query.
Once I have done that, I have three variables to create a new survey : an id, a title, an array of questions, and an integer to say if the survey will be visible for the user or not. Note: I am 100% sure that those variables are correct
(Sorry for the french words in the code / screens, I'll try to rename most of them)
ISurveyManagement test = (ISurveyManagement)Naming.lookup("rmi://localhost/surveys");
I get my RMI object,
test.addSurvey(nsondage, titre, questions, 1);
Then I call my method to add the survey. (of course, all of those instruction are in the Handle method, from the interface HttpHandler)
This is what happens after the break point :
I have clicked on my button, the title has been correctly printed
Same thing for the RMI object, not null or anything, Then, we are supposed to go into the method of the RMI object:
But we are here!!! ServerImpl ExChange run?? what!! I pass a few steps
I passed all the step of the third picture, now we are again in the beggining of the Handle method?? why? and what about my call of addSurvey??
If I pass again a lot of steps, you will see that "HELLO", my title, and the RMI object will be printed again, then instead of going into my method it goes int that Thread-2 thing again and then crash...
I'm really sorry for this big ugly question, but I'm completly lost, I'm searching for hour ><
Thank you so much by advance if you can help me
EDIT:
this is the addSurvey method:
#Override
public void addSurvey(int n, String title, ArrayList<Question> q, int active) throws RemoteException {
System.out.println("anything");
this.loadSurveys();
this.objSurveys.add(new Survey(n, title, q, active));
this.saveSurveys();
}
The sysout at the begining is not displayed, I'm sure that the methods load and save work perfectly, I'm using them in an other functionnality.
EDIT2: as you asked, this is the code of the whole class test
public class CreationManagement implements HttpHandler {
#Override
public void handle(HttpExchange t) throws IOException {
String reponse =
"<html>"
+"<head>"
+ "<title>Page admin</title>"
+"<meta http-equiv=\"content-type\" content=\"text/plain; charset=utf-8\"/>"
+"</head>"
+"<body style=\"font-family: Georgia, Times, serif;padding:20px;width:400px;border:1px solid #172183;\">"
+"<p style=\"text-align:center;padding:5px;color:white;background:#172183;\">Vos changements ont bien été pris en compte!</p>"
+ "<form action=\"http://localhost:8080/admin.html\">"
+ "<button style=\"border: none;color: #ffffff;display: block;margin: auto;background: #172183;padding: 5px 20px;cursor:pointer;\">Retour</button>"
+ "</form>";
URI requestedUri = t.getRequestURI();
String query = requestedUri.getRawQuery();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(t.getRequestBody(),"utf-8"));
} catch(UnsupportedEncodingException e) {
System.err.println("Error flow" + e);
System.exit(-1);
}
try {
query = br.readLine();
} catch(IOException e) {
System.err.println("Error while reading line " + e);
System.exit(-1);
}
/*String [] p = query.split("&");
for (int i = 0 ; i < p.length ; i++) {
reponse += p[i] + "<br>";
}*/
ISurveyManagement test = null;
try {
test = (ISurveyManagement)Naming.lookup("rmi://localhost/sondages");
} catch(NotBoundException e) {
System.err.println("Error while getting rmi object : " + e);
System.exit(-1);
} catch(MalformedURLException e) {
System.err.println("URL mal forme : " + e);
System.exit(-1);
} catch(RemoteException e) {
System.err.println("not possible to get rmi obj : " + e);
System.exit(-1);
}
test.loadSurveys();
int length = test.getSurveys().size();
int nsurvey= length + 1;
String[] op = query.split("&");
String title = op[0].split("=")[1];
String[] params = Arrays.copyOfRange(op, 1, op.length);
/*for (int a = 0 ; a < params.length ; a++) {
System.out.println(a + " " +params[a]);
}*/
ArrayList<Question> questions = new ArrayList<Question>();
//System.out.println("taille " + params.length );
for (int i = 0 ; i < params.length ; i++) {
if (i%5 == 0) {
String[] detQ = params[i].split("=");
int nq = Integer.parseInt(detQ[0].substring(1, detQ[0].length()));
String libq = detQ[1];
Question q = new Question(nq, libq, nsondage);
q.setReponses(new ArrayList<Reponse>());
questions.add(q);
} else {
String[] detR = params[i].split("=");
if (detR.length == 2) {
String lib = detR[1];
int q = Integer.parseInt(detR[0].split("_")[0]);
int num = Integer.parseInt(detR[0].split("_")[1]);
String l = "";
if (num == 1) {
l = "A";
} else if (num == 2) {
l = "B";
} else if (num == 3) {
l = "C";
} else if (num == 4) {
l = "D";
}
Reponse r = new Reponse(l, lib, q, nsondage);
questions.get(q-1).getReponses().add(r);
}
}
}
System.out.println("HELLO");
System.out.println(title);
System.out.println(test);
//Survey s = new Survey(nsurvey, title, questions, 1);
test.addSurvey(nsurvey, title, questions, 1);
//System.out.println(s.display());
System.out.println(nsurvey);
reponse += "</body></html>";
try {
Headers h = t.getResponseHeaders();
h.set("Content-Type", "text/html; charset=utf-8");
t.sendResponseHeaders(200, 0);
} catch(IOException e) {
System.err.println("error while sending header : " + e);
System.exit(-1);
}
try {
OutputStream os = t.getResponseBody();
os.write(reponse.getBytes());
os.close();
} catch(IOException e) {
System.err.println("error sending corps : " + e);
}
}
}
Is I said the survey is displayed correctly when I try to display it, the object is correctly created.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Floating point error in representation?
So I am running this code to read float string values from a a file and store the values in to an array. When the program reads in "0.333" from the file it creates a new float value but the value is converted into 0.33329999446868896! Why is this? And how can I fix this issue? The matrices are declared as follows:
this.matrix = new double[this.getRow()][this.getCol()];
this.bMatrix = new double[this.getRow()];
try {
// make sure no blank lines at the end of the file.
for (int i = 0; (strLine = reader.readLine()) != null; i++) {
System.out.println("Line from file #" + i + " " + strLine);
String[] columns = strLine.trim().split("\\s+");
for (int j = 0; j < columns.length; j++) {
if (j < (columns.length - 1)) {
//A-matrix
this.matrix[i][j] = new Float(columns[j]).floatValue();
System.out.println("Element added to A-matrix: " + columns[j]);
} else {
// B-matrix
bMatrix[i] = new Float(columns[j]).floatValue();
System.out.println("Element added to B-matrix: " + columns[j]);
}
}
}
showMatrix();
} catch (IOException | NumberFormatException e) {
reader.close();
}
}
Thanks for any assistance.
This has to do with the way floating point numbers are represented in binary. Essentially, you can't precisely represent 0.333. The closest you can get is the number you see. If you want a shorter version for printing, use StringFormatter or something before you output your values.
I am currently working on a program for one of my java class and I keep running into a wall with file reading! I am using a JTable to display the information so when the information is read from a file it is added to a row. Whenever there is a blank row the scanner cannot read it and throw an error! i get a java.util.NoSuchElementException on the last scanning line! As of right no i am suing two separate scanners. I had attempted to use the String.split method that that also gave me an error (ArrayIndexOutOfBoundsException: 0). I will post the reading a saving methods below (both two scanner version and split).
private void read() {
try {
Scanner scanner = new Scanner(new File("games.dat"));
scanner.useDelimiter(System.getProperty("line.separator"));
while (scanner.hasNext()) {
String[] tableRow = new String[6];
Scanner recIn = new Scanner(record);
recIn.useDelimiter("\\s*\\|\\s*");
tableRow[0] = recIn.next();
tableRow[1] = recIn.next();
tableRow[2] = recIn.next();
tableRow[3] = recIn.next();
tableRow[4] = recIn.next();
//recIn.next();
recIn.close();
model.addRow(new Object[]{tableRow[0],
tableRow[1], tableRow[2],
tableRow[3], tableRow[4]});
}scanner.close();
scanner = null;
} catch (Exception ex) {
JOptionPane.showConfirmDialog(null, "Could not connect to file! Make sure you are not in zipped file!",
"Warning!", JOptionPane.OK_OPTION,
JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
}
private void save() {
for (int i = 0; i < model.getRowCount(); i++) {
String data = model.getValueAt(i, 0) + "|" + model.getValueAt(i, 1)
+ "|" + model.getValueAt(i, 2) + "|" + model.getValueAt(i, 3)
+ "|" + model.getValueAt(i, 4) + "|";
games.add(data);
}
try {
for (int i = 0; i < games.size(); i++) {
fileOut.println(games.get(i));
}
fileOut.close();
} catch (Exception ex) {
JOptionPane.showConfirmDialog(null, "Could not connect to file! Make sure you are not in zipped file!",
"Warning!", JOptionPane.OK_OPTION,
JOptionPane.ERROR_MESSAGE);
}
}
recIn.next(); will fail if the line is empty, guard it with hasNext():
Scanner recIn = new Scanner(record);
recIn.useDelimiter("\\s*\\|\\s*");
if (recIn.hasNext()) {
tableRow[0] = recIn.next();
tableRow[1] = recIn.next();
tableRow[2] = recIn.next();
tableRow[3] = recIn.next();
tableRow[4] = recIn.next();
}
This assumes that when there is one element on the record, all of them are there. If this cannot be guaranteed, you need to protect each next() call with hasNext() and decide what to do when you run out of elements in the middle of a record.
Also, you seem to have an infinite loop:
while (scanner.hasNext()) {
// no calls to scanner.next()
}
Did you leave out String record = scanner.next(); from the top of that loop?
From the java.util.Scanner JavaDoc, there is this method, skip():
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html#skip%28java.util.regex.Pattern%29
The last line reads, "Note that it is possible to skip something without risking a NoSuchElementException by using a pattern that can match nothing, e.g., sc.skip("[ \t]*")."
So, perhaps add as the first call of your loop, scanner.skip("[ \t]*);
i am trying to make a java application with GUI.
i am writing a code that i want to let the User change some data and save these changes on a text file. Before doing that i want to delete the old data that is changed from a list and then rewrite the new data with the last change.if i am missing any class you wanted to see please tell me i will put it online as fast as possible
this is my
public void saveChanges(footBall Player, String name, String level,
int[] scores, int footSize) {
try {
if (CompetitorsList.size() != 0) {
for (Competitors C : CompetitorsList) {
if (C instanceof footBall) {
String Number = Player.playerNumber + "";
if (C.getPlayerNumberAsString().equals(Number)) {
System.out.println("c");
//the error hit me here when i try to remove the object from the list the exception error is java.util.ConcurrentModificationException
CompetitorsList.remove(C);
}
}
}
Name NewName = new Name(name);
System.out.println("Please get in2");
footBall NewPlayer = new footBall(Player.playerNumber, scores,
level, footSize, NewName);
CompetitorsList.add(NewPlayer);
SaveOnFile();
} else {
System.out.println("No List");
}
} catch (Exception ex) {
System.out.print("testing4");
System.out.print("something wrong" + ex);
}
}
this is the SaveOnFile method:
public void SaveOnFile() {
String scoresInString;
FileWriter fw;
try {
fw = new FileWriter("footBall");
for (Competitors C : CompetitorsList) {
if (C instanceof footBall) {
footBall Scores = new footBall();
scoresInString = Scores.returnScoreAsString(C.scores);
fw.write(C.playerNumber + ", " + C.name.getFullName()
+ ", " + C.level + ", " + scoresInString + ","
+ ((footBall) C).footSize() + "\n");
fw.write("\r\n");
}
}
fw.close();
}
// message and stop if file not found
catch (FileNotFoundException fnf) {
System.out.println("File not found ");
System.exit(0);
}
// stack trace here because we don't expect to come here
catch (IOException ioe) {
ioe.printStackTrace();
System.exit(1);
}
}
Calling remove() on a collection invalidates all active iterator. Instead, you have to use the Iterator.remove() method:
for(Iterator<Competitors> it = CompetitorsList.iterator(); it.hasNext(); ) {
Competitors C = it.next();
if(C instanceof ...) {
if(C.getPlayerNumberAsString().equals(Number))
it.remove();
...
This way, the iterator() knows about how the collection changes, which otherwise wouldn't be possible since the ArrayList doesn't track the Iterators it generated.
Alternatively, if you want to use the same "for-next" syntax and not change to the Iterator syntax, collect all the objects to be removed into a temporary collection. e.g.
ArrayList<Competitors> removeThese = new ArrayList<Competitors>();
for (Competitors C : CompetitorsList) {
if (wantToRemove(C)) // your number logic goes here...
removeThese.add(C);
}
CompetitorsList.removeAll(removeThese);