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++;
}
Related
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());
}
}
I have the following method in a program of mine that allows a user to enter a unique ID that is associated with a laptop in an ArrayList.
The desired output is as follows:
If the ID entered by the user matches an ID in the ArrayList, the laptop and its specifications will print out.
If the ID does not match, it will print out "Invalid ID".
I am very close to achieving this; however I can only figure out how to get it to print whether or not it matches for each laptop in the list. So for example, if the ID entered by the user matches one of three laptops in the list it will print as follows:
Acer Predator Helios 300 CPU: Intel i7-9750h GPU: NVIDIA GTX1660ti Memory: 16GB ID: 1234567
Invalid ID.
Invalid ID.
So my question is: how do I get it to print ONLY the single match or "Invalid ID" while still being able to loop through the entire list to check for a match? Not necessarily asking you to spoon feed me the fix, but at least help point me in the right direction or help with the logic. I thank you in advance for any help!
My method is as follows:
private static void findLaptop(ArrayList arr) {
//Prompt user to input an ID.
System.out.println("Input ID: ");
System.out.println();
//Scan for user input.
Scanner keyboard = new Scanner(System.in);
int inputId = keyboard.nextInt();
//Loop through ArrayList and check for a match.
for(int i=0; i<arr.size(); i++) {
//If entered ID matches, print laptop information.
if(inputId == ((Laptops) arr.get(i)).getId()) {
System.out.println(((Laptops)arr.get(i)).getModel() + " CPU: " + ((Laptops)arr.get(i)).getCpu() + " GPU: " +
((Laptops)arr.get(i)).getGpu() + " Memory: " + ((Laptops)arr.get(i)).getMemory() + "GB ID: " +
((Laptops)arr.get(i)).getId());
}
//If entered ID does not match, print invalid ID.
else if(inputId != ((Laptops) arr.get(i)).getId()) {
System.out.println("Invalid ID.");
}
}
}
Use below code:
//Create a boolean
boolean found= false;
for(int i=0; i<arr.size(); i++) {
//If entered ID matches, print laptop information.
if(inputId == ((Laptops) arr.get(i)).getId()) {
System.out.println(((Laptops)arr.get(i)).getModel() + " CPU: " + ((Laptops)arr.get(i)).getCpu() + " GPU: " +
((Laptops)arr.get(i)).getGpu() + " Memory: " + ((Laptops)arr.get(i)).getMemory() + "GB ID: " +
((Laptops)arr.get(i)).getId());
//set boolean true and break
found = true;
break;
}
}
//Out side the look check If entered ID does not match, print invalid ID.
if(!found) {
System.out.println("Invalid ID.");
}
You can do this using a return statement that is used after printing a match
for(int i=0; i<arr.size(); i++) {
//If entered ID matches, print laptop information.
if(inputId == (arr.get(i)).getId()) {
System.out.println((arr.get(i)).getModel() + " CPU: " + (arr.get(i)).getCpu() + " GPU: " +
(arr.get(i)).getGpu() + " Memory: " + (arr.get(i)).getMemory() + "GB ID: " +
(arr.get(i)).getId());
return;
}
}
// outside loop
System.out.println("Invalid ID.");
edit
If you have you ArrayList set up properly as ArrayList<Laptop> then you would not need all those crazy casts.
edit2
If you a foreach loop it would be even cleaner
for (Laptop lt : arr) {
if (iputId == lt.getId()) // etc
Supposing you have a class called Laptop as follows:
public class Laptop {
private String id;
private String manufacturer;
// other fields
// getters and setters
}
You can find matches with an id using Java 8 Streams:
List<Laptop> laptops = ...
String idToSearch = "something";
Optional<Laptop> result = laptops.stream() // convert into stream for easier handling
.filter(l -> l.getId().equals(idToSearch)) // find only laptops with a matching id
.findFirst(); // find the first one, if present
The variable result is an Optional<Laptop>, meaning it may or may not contain a Laptop value. You can consume this result as follows:
Laptop laptop = result.get(); // throws an exception if no value present, not reccomended
Laptop laptop = result.orElse(null); // returns null if no value present
result.ifPresent(laptop -> {
doSomething(laptop); // this function is only called if a value is present
})
So, I've been frollicking around with this for a while and encountered things like using Format and /t and what not. But I still cant figure out how to properly outline the output of my println made by this for loop:
for (int i = 0; i < AANTAL_CIJFERS; i++) //Toon cijfers per vak
{
System.out.println("Vak/project:\t" + vakken[i] + "\tCijfer\t: " + cijfers[i] + "\tBehaalde punten: " + puntBehaald(i));
}
It currently prints like this:
But i'd like the printline to look more like this:
But I just cant figure it out, anybody know how I could accomplish this?
On this case you have to use java System.out.printf()or String.format() methods instead of System.out.print() or System.out.println()
Please read this exmples how-to-use-formatting-with-printf-correctly-in-java and tabs-does-not-result-in-aligned-columns for more details.
Also here is a helpful article java-string-format-examples
I just update the code to be as the following and it works fine with me :
private static String format = "%s %-30s ";
private static String format2 = "%s %3s ";
.
.
for (int i = 0; i < AANTAL_CIJFERS; i++) //Toon cijfers per vak
{
System.out.printf(format, "Vak/project: ", vakken[i]);
System.out.printf(format2, "Cijfer: ", cijfers[i]);
System.out.printf(format2, "Behaalde punten: ", puntBehaald(i));
System.out.printf("%n");
}
So I am now using this as code:
for (int i = 0; i < AANTAL_CIJFERS; i++) //Toon cijfers per vak
{
System.out.printf(format, "Vak/project: ", vakken[i]);
System.out.printf(format, "Cijfer: ", cijfers[i]);
System.out.printf(format, "Behaalde punten: ", puntBehaald(i));
System.out.printf("\n");
}
Which gives this:
So it clearly doesnt work the way I'd expect it to from the documentation. What am I doing wrong?
It should be: Vak/project: "output from vakken[i]" TAB Cijfer: "output from cijfers[i]" TAB Behaalde punten: "output from puntBehaald(i)".
This is my format right now: private static String format = "%-20s%s";
I was trying to concatenate a string to itself + something else, like this:
String example = " "
for (int i = 0; i < 5; i++) {
if (condition OK) {
example = example + "\nAnother text";
}
}
JOptionPane.showMessageDialog(null, example);
In my mind, it should've print " (new line)Another text" but it seems to work only with the last entry in my "Another text". Like, if the condition inside the "for" loop is OK 3 times, it prints " (new line)Another text(3)" instead of " (new line) Another Text(1) (new line) Another text(2)...
Any idea of what may be happening?
EDIT: after realizing that my code was fine, I followed afzalex recommendation and found out the error was in my condition. Thanks bro
I used below program I got expected output.
String example = " ";
for (int i = 0; i < 5; i++) {
if (i == 1 || i == 3) {
example = example + "\nAnother text";
}
}
System.out.println(example);
Output:
Another text
Another text
So, probably it could be something wrong with JOptionPane.showMessageDialog(null, example); If it is being interpreted as HTML in the end, then better use </br> instead of \n, that can give you new line.
I have a number of xml's that come in haphazardly that contain a Ocount, and Lnumber, as well as other data. I have created a class to get that data.
My problem is that how can I group xml's that have the same Lnumber(string), until it reaches the Ocount(int). (the xmls that have the same lnumber has the same Ocount). And eventually send out a email telling with xmls has been processed.
String readLine = FileHandler.checkListFile(sh.getShipmentHeader().getBillToCustomer());
if (!readLine.isEmpty())
{
int orderCount = 0;
int index = readLine.indexOf(";") + 1;
String customerName = readLine.substring(index, readLine.indexOf(";", index)).trim();
index = readLine.indexOf(";", index) + 1;
String to = readLine.substring(index, readLine.length()).trim();
if (!billMap.containsKey(sh.getShipmentHeader().getBillToCustomer()))
{
billMap.put(sh.getShipmentHeader().getBillToCustomer(), 1);
orderCount = 1;
}
else
{
billMap.put(sh.getShipmentHeader().getBillToCustomer(), ((int) billMap.get(sh.getShipmentHeader().getBillToCustomer())) + 1);
orderCount = (int) billMap.get(sh.getShipmentHeader().getBillToCustomer());
}
outboundMessage += sh.getShipmentHeader().getOrderNumber() + li ;
logger.info("On-Demand Outbound Export Info: " + orderCount + " processed out of " + sh.getShipmentHeader().getOrderCount() +
" for " + customerName);
if (orderCount == sh.getShipmentHeader().getOrderCount())
{
Email email = new Email();
billMap.remove(sh.getShipmentHeader().getBillToCustomer());
outboundMessage += li + "Total of #"+ sh.getShipmentHeader().getOrderCount() + " orders processed for "+ customerName + li ;
logger.info("On-Demand Email sent for " + customerName);
System.out.println(outboundMessage);
email.outboundEmail("TEST: Orders for " + customerName + " complete", outboundMessage, to);
outboundMessage = "";
email = null;
}}
I been working on this for days, where am I going wrong.
It seems like you are having difficulty obtaining information from xmls. I suggest using XStream [1]. It is capable of serialising objects to xml and back. By using XStream, you can get an Object from the xml and compare variables (Lnumber and Ocount) easily.
If you insist using this code, I suggest adding comments to notify us what you are doing, but if want an easier alternative to work with xml files using java, I highly suggest using XStream as a solution.
[1] http://x-stream.github.io/