I am trying to make a game with LibGDX, and am having some problems with a certain class (WorldGen.java). Every time I try to run the code normally, I get a black screen that says it is Not Responding when clicked, and there appear to be no errors. The program runs fine when any references to the methods in WorldGen.java are commented out. This seemed to work fine previously, and I have only changed the if statement in this class since then.
This code is intended to create an array of Strings, convert that to a List, and then print that to a txt file.
package com.mygdx.rpg;
import java.io.IOException;
import java.nio.charset.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class WorldGen {
static List<String> printString = new ArrayList<String>();
static String username = System.getProperty("user.name");
static String mapData;
static Path mapSavePath = Paths.get("C:\\Users\\"+username+"\\Desktop\\MapFile.txt");
static Charset utf8 = StandardCharsets.UTF_8;
static String[] map = new String[1000000]; //right = +1, down = +100
//problem with generate class, causes black screen and Not Responding to occur
public static void generate(){
for(int i=0;i<1000000;i++){ //1000 x 1000 tiles, encompasses ALL world generation
if(i>-1 && i<1001 || i>999000 && i<1000001){
map[i]="-"; //void (top/bottom edges, must add to all tiles bordering edges of map)
}else if(i%1000==0){
map[i]="-"; //adds void to multiples of 1000 & 999+multiples of 1000 (left/right edges)
map[i-1]="-";
}else{
map[i]="G"; //grass
}
mapData = Arrays.toString(map);
mapData = mapData.replaceAll("\\[","").replaceAll("\\]","").replaceAll(",","");
printString.add(mapData);
}
}
public static void writeToFile(){
try{
Files.write(mapSavePath,printString,utf8);
}catch(IOException e){e.printStackTrace();}
}
Related
I have simple java code to select the file and return array.
When I use dedicated method (whole code below), my compilation (in IntelliJ) does not end -> it gets to the last lane of public static void main(String[] arg), it executes last lane System.out.println("Program ends."); but I don't get information from compilator:
Process finished with exit code -1
Instead I need to stop it manually and if I want to run it again I get information that I can't run the code in parallel, would I like to stop it and rerun now.
Whole code:
import java.util.HashMap; //import the HashMap class
import java.io.File; // Import the File class
import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files
import java.awt.FileDialog;
import java.awt.Frame;
public class Project1
{
public static void main(String[] arg)
{
HashMap<Integer, int[][]> dicUsedFuncs = new HashMap<Integer, int[][]>();
//import textfile with haskell code
String[] arrString=SelectFile();
System.out.println(arrString[0]);
System.out.println(arrString[1]);
//scan load
System.out.println("End");
}
private static String[] SelectFile()
{
String[] arrReturn = new String[2];
String strDefaultPath=System.getProperty("user.dir"); //default location to open
Frame frame = null;
FileDialog fd = new FileDialog(frame, "Please choose a text file with code.", FileDialog.LOAD);
fd.setDirectory(strDefaultPath);
fd.setFile("*.txt");
fd.setVisible(true);
String filename = fd.getFile(); //get just the selected file name
if (filename == null) {
arrReturn[0] = "NotSelected";
}else {
filename= new File(fd.getFile()).getAbsolutePath(); //get full file path of selected file
arrReturn[0] = "Selected";
arrReturn[1] = filename;
}
return arrReturn;
}
}
I added following:
library
import java.awt.Window;
loop to close all windows in method private static String[] SelectFile()
for (Window window : Window.getWindows()) { window.dispose(); }
I am using pdf-clown with pdfclown-0.2.0-HEAD.jar.I have written below code for highlighting search the keyword in Chinese language pdf file and same code is working fine with english pdf file.
import java.awt.Color;
import java.awt.Desktop;
import java.awt.geom.Rectangle2D;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.BufferedInputStream;
import java.io.File;
import org.pdfclown.documents.Page;
import org.pdfclown.documents.contents.ITextString;
import org.pdfclown.documents.contents.TextChar;
import org.pdfclown.documents.contents.colorSpaces.DeviceRGBColor;
import org.pdfclown.documents.interaction.annotations.TextMarkup;
import org.pdfclown.documents.interaction.annotations.TextMarkup.MarkupTypeEnum;
import org.pdfclown.files.SerializationModeEnum;
import org.pdfclown.util.math.Interval;
import org.pdfclown.util.math.geom.Quad;
import org.pdfclown.tools.TextExtractor;
public class pdfclown2 {
private static int count;
public static void main(String[] args) throws IOException {
highlight("ebook.pdf","C:\\Users\\Downloads\\6.pdf");
System.out.println("OK");
}
private static void highlight(String inputPath, String outputPath) throws IOException {
URL url = new URL(inputPath);
InputStream in = new BufferedInputStream(url.openStream());
org.pdfclown.files.File file = null;
try {
file = new org.pdfclown.files.File("C:\\Users\\Desktop\\pdf\\test123.pdf");
Map<String, String> m = new HashMap<String, String>();
m.put("亿元或","hi");
m.put("收入亿来","hi");
System.out.println("map size"+m.size());
long startTime = System.currentTimeMillis();
// 2. Iterating through the document pages...
TextExtractor textExtractor = new TextExtractor(true, true);
for (final Page page : file.getDocument().getPages()) {
Map<Rectangle2D, List<ITextString>> textStrings = textExtractor.extract(page);
for (Map.Entry<String, String> entry : m.entrySet()) {
Pattern pattern;
String serachKey = entry.getKey();
final String translationKeyword = entry.getValue();
/*
if ((serachKey.contains(")") && serachKey.contains("("))
|| (serachKey.contains("(") && !serachKey.contains(")"))
|| (serachKey.contains(")") && !serachKey.contains("(")) || serachKey.contains("?")
|| serachKey.contains("*") || serachKey.contains("+")) {s
pattern = Pattern.compile(Pattern.quote(serachKey), Pattern.CASE_INSENSITIVE);
}
else*/
pattern = Pattern.compile(serachKey, Pattern.CASE_INSENSITIVE);
// 2.1. Extract the page text!
//System.out.println(textStrings.toString().indexOf(entry.getKey()));
// 2.2. Find the text pattern matches!
final Matcher matcher = pattern.matcher(TextExtractor.toString(textStrings));
// 2.3. Highlight the text pattern matches!
textExtractor.filter(textStrings, new TextExtractor.IIntervalFilter() {
public boolean hasNext() {
// System.out.println(matcher.find());
// if(key.getMatchCriteria() == 1){
if (matcher.find()) {
return true;
}
/*
* } else if(key.getMatchCriteria() == 2) { if
* (matcher.hitEnd()) { count++; return true; } }
*/
return false;
}
public Interval<Integer> next() {
return new Interval<Integer>(matcher.start(), matcher.end());
}
public void process(Interval<Integer> interval, ITextString match) {
// Defining the highlight box of the text pattern
// match...
System.out.println(match);
/* List<Quad> highlightQuads = new ArrayList<Quad>();
{
Rectangle2D textBox = null;
for (TextChar textChar : match.getTextChars()) {
Rectangle2D textCharBox = textChar.getBox();
if (textBox == null) {
textBox = (Rectangle2D) textCharBox.clone();
} else {
if (textCharBox.getY() > textBox.getMaxY()) {
highlightQuads.add(Quad.get(textBox));
textBox = (Rectangle2D) textCharBox.clone();
} else {
textBox.add(textCharBox);
}
}
}
textBox.setRect(textBox.getX(), textBox.getY(), textBox.getWidth(), textBox.getHeight());
highlightQuads.add(Quad.get(textBox));
}*/
List<Quad> highlightQuads = new ArrayList<Quad>();
List<TextChar> textChars = match.getTextChars();
Rectangle2D firstRect = textChars.get(0).getBox();
Rectangle2D lastRect = textChars.get(textChars.size()-1).getBox();
Rectangle2D rect = firstRect.createUnion(lastRect);
highlightQuads.add(Quad.get(rect).get(rect));
// subtype can be Highlight, Underline, StrikeOut, Squiggly
new TextMarkup(page, highlightQuads, translationKeyword, MarkupTypeEnum.Highlight);
}
public void remove() {
throw new UnsupportedOperationException();
}
});
}
}
SerializationModeEnum serializationMode = SerializationModeEnum.Standard;
file.save(new java.io.File(outputPath), serializationMode);
System.out.println("file created");
long endTime = System.currentTimeMillis();
System.out.println("seconds take for execution is:"+(endTime-startTime)/1000);
} catch (Exception e) {
e.printStackTrace();
}
finally{
in.close();
}
}
}
Kindly provide your inputs to highlight specific search keyword for non english pdf files.
I am serching the keyword in below text which is in chinese langauage.
普双套习近平修宪普京利用双套车绕开宪法装班要走普京
enter image description here
Your PDF Clown version
The PDF Clown version you retrieved here from Tymate's maven repository on github has been pushed there April 23rd, 2015. The final (as of now) check-in to the PDF Clown subversion source code repository TRUNK on sourceforge, on the other hand, is from May 27th, 2015. There actually are some 30 checkins after April 23rd, 2015. Thus, you definitely do not use the most current version of this apparently dead PDF library project.
Using the current 0.2.0 snapshot
I tested your code with the 0.2.0 development version compiled from that trunk and the result indeed is different:
It is better insofar as the highlights have the width of the sought character and are located nearer to the actual character position. There still is a bug, though, as the second and third match highlights are somewhat off.
Fixing the bug
The remaining problem actually is not related to the language of the text. It simply is a bug in the processing of one type of the PDF text drawing commands, so it can be observed in documents with text in arbitrary languages. Due to the fact that these commands nowadays are used very seldom only, though, the bug is hardly ever observed, let alone reported. Your PDF, on the other hand, makes use of that kind of text drawing commands.
The bug is in the ShowText class (package org.pdfclown.documents.contents.objects). At the end of the scan method the text line matrix in the graphics state is updated like this if the ShowText instance actually is a ShowTextToNextLine instance derived from it:
if(textScanner == null)
{
state.setTm(tm);
if(this instanceof ShowTextToNextLine)
{state.setTlm((AffineTransform)tm.clone());}
}
The text line matrix here is set to the text matrix after the move to the next line and the drawing of the text. This is wrong, it must instead be set to text matrix right after the move to the next line before the drawing of the text.
This can be fixed e.g. like this:
if(textScanner == null)
{
state.setTm(tm);
if(this instanceof ShowTextToNextLine)
state.getTlm().concatenate(new AffineTransform(1, 0, 0, 1, 0, -state.getLead()));
}
With this change in place the result looks like this:
I'm looking into UC San Diego's OOP course on coursera. I have to take a CVS file, then process it and parse the date into a hashmap for the second assignment they had given. But when I try to load the CSV file it seems that Java can't get an access to it.
package app;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import de.fhpotsdam.unfolding.UnfoldingMap;
import de.fhpotsdam.unfolding.providers.Google.GoogleMapProvider;
import de.fhpotsdam.unfolding.utils.MapUtils;
import processing.core.PApplet;
public class LifeExpectancy extends PApplet {
//properties
UnfoldingMap map;
GoogleMapProvider provider;
File csvFile;
//setup method
//it only runs once, so write your code accordingly
public void setup() {
csvFile = new File("/data/LifeExpectancyWorldBank.csv");
try {
loadLifeExpectancyfromCSV(csvFile.getCanonicalPath());
} catch (IOException e) {
e.printStackTrace();
}
size(800, 600, OPENGL);
provider = new GoogleMapProvider();
map = new UnfoldingMap(this, 50, 50, 700, 500, provider);
MapUtils.createDefaultEventDispatcher(this, map);
}
//draw method
//it is dynamic, that means it runs through the program's runtime
//so write your code accordingly
public void draw() {
map.draw();
}
//methods
/**
* Loads a CSV file, parses it and returns the parsed data accordingly
* #param fileName name of the file that will be loaded
* #return parsed data that comes from the file
*/
private Map<String, Float> loadLifeExpectancyfromCSV(String fileName) {
Map<String, Float> lifeExpMap = new HashMap<String, Float>();
String[] rows = loadStrings(fileName);
for (String row : rows) {
String[] columns = row.split(",");
float value = Float.parseFloat(columns[5]);
lifeExpMap.put(columns[4], value);
}
return lifeExpMap;
}
}
When I run this code this happens:
The file "/data/LifeExpectancyWorldBank.csv" is missing or inaccessible, make sure the URL is valid or that the file has been added to your sketch and is readable.
Exception in thread "Animation Thread" java.lang.NullPointerException
at app.LifeExpectancy.loadLifeExpectancyfromCSV(LifeExpectancy.java:59)
at app.LifeExpectancy.setup(LifeExpectancy.java:27)
at processing.core.PApplet.handleDraw(PApplet.java:2361)
at processing.core.PGraphicsJava2D.requestDraw(PGraphicsJava2D.java:240)
at processing.core.PApplet.run(PApplet.java:2256)
at java.lang.Thread.run(Thread.java:745
What am I missing?
I am trying to make a program that uses JFrames and JPanels to construct a voting program. There is a file called voters.txt that is formatted like so:
1234:Herb Weaselman:false
9876:Marge Magnificent:false
4444:Ingmar Inglenook:false
8888:Hector Heroman:false
5678:Agnes Angular:false
In the beginning of my program, I have to ask the user for their voter ID and if their input does not match one of the IDs from the text file, then the program ends. I have managed to achieve this but now I need to overwrite this voters.txt file by changing the false element of whoever voted to true. For instance, if the user entered an ID of 1234, then I would need to change the word after Herb Weaselman to true instead of false. I am not sure how to do this. I know how to write to a file but am not sure how to change that one specific element. Here is the code I have currently:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
public class Assig5 extends JFrame
{
public Assig5()
{
}
public static void main(String[] args) throws IOException
{
LoginWindow loginWindow = new LoginWindow();
loginWindow.fileReader();
if(!loginWindow.checkResult(loginWindow.result))
{
System.out.println("Invalid Voter ID");
System.exit(0);
}
System.out.println("Continue");
}
}
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
public class LoginWindow extends JFrame
{
static ArrayList<String> list = new ArrayList<String>();
public String result;
public LoginWindow()
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
result = JOptionPane.showInputDialog(frame, "Enter voter ID:");
}
public static void fileReader() throws FileNotFoundException
{
Scanner s = new Scanner(new File("voters.txt"));
while (s.hasNextLine())
{
list.add(s.nextLine());
}
s.close();
}
public static boolean checkResult(String result)
{
for(int i = 0; i < list.size(); i++)
{
String[] retval = list.get(i).split(":");
if(retval[0].equals(result))
{
return true;
}
}
return false;
}
}
Any help would be appreciated. Thanks in advance.
Just change your array index from false to true when there is a match. Then rewrite the file with the data from the array. If there is not match, the file does not change.
Solution
if(retval[0].equals(result)){
retval[2] = true;
return true;
}
I am remaking part of a game in Java, and I need to know how to play the MIDI sound files. Preferably it would not involve importing any external libraries. It must also be runnable in a new thread, so that I can stack the individual sounds over the background song.
Thanks for your thoughts and time.
This code plays two MIDI tracks at the same time (the 2nd sequence starts as soon as the 1st dialog is dismissed). No threads are explicitly created, but I imagine it would work much the same if they were wrapped in a Thread object.
import java.net.URL;
import java.util.Locale;
import javax.sound.midi.MidiDevice;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Receiver;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
import javax.sound.midi.Transmitter;
import javax.swing.JOptionPane;
import org.apache.commons.lang.StringUtils;
class PlayMidi {
public static boolean useExternalSynth = false;
public static void main(String[] args) throws Exception {
MidiDevice receivingDevice = getReceivingDevice();
receivingDevice.open();
URL url1 = new URL("http://pscode.org/media/EverLove.mid");
Sequence sequence1 = MidiSystem.getSequence(url1);
Sequencer sequencer1 = MidiSystem.getSequencer(false);
Transmitter tx1 = sequencer1.getTransmitter();
Receiver rx1 = receivingDevice.getReceiver();
tx1.setReceiver(rx1);
sequencer1.open();
sequencer1.setSequence(sequence1);
URL url2 = new URL("http://pscode.org/media/AftrMdnt.mid");
Sequence sequence2 = MidiSystem.getSequence(url2);
Sequencer sequencer2 = MidiSystem.getSequencer(false);
Transmitter tx2 = sequencer2.getTransmitter();
Receiver rx2 = receivingDevice.getReceiver();
tx2.setReceiver(rx2);
sequencer2.open();
sequencer2.setSequence(sequence2);
sequencer1.start();
JOptionPane.showMessageDialog(null, "Everlasting Love");
sequencer2.start();
JOptionPane.showMessageDialog(null, "After Midnight");
}
private static MidiDevice getReceivingDevice()
throws MidiUnavailableException {
for (MidiDevice.Info mdi: MidiSystem.getMidiDeviceInfo()) {
MidiDevice dev = MidiSystem.getMidiDevice(mdi);
if (dev.getMaxReceivers() != 0) {
String lcName =
StringUtils.defaultString(mdi.getName())
.toLowerCase(Locale.ENGLISH);
if (lcName.contains(useExternalSynth? "usb": "java")) {
return dev;
}
}
}
return null;
}
}