im starting my adventure with learning to code in Java. Im stuck on an example from book. It does compile but there is no effect when I run it. The output is just blank. Im using Visual studio code. The example says that all 3 separate files (ProstyPortal, ProstyPortalGra & PomocnikGry) should be in 1 folder. When i try to start a file with main also nothing happens. I decided to join them all into one file but still i do get no result. The code is basically one line battleship game example.
ftp://ftp.helion.pl/przyklady/javrg2.zip - in folder r05 there are files (ProstyPortal, ProstyPortalGra & PomocnikGry) from the example that should work when in the same folder but they dont.
Damn, its really hard to find whats wrong when you just start learning :P
Its an example from chapter nr 5.
I did follow all the rules and sugestions as in the book but even a straight copying the code does not help. the previous examples i did run without bigger issues.
import java.io.*;
class ProstyPortalGra {
public static void main(String[] args) {
int iloscRuchow = 0;
PomocnikGry pomocnik = new PomocnikGry();
ProstyPortal portal = new ProstyPortal();
int liczbaLosowa = (int) (Math.random() * 5);
int[] polozenie = {liczbaLosowa, liczbaLosowa+1, liczbaLosowa+2};
portal.setPolaPolozenia(polozenie);
boolean czyIstnieje = true;
while (czyIstnieje == true) {
String pole = pomocnik.pobierzDaneWejsciowe("Podaj liczbę");
String wynik = portal.sprawdz(pole);
iloscRuchow++;
if (wynik.equals("zatopiony")) {
czyIstnieje = false;
System.out.println(iloscRuchow + " ruchów");
} // koniec if
} // koniec while
} // koniec main
}
class ProstyPortal {
int [] polaPolozenia;
int iloscTrafien;
public void setPolaPolozenia(int[] ppol) {
polaPolozenia = ppol;
}
public String sprawdz(String stringPole) {
int strzal = Integer.parseInt(stringPole);
String wynik = "pudło";
for (int pole : polaPolozenia) {
if (strzal == pole) {
wynik = "trafiony";
iloscTrafien++;
break;
}
} // koniec pętli
if (iloscTrafien == polaPolozenia.length) {
wynik = "zatopiony";
}
System.out.println(wynik);
return wynik;
} // koniec metody
} // koniec klasy
class PomocnikGry {
public String pobierzDaneWejsciowe(String komunikat) {
String wierszWej = null;
System.out.print(komunikat + " ");
try {
BufferedReader sw = new BufferedReader(
new InputStreamReader(System.in));
wierszWej = sw.readLine();
if (wierszWej.length() == 0) return null;
} catch (IOException e) {
System.out.println("IOException: " + e);
}
return wierszWej;
}
}
So you want it to print something? If that's the problem, then you must make sure that the if-statement that tests whether the wynik is equal to "zatopiony" actually happens to be true. You program will only give an output, if this if-statement is true.
I separated the classes into separate files with proper names located in the same folder. Still doesnt workin and i do get this error : error: cannot find symbol.
this error occurs for every separated class. I checked all common errors from this thread:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
Files are saved with UTF-8 encoding if that means anyting. When i saves with BOM encoding i got a lot more errors
Related
I am building a small Java utility (using Jackson) to catch errors in Java files, and one part of it is a text area, in which you might paste some JSON context and it will tell you the line and column where it's found it:
I am using the error message to take out the line and column as a string and print it out in the interface for someone using it.
This is the JSON sample I'm working with, and there is an intentional error beside "age", where it's missing a colon:
{
"name": "mkyong.com",
"messages": ["msg 1", "msg 2", "msg 3"],
"age" 100
}
What I want to do is also highlight the problematic area in a cyan color, and for that purpose, I have this code for the button that validates what's inserted in the text area:
cmdValidate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
functionsClass ops = new functionsClass();
String JSONcontent = JSONtextArea.getText();
Results obj = new Results();
ops.validate_JSON_text(JSONcontent, obj);
String result = obj.getResult();
String caret = obj.getCaret();
//String lineNum = obj.getLineNum();
//showStatus(result);
if(result==null) {
textAreaError.setText("JSON code is valid!");
} else {
textAreaError.setText(result);
Highlighter.HighlightPainter cyanPainter;
cyanPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.cyan);
int caretPosition = Integer.parseInt(caret);
int lineNumber = 0;
try {
lineNumber = JSONtextArea.getLineOfOffset(caretPosition);
} catch (BadLocationException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
JSONtextArea.getHighlighter().addHighlight(lineNumber, caretPosition + 1, cyanPainter);
} catch (BadLocationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
}
The "addHighlight" method works with a start range, end range and a color, which didn't become apparent to me immediately, thinking I had to get the reference line based on the column number. Some split functions to extract the numbers, I assigned 11 (in screenshot) to a caret value, not realizing that it only counts character positions from the beginning of the string and represents the end point of the range.
For reference, this is the class that does the work behind the scenes, and the error handling at the bottom is about extracting the line and column numbers. For the record, "x" is the error message that would generate out of an invalid file.
package parsingJSON;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class functionsClass extends JSONTextCompare {
public boolean validate_JSON_text(String JSONcontent, Results obj) {
boolean valid = false;
try {
ObjectMapper objMapper = new ObjectMapper();
JsonNode validation = objMapper.readTree(JSONcontent);
valid = true;
}
catch (JsonParseException jpe){
String x = jpe.getMessage();
printTextArea(x, obj);
//return part_3;
}
catch (IOException ioe) {
String x = ioe.getMessage();
printTextArea(x, obj);
//return part_3;
}
return valid;
}
public void printTextArea(String x, Results obj) {
// TODO Auto-generated method stub
System.out.println(x);
String err = x.substring(x.lastIndexOf("\n"));
String parts[] = err.split(";");
//String part 1 is the discarded leading edge that is the closing brackets of the JSON content
String part_2 = parts[1];
//split again to get rid of the closing square bracket
String parts2[] = part_2.split("]");
String part_3 = parts2[0];
//JSONTextCompare feedback = new JSONTextCompare();
//split the output to get the exact location of the error to communicate back and highlight it in the JSONTextCompare class
//first need to get the line number from the output
String[] parts_lineNum = part_3.split("line: ");
String[] parts_lineNum_final = parts_lineNum[1].split(", column:");
String lineNum = parts_lineNum_final[0];
String[] parts_caret = part_3.split("column: ");
String caret = parts_caret[1];
System.out.println(caret);
obj.setLineNum(lineNum);
obj.setCaret(caret);
obj.setResult(part_3);
System.out.println(part_3);
}
}
Screenshot for what the interface currently looks like:
Long story short - how do I turn the coordinates Line 4, Col 11 into a caret value (e.g. it's value 189, for the sake of argument) that I can use to get the highlighter to work properly. Some kind of custom parsing formula might be possible, but in general, is that even possible to do?
how do I turn the coordinates Line 4, Col 11 into a caret value (e.g. it's value 189,
Check out: Text Utilities for methods that might be helpful when working with text components. It has methods like:
centerLineInScrollPane
getColumnAtCaret
getLineAtCaret
getLines
gotoStartOfLine
gotoFirstWordOnLine
getWrappedLines
In particular the gotoStartOfLine() method contains code you can modify to get the offset of the specified row/column.offset.
The basic code would be:
int line = 4;
int column = 11;
Element root = textArea.getDocument().getDefaultRootElement();
int offset = root.getElement( line - 1 ).getStartOffset() + column;
System.out.println(offset);
The way it works is essentially counting the number of characters in each line, up until the line in which the error is occurring, and adding the caretPosition to that sum of characters, which is what the Highlighter needs to apply the marking to the correct location.
I've added the code for the Validate button for context.
functionsClass ops = new functionsClass();
String JSONcontent = JSONtextArea.getText();
Results obj = new Results();
ops.validate_JSON_text(JSONcontent, obj);
String result = obj.getResult();
String caret = obj.getCaret();
String lineNum = obj.getLineNum();
//showStatus(result);
if(result==null) {
textAreaError.setText("JSON code is valid!");
} else {
textAreaError.setText(result);
Highlighter.HighlightPainter cyanPainter;
cyanPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.cyan);
//the column number as per the location of the error
int caretPosition = Integer.parseInt(caret); //JSONtextArea.getCaretPosition();
//the line number as per the location of the error
int lineNumber = Integer.parseInt(lineNum);
//get the number of characters in the string up to the line in which the error is found
int totalChars = 0;
int counter = 0; //used to only go to the line above where the error is located
String[] lines = JSONcontent.split("\\r?\\n");
for (String line : lines) {
counter = counter + 1;
//as long as we're above the line of the error (lineNumber variable), keep counting characters
if (counter < lineNumber)
{
totalChars = totalChars + line.length();
}
//if we are at the line that contains the error, only add the caretPosition value to get the final position where the highlighting should go
if (counter == lineNumber)
{
totalChars = totalChars + caretPosition;
break;
}
}
//put down the highlighting in the area where the JSON file is having a problem
try {
JSONtextArea.getHighlighter().addHighlight(totalChars - 2, totalChars + 2, cyanPainter);
} catch (BadLocationException e1) {
// TODO Auto-generated catch block
e1.getMessage();
}
}
The contents of the JSON file is treated as a string, and that's why I'm also iterating through it in that fashion. There are certainly better ways to go through lines in the string, and I'll add some reference topics on SO:
What is the easiest/best/most correct way to iterate through the characters of a string in Java? - Link
Check if a string contains \n - Link
Split Java String by New Line - Link
What is the best way to iterate over the lines of a Java String? - Link
Generally a combination of these led to this solution, and I am also not targeting it for use on very large JSON files.
A screenshot of the output, with the interface highlighting the same area that Notepad++ would complain about, if it could debug code:
I'll post the project on GitHub after I clean it up and comment it some, and will give a link to that later, but for now, hopefully this helps the next dev in a similar situation.
I am currently working on a Java program that crawls a webpage and prints out some information from it.
There is one part that I can't figure out, and thats when I try to print out one specific String Array with some information in it, all it gives me is " ] " for that line. However, a few lines before, I also try printing out another String array in the exact same way and it prints out fine. When I test what is actually being passed to the "categories" variable, its the correct information and can be printed out there.
public class Crawler {
private Document htmlDocument;
String [] keywords, categories;
public void printData(String urlToCrawl)
{
nextURL=urlToCrawl;
crawl();
//This does what its supposed to do. (Print Statement 1)
System.out.print("Keywords: ");
for (String i :keywords) {System.out.print(i+", ");}
//This doesnt. (Print Statement 2)
System.out.print("Categories: ");
for (String b :categories) {System.out.print(b+", ");}
}
public void crawl()
{
//Gather Data
//open up JSOUP for HTTP parsing.
Connection connection = Jsoup.connect(nextURL).userAgent(USER_AGENT);
Document htmlDocument = connection.get();
this.htmlDocument=htmlDocument;
System.out.println("Recieved Webpage "+ nextURL);
int guacCounter = 0;
for(Element guac : htmlDocument.select("script"))
{
if(guacCounter==5)
{
//String concentratedGuac = guac.toString();
String[] items = guac.toString().split("\\n");
categories = processGuac(items);
break;
}
else if(guacCounter<5) {
guacCounter++;
}
}
}
public String[] processKeywords(String totalKeywords)
{
String [] separatedKeywords = totalKeywords.split(",");
//System.out.println(separatedKeywords.toString());
return separatedKeywords;
}
public String[] processGuac(String[] inputGuac)
{
int categoryIsOnLine = 6;
String categoryData = inputGuac[categoryIsOnLine-1];
categoryData = categoryData.replace(",","");
categoryData = categoryData.replace("'","");
categoryData = categoryData.replace("|",",");
categoryData = categoryData.split(":")[1];
//this prints out the list of categories in string form.(Print Statement 3)
System.out.println("Testing here: " + categoryData.toString());
String [] categoryList=categoryData.split(",");
//This prints out the list of categories in array form correctly.(Print statement 4)
System.out.println("Testing here too: " );
for(String a : categoryList) {System.out.println(a);}
return categoryList;
}
}
I cut out a lot of the irrelevant parts of my code so there might be some missing variables.
Here is what my printouts look like:
PS1:
Keywords: What makes a good friend, making friends, signs of a good friend, supporting friends, conflict management,
PS2:
]
PS3:
Testing here: wellbeing,friends-and-family,friendships
PS4:
Testing here too:
wellbeing
friends-and-family
friendships
This is my whole code, it's quite complex but please help me. It's taken me for 2 days but I failed:
public static ArrayList<DocGia> XuatDocGia() throws IOException {
ArrayList<DocGia> listDocGia = new ArrayList<>();
File fileDocGia = new File("fileDocGia.txt");
if(fileDocGia.exists() == false) {
System.out.println("Chưa có đọc giả nào trong thư viện");
} else {
BufferedReader br = new BufferedReader(new FileReader("fileDocGia.txt"));
if (br.readLine() == null) {
System.out.println("Chưa có đọc giả nào trong thư viện");
} else {
int soDong = DemSoDong("fileDocGia.txt");
int dongHienTai = 0;
Scanner fileScanner = new Scanner(fileDocGia);
for(int i = 0, z = 0;;i++, z++) {
DocGia docGia = null;
System.out.println("***Đọc giả thứ: " + (i+1));
docGia.tendocgia = fileScanner.nextLine();
if(i >= 1) {
docGia.tendocgia = fileScanner.nextLine();
}
docGia.maDocGia = fileScanner.nextLine();
docGia.soSachmuon = fileScanner.nextInt();
docGia.thoiGianMuonSach = fileScanner.nextInt();
listDocGia.add(docGia);
docGia.XuatDocGia();
dongHienTai += 4;
if(dongHienTai == soDong) {
fileScanner.close();
break;
}
}
}
for(DocGia docGia: listDocGia) {
docGia.XuatDocGia();
}
}
return listDocGia;
}
look at my code, when i run:
docGia.XuatDocGia();
-> the value of every single element is right at debug. it also means the value of the variable inside is right. but at the end of this function. i run
for(DocGia docGia: listDocGia) {
docGia.XuatDocGia();
}
this is XuatDocGia funtion:
public static void XuatDocGia(){
System.out.println(tendocgia);
System.out.println(maDocGia);
System.out.println(soSachmuon);
System.out.println(thoiGianMuonSach);
}
It just shows for me the last element in this ArrayList, repeat in 3 times( equal the number of elements).
I think a problem come from adding process of listDocGia.add(docGia);
You guys no need to bother everything else in my code, because i know it's really complex. I have tested carefully, just focus on my problem.
I'm so sorry because i'm Vietnamese and beginner at Java. The next time everything will be English. Thank you so much.
If this is the actual code, you are adding null references to your List, but since you are using a static method to print the values, you don't get a NullPointerException. Assuming your code passes compilation, this means all the members of the DocGia class are static, which explains why you get the same values in each iteration of your loop.
You should change
DocGia docGia = null;
to
DocGia docGia = new DocGia ();
and change all the members of DocGia (including the XuatDocGia method that prints them) to be non static.
I am new to MVC and following this link I have a search page for resulting pdf metadatas by using Solr. My if statement and for loop in html side do not work
Searching.java in models folder:
public class Searching {
public String q;
public String outputTitle;
public String outputAuthor;
public String outputContent;
public String outputPage;
public String outputPath;
}
search function in Application.java:
final static Form<Searching> searchForm = form(Searching.class);
final static List<Searching> searchList = new ArrayList<Searching>();
public static Result search() {
Form<Searching> filledForm = searchForm.bindFromRequest();
Searching searched = filledForm.get();
....(database connection lines)
QueryResponse response = solr.query(query);
SolrDocumentList results = response.getResults();
if(results.isEmpty())
System.out.println("SEARCH NOT FOUND");
else {
for (int i = 0; i < results.size(); ++i) {
searched.outputTitle = (String)results.get(i).getFirstValue("title");
searched.outputAuthor = (String)results.get(i).getFirstValue("author");
searched.outputPage =results.get(i).getFirstValue("pageNumber").toString();
searched.outputContent = (String)results.get(i).getFirstValue("content");
searched.outputPath = (String)results.get(i).getFirstValue("path");
searchList.add(searched);
}
System.out.println("\nresults.getNumFound(): "+ searched.outputFound);
System.out.println("results.size(): "+results.size());
}
return play.mvc.Results.ok(search.render(searched, searchForm, searchList));
}
search.scala.html
#(searched: Searching, searchForm: Form[Searching], searchList: List[Searching])
.. some buttons,a search bar...
#if(searchList.isEmpty()) {
<h1>Error</h1>
} else {
#for(search <- searchList) {
<ul>Title: #search.outputTitle</ul>
<ul>Author: #search.outputAuthor <a href="#search.outputPath" download>Download PDF</a></ul>
<ul>Number of Page(s): #search.outputPage</ul>
}
}
Java code works well. I can see outputs on the terminal, but my html side has problem and it shows one book many times according to size of searchList
I am posting the answer explicitly even though I was able to help the OP in the chat - maybe somebody else is running into such problem but did not check the chat:
The problem is even though you have the line in the for-loop you are still using the same searched variable. What you have to do is to reinitialize the variable when entering the loop. Something like:
for (...) {
searched = new Searching();
searched.outputTitle = (String)results.get(i).getFirstValue("title");
....
searchList.add(searched);
}
This solves the problem with the duplicates and everything is fine now.
First apologies, I'm mainly a Perl person doing some Java. I've read some literature but can't get this to give me the signature that I need:
logger.debug("Entered addRelationships");
boolean rval = true;
for(int i=0;i<relationships.length;i++)
{
URI converted_uri ;
try {
converted_uri = new URI("relationships[i].datatype") ;
} catch (URISyntaxException e) {
logger.error("Error converting datatype", e);
return rval = false ;
}
boolean r = addRelationship(context, relationships[i].subject,
relationships[i].predicate, relationships[i].object,
relationships[i].isLiteral, converted_uri);
if(r==false)
{
rval = false;
}
}
return rval;
}
The resulting error is:
addRelationship(org.fcrepo.server.Context,java.lang.String,java.lang.String,java.lang.String,boolean,java.lang.String) in org.fcrepo.server.management.DefaultManagement cannot be applied to (org.fcrepo.server.Context,java.lang.String,java.lang.String,java.lang.String,boolean,java.net.URI)
It seems to me that converted_uri is a URI at the end of this? datatype was a String in the previous release, so no gymnastics were required!
Just remove the qoutes:
converted_uri = new URI(relationships[i].datatype) ;
When you are using quotes, exactly as in perl you are dealing with string literal. If you want to refer to variable you have to mention it in code directly.
While #AlexR pointed out another problem in your code, it's not the cause of the problem you identified in your question.
You had a compile error, and an error in the syntax of the URI will only show up at runtime like the one that #AlexR identified.
The problem you have is that you are trying to pass a URI as the last argument, but the method addRelationship expects a String as the last argument. That's what the error says.
(The first part of the error says what the signature of the method is in reality, as you see it ends in java.lang.String, while the second part of the error says what type of data you are trying to give to the method, and as you see that one ends in java.net.URI)
So it seems that the URI was not changed as you expected; it still needs a String.
Solution is to change your code to:
boolean rval = true;
for(int i = 0; i < relationships.length; i++)
{
boolean r = addRelationship(context, relationships[i].subject,
relationships[i].predicate, relationships[i].object,
relationships[i].isLiteral, relationships[i].datatype);
if (!r)
{
rval = false;
}
}
return rval;