I'm working on assignment for OOP and am stuck on the last step which is, "Write all players to an output file that has a similar format of the input file."
I need to know how to print all the info in the main to an output file with the same format as the input file and I use here ArrayList. it's working fine when I print the name and the height but when I want to print season or score, an exception appears.
pw.write(t1.getName() + "; " + t1.getCity() + "\n");
for (int m = 0; m < p2.size(); m++) {
pw.print(t1.getPlayerList().get(m).getName() + "; " + t1.getPlayerList().get(m).getHeight() + "; ");
pw.println(t1.getPlayerList().get(m).getSeasonalRecords().get(m).getScores());
}
it works well, but when I write
pw.println(t1.getPlayerList().get(m).getSeasonalRecords().get(m).getScores());
appear something is wrong
that the exceptions that I got
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
at java.util.ArrayList.rangeCheck(ArrayList.java:657)
at java.util.ArrayList.get(ArrayList.java:433)
The root cause of the issue is described in the comments: index m exceeds the number of seasonal records and definitely it may take another nested loop to print the seasonal records.
It may be better to replace for loops with indexes with for-each to make the code shorter, more readable and less prone to the mentioned errors:
for (var player : t1.getPlayerList()) {
pw.println(player.getName() + "; " + player.getHeight() + "; ");
for (var seasonRecord : player.getSeasonalRecords()) {
pw.println(seasonalRecord.getScores());
}
}
Related
I need to receive 300 recommendation in one short using for loop using my code.
Currently I can receive one to 10 recommendation response. But when i deal with 200 to 500 recommendations it's so hard for me to edit my code from 1 to 500. Instead I try to implement the for loop in my code but it's fails.
Below is my code.
Map<String, String> recommendations5 = response.jsonPath().getMap("recommendation[5]");
System.out.print("\n\n");
System.out.print(recommendations5.get("validatingAirlineName"));
System.out.print("\n\n");
System.out.println("adultBaseFare=" + recommendations5.get("adultBaseFare"));
System.out.println("adultTaxFare=" + recommendations5.get("adultTaxFare"));
System.out.println("Deeplink=" + recommendations5.get("Deeplink"));
System.out.println("marketingAirlineCodes=" + recommendations5.get("marketingAirlineCodes"));
System.out.println("validatingAirlineName=" + recommendations5.get("validatingAirlineName"));
System.out.println("totalBaseFare=" + recommendations5.get("totalBaseFare"));
System.out.println("totalFare=" + recommendations5.get("totalFare"));
System.out.println("validatingAirlineCode=" + recommendations5.get("validatingAirlineCode"));
System.out.println("validatingAirlineName=" + recommendations5.get("validatingAirlineName"));
Below is the my for loop logic but it fails.
My error:
Exception in thread "main" java.lang.IllegalArgumentException: The parameter "i" was used but not defined. Define parameters using the JsonPath.params(...) function
My for loop code:
for(int i=0;i<=jsonResponse.size();i++)
{
Map<String, String> recommendations5 = response.jsonPath().getMap("recommendation[i]");
System.out.print("\n\n");
System.out.print(recommendations5.get("validatingAirlineName"));
System.out.print("\n\n");
System.out.println("adultBaseFare=" + recommendations5.get("adultBaseFare"));
System.out.println("adultTaxFare=" + recommendations5.get("adultTaxFare"));
System.out.println("Deeplink=" + recommendations5.get("Deeplink"));
System.out.println("marketingAirlineCodes=" + recommendations5.get("marketingAirlineCodes"));
System.out.println("validatingAirlineName=" + recommendations5.get("validatingAirlineName"));
System.out.println("totalBaseFare=" + recommendations5.get("totalBaseFare"));
System.out.println("totalFare=" + recommendations5.get("totalFare"));
System.out.println("validatingAirlineCode=" + recommendations5.get("validatingAirlineCode"));
System.out.println("validatingAirlineName=" + recommendations5.get("validatingAirlineName"));
}
You need to replace the String i will the actually i int value
Map<String, String> recommendations5 = response.jsonPath().getMap("recommendation[" + i + "]");
I'm reading data from a spreadsheet and an exception is occurring, but I can't figure out where it is.
int quantidade_linhas = sheet.getLastRowNum();
for (int i = 0; i < quantidade_linhas; i++) {
String nomes = sheet.getRow(i).getCell(0).getStringCellValue();
String sobrenomes = sheet.getRow(i).getCell(1).getStringCellValue();
System.out.println("Dados: " + nomes + " " + sobrenomes);
}
PlanilhaSerLida.close();
System.out.println("Fechando a planilha!\n");
}
Error Console:
Exception in thread "main" java.lang.NullPointerException at
arquivo.lerDados.main(lerDados.java:32)
Line 32 where the error is pointed out is precisely the string nomes
An excel spreadsheet can have blank rows that are empty and thus have no cell values. I'd first debug your program with this code, put it right under the for-loop declaration:
System.out.println("Row " + i + " null?: " + (sheet.getRow(i) == null))
That prints for each row the index and whether the row is null or not. After that you can decide to either fix the spreadsheet, make your program ignore empty (null) rows or do both.
Also a tip, if one of the rows contains a numerical value it will cause an exception since it won't auto convert the int to a string. Make a utility function that checks cell.getCellType() for a (CellType) string or a numerical value and then converts when needed.
I am trying to write to a text document with a specific format. Here's what I have right now.
String line = "";
double totalCost = 0;
Node curr = summary.head.next;
while(curr!=summary.tail)
{
line += [an assortment of strings and variables] +"\r";
totalCost += PRICELIST.get(curr.itemName)*curr.count;
curr = curr.next;
}
write.printf("%s" + "%n", line);
This is what the part adding onto line actually looks like.
"Item's name: " + curr.itemName + ", Cost per item: " + NumberFormat.getCurrencyInstance().format(PRICELIST.get(curr.itemName)) +
", Quantity: " + curr.count + ", Cost: " + NumberFormat.getCurrencyInstance().format(PRICELIST.get(curr.itemName)*curr.count) + "\r";
I've tried that with a newline character too. Before I had it working when the print statement was inside the loop meaning it only wrote one line at a time. I want to do it this way because I will have multiple threads writing to this file and this way any thread will not hold the lock for as long.
If using Java 7 or later you can use System.lineSeparator()
Use System.getProperty("line.separator") instead of "\r"
Cache ir for efficiency though.
First of all don't use
while(..){
result += newString
..
}
inside loop. This is very inefficient especially for long texts because each time you call
result += newString
you are creating new String which needs to copy content of result and append to it newStrint. So the more text you processed so far, the more it has to copy so it becomes slower.
Instead use
StringBuilder sb = new StringBuilder();
while(..){
sb.append(newString);
}
result = sb.toString.
which in your case should be something more like
sb.append("Item's name: ").append(curr.itemName)
.append(", Cost per item: ").append(NumberFormat.getCurrencyInstance().format(PRICELIST.get(curr.itemName)))
.append(", Quantity: ").append(curr.count )
.append(", Cost: ").append(NumberFormat.getCurrencyInstance().format(PRICELIST.get(curr.itemName) * curr.count))
.append(System.lineSeparator());
Also instead of
write.printf("%s" + "%n", line);
you should use simpler version, which is
write.println(line);
which automatically add line separator based on OS.
You can also try to use \n\r in combination. This helped in one of my projects.
I am using a while loop and getting data from a text file and using classes to reference each string. I don't have any issues getting the values for each string and printing it out.
However, I am confused on how to use System.out.printf(....) to put all of the strings I need in one line while using a loop.
For example, let's say the text file was:
I
like
to
use
computers
I want to use a loop to print out the words into one string and I may have different spacing between each word.
The code I have so far:
while (!readyOrder.isEmpty()) {
s = readyOrder.poll();
System.out.printf(s.getQuantity() + " x " + s.getName()
+ "(" + s.getType() + ")" + " "
+ s.getPrice() * s.getQuantity());
System.out.println(" ");
total = total + s.getPrice() * s.getQuantity();
}
And the output should be:
1_x_The Shawshank Redemption_______(DVD)________________19.95
The underlined spaces are where the spaces should be and how long they should be.
How can I use printf to do that?
I think you need to use the string padding functionality of printf. For example %-30s formats to width of 30 characters, - means left justify.
for (Stock s : Arrays.asList(
new Stock(1, "The Shawshank Redemption", 100, "DVD"),
new Stock(2, "Human Centipede", 123, "VHS"),
new Stock(1, "Sharknado 2", 123, "Blu ray"))) {
System.out.printf("%2d x %-30s (%-7s) %5.2f\n",
s.getQuantity(), s.getName(), s.getType(),
s.getPrice() * s.getQuantity());
}
Output
1 x The Shawshank Redemption (DVD ) 100.00
2 x Human Centipede (VHS ) 246.00
1 x Sharknado 2 (Blu ray) 123.00
hello i would like to ask you about the 2D tables in java!!my code is this an i would like to make a system out in order t see the registrations in mytable citylink can anyone help me?
int i=0;
while(i<=citylink.length) {
for(Xml polh_is:fetchsite.child("site").child("poleis").children("polh")) { //url
if((polh_is.string("name")=="")||(polh_is.content()==""))//attribute
error += "Error in polh: name is - " + polh_is.string("name") + " with url - " + polh_is.content() + " -.\n";
else
for(int j=0; j<citylink.length; j++) {
citylink[j][0]=HtmlMethods.removeBreaks(polh_is.string("name"));
citylink[j][1]=HtmlMethods.removeBreaks(polh_is.string("with url -"+polh_is.content() +"-.\n"));
i++;
}
}
}
citylink seems to be a single-dimensional array?
You can use another 2D array to store the values.
Something like this?:
StringBuilder citiesBuilder = new StringBuilder();
for (String[] city:citylink) {
citiesBuilder.append(String.format("%s (URL: %s)%n", city[0], city[1]));
}
System.out.println(citiesBuilder.toString());
EDIT
changed 'cities' to 'citylink' - my mistake. But trust me, it works ;) (Hope your Java is 1.5 at minimum)
ahh, and I assume, citylink is of type String[][]. Otherwise, please provide the declaration so I can adapt the code.
I don't understand the purpose of the second for loop: is it not filling the whole array with the last element?
What about:
int i=0;
for(Xml polh_is:fetchsite.child("site").child("poleis").children("polh")) { //url
if((polh_is.string("name")=="")||(polh_is.content()==""))//attribute
error += "Error in polh: name is - " + polh_is.string("name") + " with url - " + polh_is.content() + " -.\n";
else if (i >= citylink.length)
break;
else {
citylink[i][0]=HtmlMethods.removeBreaks(polh_is.string("name"));
citylink[i][1]=HtmlMethods.removeBreaks(polh_is.string("with url -"+polh_is.content() +"-.\n"));
i++;
}