Java for each issue - java

Actually I was searching for an example or similar question in Stackoverflow and I find this one : Java Objective-C for each issue. So that's why I'll give the code which Android-Droid is using in his example.The thing that I need to do is similar to the Objective C code that he is using :
StPacketInjectQueryPackage qType = (StPacketInjectQueryPackage)[[q objectForKey:#"type"] intValue]; .
According to his code...my question is how can I do that...using his Java code?
EDIT (My Problem):
If I use his code, how can I get the objectForKey:#"type" in Java.I guess it has to be similar to this :
RPCPacketInjectQueryPackage qType = (RPCPacketInjectQueryPackage) b.getKeys
OR b.get("type"); or something like that...
Any suggestions?

For-each in Java is pretty well documented in the standard Java documentation. For example: http://download.oracle.com/javase/1,5.0/docs/guide/language/foreach.html
If that doesn't adequately explain how to do what you're trying to do, I would suggest taking a stab at it in Java and then asking a question on StackOverflow about what is wrong with your code if you can't get it to work.

The closest thing in Java is a new (1.5 or 1.6) "enhanced" for loop.
Iterable<Element> list = ....
for (Element el : list) {
System.out.println(el);
}

Related

Java: READ and WRITE are "ambiguous" when using FileChannel with ByteChannel?

I am learning Java through an introductory course using the textbook, Java Programming 9th Edition by Joyce Farrel. The examples and exercises are written for Java 9e, however, I am using Java SE 14.
I've successfully navigated Java API and found updates as well as useful explanations as to what errors I have been encountering between the two versions and what is the best way to make corrections to get the examples and exercises to work.
However, in this case, I have been having a really hard time. I'm pretty sure it's due to the lack of experience, but I can't find anything I can understand using the Java API that has given me an idea on how to resolve this issue. Google and Stackoverflow posts have not been that much more successful as I am assuming people are using a much more streamlined method or approach.
Code with the comment on the line in question:
...
Path rafTest = Paths.get("raf.txt");
String addIn = "abc";
byte[] data = addIn.getBytes();
ByteBuffer out = ByteBuffer.wrap(data);
FileChannel fc = null;
try {
fc = (FileChannel)Files.newByteChannel(file, READ, WRITE); // Error READ and Write is ambiguous?
...
} catch (Exception e){
System.out.println("Error message: " + e);
}
...
What is the best way to go about finding an approach to figuring out what exactly is going here?
#Bradley: Found the answer by trying to rewrite my question. The compiler returned 3 specific errors dealing with StandardOpenOption. Using that and Java API, I found the solution. Thank you.
#NomadMaker: First thought was that I did not include the package correctly for newByteChannel. The second options were that the arguments needed a more specific reference.
Answer: newByteChannel(...); requires the open options argument to reference the StandardOpenOption.READ and WRITE. So that:
...newByteChannel(raf, StandardOpenOption.READ, StandardOpenOption.WRITE);
This change was implemented in Java SE 11. The program now works correctly.

Finding Object in Array of Arrays based in Sub-Object condition

I need to find a object in java based in the property of its many subojects.
What I currently have is ugly as hell and I'm sure there's a more efficient way to do so.
Probably with a library like hamcrest, or maybe directly with Java (my knowledge in Java is not the best).
This is what I have so far:
private HotelResult findHotelResult(List<HotelResult> hotelResultsList, HotelSelection hotelSelection) {
for (HotelResult hotelResult : hotelResultsList)
for (RoomOption roomOption : hotelResult.getRoomOptions())
for (RoomTypeIds roomTypeIds : roomOption.getRoomTypeIds())
for (RoomRateIds roomRateIds : roomTypeIds.getRoomRateIds())
if ( roomRateIds.getId().equals(hotelSelection.getResultId()) )
return hotelResult;
(...)
}
Thank you in advance.
Try this if you are using Java 8 o higher...
private HotelResult findHotelResult(List<HotelResult> hotelResultsList, HotelSelection hotelSelection) {
Optional<HotelResult> found = hotelResultsList.stream().filter((r) -> {
Optional<RoomRateIds> optId = r.getRoomOptions().stream().flatMap(o -> o.getRoomTypeIds().stream())
.flatMap(rate -> rate.getRoomRateIds().stream())
.filter(id -> id.getId().equals(hotelSelection.getResultId())).findFirst();
return optId.isPresent();
}).findFirst();
return found.orElse(null);
}
There is no more efficient way of doing so, at least not without re-organizing your data model from what it currently is into something completely different.
There is nothing wrong with nice, cleanly laid out nested loops, making very clear what is happening. You could perhaps replace them with a sequence of forEach( ...forEach( ... forEach( ... ) ) ) but then you will have an undecipherable tangle of parentheses to deal with, the purpose of the code will be less clear, debugging the code will become next to impossible, and performance will suffer.
The only thing that could be improved in the code that you have shown us would be to either get rid of the unnecessary blank lines, or get rid of the egyptian-style curly braces, or both, since every single curly brace in that code is unnecessary.
That, alone, might make the code look less as if it could use some improvement. Since it doesn't.

Using Julia JavaCall with Java DecimalFormat (à la MATLAB)

I don't know java and can't get JavaCall.jl to work with java.text.DecimalFormat. In MATLAB this is very simple -- just check out this link.
Reading the JavaCall.jl documentation, I tried replicating the provided example with DecimalFormat and got this far:
julia>using JavaCall
julia>JavaCall.init(["-Xmx128M"])
julia>jdf = #jimport java.text.DecimalFormat
After that, I got a bunch of errors. (bear in mind: I absolutely have no clue as to how Java works?)
Please help!
It's not clear from the question whether you're looking to know more about JavaCall.jl or just to use some comma separated formatting.
If the latter, then you can use the Formatting.jl package: https://github.com/JuliaIO/Formatting.jl
julia> using Formatting
julia> sprintf1("%'.02f", 123456789)
"123,456,789.00"
And then you don't need any Java.
This package also has a bunch of other formatting options.

Jython: "no viable alternative at input" when i try to append to list of strings

Attempting to re-write the Minecraft Launcher in jython as i have a rather basic knowledge of java but i believe im competent enough with python to undertake this task. I've been translating the decompiled classes as best as i can, but i'm encountering this SyntaxError whenever i try to append strings to my list launchParameters.
The reason why i'm puzzled as to why this is happening is because the first .append() worked for my list, but after that i get the mentioned SyntaxError thrown at me from the console.
#classmethod
def main(cls, paramArrayofString):
maxHeap = 1024
minHeap = 511
runtimeMemory = float(Runtime.getRuntime().maxMemory() / maxHeap / maxHeap)
if (runtimeMemory > minHeap):
LauncherFrame.main(paramArrayofString)
else:
try:
someString = CraftiLauncher.__class__.getProtectionDomain().getCodeSource().toURI().getPath()
launchParameters = []
if (Util.getPlatform() == "Windows"):
launchParameters.append("javaw")
else:
launchParameters.append("java")
launchParameters.append("-Xmx1024m") #This one appears to work
launchParameters.append("-Dsun.java2d.noddraw=true") #This is where i get my first error
launchParameters.append("-Dsun.java2d.d3d=false")
launchParameters.append("-Dsun.java2d.opengl=false")
launchParameters.append("-Dsun.java2d.pmoffscreen=false")
launchParameters.append("-classpath")
launchParameters.append(someString)
launchParameters.append("net.Crafti.LauncherFrame")
localProcessBuilder = ProcessBuilder(launchParameters)
localProcess = localProcessBuilder.start()
if (localProcess == None):
sys.exit()
if there's anything i need to elaborate on, please ask; if you think there's a page that might help me, feel free to link it!
Thanks in advance!
Well, i'm not entirely sure why i was getting the error, but it seems that just a simple fix of code indentation was the answer the whole time.
I didn't even change the indentation at all; i just simply dedented and indented everything again and now it works!

Porting XML parsing from Java to Objective C

I am trying to port code written in Java to Objective C (for iPhone), but I'm kind of confused about a few lines of my code (mentioned below). How should I port this efficiently?
Namespace nmgrhistory=Namespace.getNamespace("history", "http://www.mywebsite.com/History.xsd");
pEventEl.addContent(new Element("History",nmgrhistory));
Namespace nmgrState=Namespace.getNamespace("state", "http://www.mywebsite.com/State.xsd");
pEventEl.addContent(new Element("State",nmgrState));
Iterator<Element> eld=(Iterator<Element>) pEventEl.getChild(
pEventEl.getName() == "event"? "./history:history/state:state" : "./state:state",pEventEl.getNamespace());
I'm not very sure about the replacements for the classes Namespace, Iterator and Element.
Anybody having idea or having done this before, please enlighten me.
Ok... So although these are not the actual replacements ... But basically what u need for parsing XML in Objecive - C is "NSXMLParser"
so u can say that NSXMLParser is the replacement for Namespace
And for "Iterator" NSXMLParserDelegate has a method named:-
– parser:didStartElement:namespaceURI:qualifiedName:attributes:
OR
– parser:foundCharacters:
I don't know java, but the url's your are pointing at are .xsd files which are xml definition files. XML parsing on iOS is somewhat limited out of the box: NSXMLParser.
I strongly recommend one of the bazillion open source XML parsers. They're much more user friendly.
Well thanks to all for making the efforts to answer, but I got a nice library TouchXML that solves the purpose.

Categories

Resources