Hey guys I don't get why I get an exception in this simple code
I'm trying to make a card game, and try to read the users wanted index of the card in his hand (it's in German)
public Karte abschlagen(Karte gegnK) {
System.out
.println("Bitte die Zahl für die jeweilige Karte auswählen: ");
gibHandAus(); // prints the users cards with their indexes
try {
Scanner sc = new Scanner(System.in);
int index = sc.nextInt();
if (index < 0 || index >= getHand().size()) {
System.out
.println("Bitte nur eine der gegebenen Zahlen auswählen!");
sc.close();
return abschlagen(gegnK);
}
Karte k = getHand().get(index);
getHand().remove(index);
sc.close();
So what's the problem here?
Before I can choose a number, it throws the noSuchElement exception.
I read in another question that the close() method can be causing this, but it still did it without it.
The error message is:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at durak.Spiel.spielerWehrtAb(Spiel.java:229)
at durak.Spiel.main(Spiel.java:314)
EDIT: Code of spielerWehrAb():
public static boolean spielerWehrtAb(Karte k) {
.
.
.
try {
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
sc.close();
if (x == 0) {
... }
else if(x == 1) {
System.out.println("1 ausgewählt");
Karte k2 = spieler.abschlagen(k);
....
}
else return spielerWehrAb(k);
The problem is Scanner.close(); closes the underlying stream. The second time, you're trying to read from a closed stream, so it obviously fails.
Please see the tests I designed to demonstrate this behavior here: java.util.Scanner strange behaviour when used with System.in
The solution would be not to read after closing the Scanner. You could, for example, define the Scanner as a class member and always use that member.
Related
I've created a custom Magic command with the intention of generating a spark query programatically. Here's the relevant part of my class that implements the MagicCommandFunctionality:
MagicCommandOutcomeItem execute(MagicCommandExecutionParam magicCommandExecutionParam) {
// get the string that was entered:
String input = magicCommandExecutionParam.command.substring(MAGIC.length())
// use the input to generate a query
String generatedQuery = Interpreter.interpret(input)
MIMEContainer result = Text(generatedQuery);
return new MagicCommandOutput(MagicCommandOutcomeItem.Status.OK, result.getData().toString());
}
This works splendidly. It returns the command that I generated. (As text)
My question is -- how do I coerce the notebook into evaluating that value in the cell? My guess is that a SimpleEvaluationObject and TryResult are involved, but I can't find any examples of their use
Rather than creating the MagicCommandOutput I probably want the Kernel to create one for me. I see that the KernelMagicCommand has an execute method that would do that. Anyone have any ideas?
Okay, I found one way to do it. Here's my solution:
You can ask the current kernelManager for the kernel you're interested in,
then call PythonEntryPoint.evaluate. It seems to do the job!
#Override
MagicCommandOutcomeItem execute(MagicCommandExecutionParam magicCommandExecutionParam) {
String input = magicCommandExecutionParam.command.substring(MAGIC.length() + 1)
// this is the Scala code I want to evaluate:
String codeToExecute = <your code here>
KernelFunctionality kernel = KernelManager.get()
PythonEntryPoint pep = kernel.getPythonEntryPoint(SCALA_KERNEL)
pep.evaluate(codeToExecute)
pep.getShellMsg()
List<Message> messages = new ArrayList<>()
//until there are messages on iopub channel available collect them into response
while (true) {
String iopubMsg = pep.getIopubMsg()
if (iopubMsg == "null") break
try {
Message msg = parseMessage(iopubMsg) //(I didn't show this part)
messages.add(msg)
String commId = (String) msg.getContent().get("comm_id")
if (commId != null) {
kernel.addCommIdManagerMapping(commId, SCALA_KERNEL)
}
} catch (IOException e) {
log.error("There was an error: ${e.getMessage()}")
return new MagicKernelResponse(MagicCommandOutcomeItem.Status.ERROR, messages)
}
}
return new MagicKernelResponse(MagicCommandOutcomeItem.Status.OK, messages)
}
So I have had an issue for a while now and thought it was worth the time to ask the more experienced regex guys if there was a way to fix this issue with a quick search and replace.
So i use a tool which generates java code(not written in java or I would manually fix the cause directly), however, it has an issue calling variables before an object is created.
This always occurs only once per object, but not for every object, the object name is unknown, and the error is always the line directly before the constructor is called. This is the format the error is always in:
this.unknownObjectName.mirror = true;
this.unknownObjectName = new Model(unknown, parameter, values);
I know there should be a trick to fix this, as a simple string replace simply will not work since 'unknownObjectName' is unknown.
Would this even be possible with regex, if so, please enlighten me :)
This is how the code SHOULD read:
this.unknownObjectName = new Model(unknown, parameter, values);
this.unknownObjectName.mirror = true;
For complex models, this error may happen hundreds of times, so this will indeed save a lot of time. That and I would rather walk on hot coals then do mindless busy work like fixing all these manually :)
Edit:
I through together a java app that does the job.
public static void main(String args[]){
File file = new File(args[0]);
File file2 = new File(file.getParentFile(), "fixed-" + file.getName());
try {
if(file2.exists()) {
file2 = new File(file.getParentFile(), "fixed-" + System.currentTimeMillis() + "-" + file.getName());
}
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file2)));
String line, savedline = null, lastInitVar = "";
while((line = br.readLine()) != null){
if(line.contains("= new ")){
String varname = line.substring(0, line.indexOf("=")).trim();
lastInitVar = varname;
}else if(line.contains(".mirror")){
String varname = line.substring(0, line.indexOf(".mirror")).trim();
if(!lastInitVar.equals(varname)){
savedline = line;
continue;
}
}else if(savedline != null && savedline.contains(lastInitVar)){
bw.write(savedline + "\n");
savedline = null;
}
bw.write(line + "\n");
}
bw.flush();
bw.close();
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Over thinking it
Write a program to read line by line and when you see a object access before a constructor don't write it out, write out the next line and then write out the buffered line, rinse repeat.
Some people, when confronted with a problem, think "I know, I'll use
regular expressions." Now they have two problems. - Jamie Zawinski
Regular Expressions are for matching patterns not state based logic.
I am new in this superb place. I got help several times from this site. I have seen many answers regarding my question that was previously discussed but i am facing problem to count the number of characters using FileReader. It's working using Scanner. This is what i tried:
class CountCharacter
{
public static void main(String args[]) throws IOException
{
File f = new File("hello.txt");
int charCount=0;
String c;
//int lineCount=0;
if(!f.exists())
{
f.createNewFile();
}
BufferedReader br = new BufferedReader(new FileReader(f));
while ( (c=br.readLine()) != null) {
String s = br.readLine();
charCount = s.length()-1;
charCount++;
}
System.out.println("NO OF LINE IN THE FILE, NAMED " +f.getName()+ " IS " +charCount);
}
}`
It looks to me that each time you go through the loop, you assign the charCount to be the length of the line that iteration of the loop is concerned with. i.e. instead of
charCount = s.Length() -1;
try
charCount = charCount + s.Length();
EDIT:
If you have say the document with the contents "onlyOneLine"
Then when you first hit the while check the br.readLine() will make the BufferredReader read the first line, during the while's code block however br.readLine() is called again which advances the BufferredReader to the second line of the document, which will return null. As null is assigned to s, and you call length(), then NPE is thrown.
try this for the while block
while ( (c=br.readLine()) != null) {
charCount = charCount + c.Length(); }
Is it possible to print a stack trace to a string in GWT? The usual methods of using the classes in java.io won't work I think, because the java.io package is not available clientside (and Writer, PrintWriter, etc are in that package)
Thank you
I'm not sure if StackTraceElement is emulated, but if it is you can run something like
for (StackTraceElement element : exception.getStackTrace()) {
string += element + "\n";
}
Here is the method I'm using to retrieve a full stack trace as a String in GWT :
private static String getMessage (Throwable throwable) {
String ret="";
while (throwable!=null) {
if (throwable instanceof com.google.gwt.event.shared.UmbrellaException){
for (Throwable thr2 :((com.google.gwt.event.shared.UmbrellaException)throwable).getCauses()){
if (ret != "")
ret += "\nCaused by: ";
ret += thr2.toString();
ret += "\n at "+getMessage(thr2);
}
} else if (throwable instanceof com.google.web.bindery.event.shared.UmbrellaException){
for (Throwable thr2 :((com.google.web.bindery.event.shared.UmbrellaException)throwable).getCauses()){
if (ret != "")
ret += "\nCaused by: ";
ret += thr2.toString();
ret += "\n at "+getMessage(thr2);
}
} else {
if (ret != "")
ret += "\nCaused by: ";
ret += throwable.toString();
for (StackTraceElement sTE : throwable.getStackTrace())
ret += "\n at "+sTE;
}
throwable = throwable.getCause();
}
return ret;
}
I would not recommend trying to display error stack trace in a GUI label.
1) They are not readable after GWT Obfuscation. They just look like bunch of tab aligned characters over new lines.
2) They are not in I18N format.
3) The correct way is the just show user a well formed error "Message" . exception.getMessage() will give you a single line of non-obf information which should provide the necessary UX interaction to user.
4) If you are looking for well formed exception stacktrace helpful for debugging ( not for user ) you should use GWT's well documented logging feature with web mode exceptions -
a) https://developers.google.com/web-toolkit/doc/latest/DevGuideLogging
b) Also read on http://code.google.com/p/google-web-toolkit/wiki/WebModeExceptions
Use com.google.gwt.logging.impl.StackTracePrintStream
Throwable t = ...;
StringBuilder message = new StringBuilder();
StackTracePrintStream ps = new StackTracePrintStream(message);
t.printStackTrace(ps);
ps.flush();
A qustion about Eclipse PDE development: I write a small plugin for Eclipse and have the following
* an org.eclipse.ui.texteditor.ITextEditor
* a line number
How can I automatically jump to that line and mark it? It's a pity that the API seems only to support offsets (see: ITextEditor.selectAndReveal()) within the document but no line numbers.
The best would be - although this doesn't work:
ITextEditor editor = (ITextEditor)IDE.openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file, true );
editor.goto(line);
editor.markLine(line);
It this possible in some way? I did not find a solution
on the class DetailsView I found the following method.
private static void goToLine(IEditorPart editorPart, int lineNumber) {
if (!(editorPart instanceof ITextEditor) || lineNumber <= 0) {
return;
}
ITextEditor editor = (ITextEditor) editorPart;
IDocument document = editor.getDocumentProvider().getDocument(
editor.getEditorInput());
if (document != null) {
IRegion lineInfo = null;
try {
// line count internaly starts with 0, and not with 1 like in
// GUI
lineInfo = document.getLineInformation(lineNumber - 1);
} catch (BadLocationException e) {
// ignored because line number may not really exist in document,
// we guess this...
}
if (lineInfo != null) {
editor.selectAndReveal(lineInfo.getOffset(), lineInfo.getLength());
}
}
}
Even though org.eclipse.ui.texteditor.ITextEditor deals wiith offset, it should be able to take your line number with the selectAndReveal() method.
See this thread and this thread.
Try something along the line of:
((ITextEditor)org.eclipse.jdt.ui.JavaUI.openInEditor(compilationUnit)).selectAndReveal(int, int);