use fileReader in java to read one character at a time - java

As a part of a school exercise, I am trying to read characters from a text file and count the frequency of the characters appeared the text file. I stored the frequency in an array, where the index is the ASCII code of the char, and the number in the array is the frequency.
int c;
FileReader fr = new FileReader (inputFile);
int [] freq = new int [200];
while ( (c= fr.read())!= -1){
int index = c;
freq [index]= freq [index]+1;
}
PrintWriter pw = new PrintWriter(new FileWriter(outputFile));
for (int i =0; i<frequency.length; i++) {
if(frequency[i]!=0){
pw.println( ((char)i) + " " +frequency[i]);
Somehow this method only works with text files with a single line, like "abcdefgh". It doesn't work with files with multiple lines, like "ab /newline cde /newline..." For this type of file, it will generate a blank line and some numbers on top of the result when I print out the array. I really couldn't figure out why.

It looks fine to me.
import java.io.FileReader;
import java.util.Arrays;
public class Foo {
public static void main(String[] args) throws Exception {
FileReader fr = new FileReader("/tmp/a");
int[] freq = new int[200];
int c;
while ((c = fr.read()) != -1) {
freq[c] = freq[c] + 1;
}
System.out.println(Arrays.toString(freq));
}
}
Example contents of /tmp/a:
abc
def
Output:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
edit - In response to the revised question:
The output is
2
a 1
b 1
c 1
d 1
e 1
f 1
The file has two line breaks, so the program is writing a line break, and then "2".
I'm guessing you want to convert the characters to something like their Java escape sequences. Here's a solution using Apache commons-lang:
import org.apache.commons.lang3.StringEscapeUtils;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class Foo {
public static void main(String[] args) throws Exception {
write(read());
}
static int[] read() throws IOException {
FileReader fr = new FileReader("/tmp/a");
int[] freq = new int[200];
int c;
while ((c = fr.read()) != -1) {
freq[c] = freq[c] + 1;
}
return freq;
}
static void write(int[] freq) throws IOException {
try (PrintWriter pw = new PrintWriter(new FileWriter("/tmp/b"))) {
for (int i = 0; i < freq.length; i++) {
if (freq[i] != 0) {
char c = (char) i;
String s = StringEscapeUtils.escapeJava("" + c);
pw.println(s + " " + freq[i]);
}
}
}
}
}
Output:
\n 2
a 1
b 1
c 1
d 1
e 1
f 1

Related

how to convert string to collection

I have a string in the below format.
[[115, 1, 0123490, 63824005632, 0036760004, , 01, N, 78, , 7481067028,
122016, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
TABORA, EMMANUEL, J, 4732 WENATCHIE TRL, LIMA, OH, 45805, EM, RXRELIEF CARD,
MUCINEX DM 20 0056-32 TAB SA 12HR 600-30MG], [115, 1, 0123490,
63824005632, 0038380001, ,
01, N, 78, , 7481067028, 122016, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, TABORA, EMMANUEL, J, 4732 WENATCHIE TRL, LIMA,
OH, 45805, EM, APEX AFFINITY DISCOUNT CARD, MUCINEX DM 20 0056-32 TAB SA
12HR 600-30MG]]
I want to store in collection with each
[115, 1, 0123490, 63824005632, 0038380001, , 01, N, 78, , 7481067028,
122016, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
TABORA, EMMANUEL, J, 4732 WENATCHIE TRL, LIMA, OH, 45805, EM, APEX AFFINITY
DISCOUNT CARD, MUCINEX DM 20 0056-32 TAB SA 12HR 600-30MG]
[115, 1, 0123490, 63824005632, 0036760004, , 01, N, 78, , 7481067028,
122016, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
TABORA, EMMANUEL, J, 4732 WENATCHIE TRL, LIMA, OH, 45805, EM, RXRELIEF CARD,
MUCINEX DM 20 0056-32 TAB SA 12HR 600-30MG]
How can I split or store in collection?
This should work as long the character ] does not appear as part of a value inside an entry:
public static void main(String[] args) {
String clob = "[[115, 1, 0123490, 63824005632, 0036760004, , 01, N, 78, , 7481067028, 122016, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, TABORA, EMMANUEL, J, 4732 WENATCHIE TRL, LIMA, OH, 45805, EM, RXRELIEF CARD, MUCINEX DM 20 0056-32 TAB SA 12HR 600-30MG], [115, 1, 0123490, 63824005632, 0038380001, , 01, N, 78, , 7481067028, 122016, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, TABORA, EMMANUEL, J, 4732 WENATCHIE TRL, LIMA, OH, 45805, EM, APEX AFFINITY DISCOUNT CARD, MUCINEX DM 20 0056-32 TAB SA 12HR 600-30MG]]";
List<String> entries = new ArrayList<>();
int start = 1;
while (true) {
start = clob.indexOf("[", start);
int end = clob.indexOf("]", start);
if (start != -1 && end != -1) {
entries.add(clob.substring(start, end + 1));
start = end + 1;
} else {
break;
}
}
}
If you know the escape sequence for characters inside your entries (e.g. \]) you have to check if the found end index represents that escape sequence and if, read again, starting from the end index.
There are many ways to do it. Here’s my suggestion:
public static List<List<String>> stringTo2DList(String input) {
if (input.equals("[]")) {
return Collections.emptyList();
}
if (! input.startsWith("[[")) {
throw new IllegalArgumentException("Not a list of lists");
}
if (! input.endsWith("]]")) {
throw new IllegalArgumentException("Not a list of lists");
}
List<List<String>> result = new ArrayList<>();
String[] innerLists = input.substring(2, input.length() - 2).split("\\], \\[");
for (String innerList : innerLists) {
// check for empty inner list
if (innerList.isEmpty()) {
result.add(Collections.emptyList());
} else {
result.add(Arrays.asList(innerList.split(", ")));
}
}
return result;
}
Should your string contain [], I am interpreting it as an empty list even though it might be a list of one element, the empty string. If you prefer the latter, just skip the check for the empty list in for loop.

Read string from USB HID RFID Reader with Java

I'm trying to read a String from a via USB connected RFID-Reader. The Reader is recognized correctly inside my appliaction. But I do not know how to read the transferred characters into a String.
If I do not detach the device, the String is printed like by a Keyboard (as you would expect from a HID). What I want is to catch that String inside my Java application only. This is the reason why I detach the USB device.
For example my application prints '"''#$&' to the console (see code below) or something like this
[0, 0, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 34, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 35, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 36, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 38, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
But what I wanted to read is 05006790.
I think that there is a stupid false in my attempt. I hope that someone can help me to figure out how I have to read the Bytes into a String correctly.
Thank you very much.
CODE FOLLOWS HERE
Context context = new Context();
int result = LibUsb.init(context);
DeviceList list = new DeviceList();
result = LibUsb.getDeviceList(context, list);
for (Device device: list)
{
int address = LibUsb.getDeviceAddress(device);
int busNumber = LibUsb.getBusNumber(device);
DeviceDescriptor descriptor = new DeviceDescriptor();
DeviceHandle handle = new DeviceHandle();
int resultOpen = LibUsb.open(device, handle);
// if (resultOpen < 0) // handle = null;
int resultDescriptor = LibUsb.getDeviceDescriptor(device, descriptor);
// if (resultDescriptor< 0) // handle = null;
if(descriptor.idVendor() == 0x8ff && descriptor.idProduct() == 0x0009)
{
System.out.println("found");
LibUsb.detachKernelDriver(handle, 0);
}
}
UsbServices services = UsbHostManager.getUsbServices();
UsbDevice deviceHigh = findDevice(services.getRootUsbHub(), (short) 0x8ff, (short) 0x0009);
if(deviceHigh != null)
{
System.out.println("found high");
UsbConfiguration configuration = deviceHigh.getActiveUsbConfiguration();
UsbInterface iface = configuration.getUsbInterface((byte) 0x00);
iface.claim();
UsbEndpoint endpoint = iface.getUsbEndpoint((byte) 0x81);
UsbPipe pipe = endpoint.getUsbPipe();
pipe.open();
byte[] buffer = new byte[128];
int rx = 0;
rx = pipe.syncSubmit(buffer);
System.out.printf("%d bytes received\n", rx);
System.out.println(Arrays.toString(buffer));
iface.release();
}

Side Collisions

I'm making a tilemap game and I've got the simple collisions down. However to make the game work I have to know which side of the rectangle hit the wall/brick. Just putting a simple collision code inside of the main collision:
if(spriteX < brickX + brickwidth) {}
doesn't work. The main collision code at the moment is:
for(int counter = 0; counter < 31; counter++) {
if(spriteX + 40 >= collisionX[counter] && collisionX[counter] + 100 >= spriteX
&& spriteY + 40 >= collisionY[counter] && collisionY[counter] + 100 >= spriteY) {
velX = 0;
velY = 0;
collisions = counter;
} else {
if(counter == collisions && jumping == false) {
fall();
}
}
}
If you want the entire class:
package Main;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
public class Panel extends JPanel implements Runnable, KeyListener {
// dimensions
public static final int width = 800;
public static final int height = 800;
public static final int scale = 1;
// main loop
private Thread thread;
private boolean running = false;
private int FPS = 60;
private int targetTime = 1000 / FPS;
// drawing
private Graphics2D g;
private BufferedImage image;
int x;
int y;
boolean makeCollision = false;
// sprite
int spriteX = 210;
int spriteY = 200;
int velX = 0;
int velY = 10;
public boolean notOnGround = true;
int counter;
int collisionsCounter;
int jumps = 0;
public int row;
public int column;
public boolean collision;
public boolean jumping = false;
public String side = null;
// tilemap
int[][] map = {
{1, 1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 1, 0, 0, 1, 1},
{1, 0, 0, 0, 0, 1, 1, 1},
{1, 0, 0, 0, 1, 1, 0, 1},
{1, 0, 0, 1, 1, 0, 0, 1},
{1, 0, 0, 1, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 1},
{1, 1, 1, 1, 1, 1, 1, 1}
};
int[] collisionX = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 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));
setFocusable(true);
requestFocus();
}
public void addNotify() {
super.addNotify();
if(thread == null) {
running = true;
addKeyListener(this);
thread = new Thread(this);
thread.start();
}
}
public void init() {
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
g = (Graphics2D) image.getGraphics();
}
public void update() {
if(spriteY < jump[0]) {
System.out.println(jump[0]);
jumping = false;
fall();
}
}
public void draw() {
g.clearRect(0, 0, WIDTH, HEIGHT);
x = 0;
y = 0;
for(column = 0; column <= 7; column++) {
x = 0;
for(row = 0; row <= 7; row++) {
changeColor(row, column, g);
g.fillRect(x, y, 100, 100);
x = x + 100;
}
y = y + 100;
}
g.setColor(Color.YELLOW);
g.fillRect(spriteX, spriteY, 40, 40);
spriteX += velX;
spriteY += velY;
for(int counter = 0; counter < 31; counter++) {
if(spriteX + 40 >= collisionX[counter] && collisionX[counter] + 100 >= spriteX
&& spriteY + 40 >= collisionY[counter] && collisionY[counter] + 100 >= spriteY){
velX = 0;
velY = 0;
collisions = counter;
} else {
if(counter == collisions && jumping == false) {
fall();
}
}
}
}
public void changeColor(int rowGive, int columnGive, Graphics g) {
if(map[rowGive][columnGive] == 1) {
g.setColor(Color.BLACK);
if(counter < 30) {
collisionX[counter] = x;
collisionY[counter] = y;
}
counter++;
} else {
g.setColor(Color.WHITE);
}
}
public void fall() {
velY = 5;
}
public void drawToScreen() {
Graphics g2 = getGraphics();
g2.drawImage(image, 0, 0, width * scale, height * scale, null);
g2.dispose();
}
public void run() {
init();
long wait;
long elapsed;
long start;
while(running) {
start = System.nanoTime();
update();
draw();
drawToScreen();
elapsed = System.nanoTime() - start;
wait = targetTime - elapsed / 1000000;
if(wait < 0) wait = 5;
try {
thread.sleep(wait);
} catch(Exception e) {
e.printStackTrace();
}
}
}
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if(code == KeyEvent.VK_RIGHT) {
velX = 5;
}
if(code == KeyEvent.VK_LEFT) {
velX = -5;
}
if(code == KeyEvent.VK_SPACE && jumping == false) {
jumping = true;
velY = -5;
jump[0] = spriteY - 100;
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}}
Let's try to divide the problem a little bit. You don't need to find out when a rectange hit a wall: you need to find when the left side of the rectangle hit the right side of the wall and when the right side of the rectangle hit the left side of the wall.
To be more precise: don't test objects. Divide your object in collision surfaces (left and right sides in your case), find a way to modelize them (usually x and x+width are the left and right side of your rectangle, if x is the x coordinate of your topleft corner). And test both at the same time with an "or" condition.
if(spriteX < brickX + brickwidth || spriteX + spritewidth > brickX) {}
edit Reading your complete class a little more closely, it looks like you do something similar but you use "&&" condition, meaning you can never be true since both side collisions cannot happen at the same time. But I may be wrong, can you tell me ?
While not strictly about your collision problem I've noticed a "bug" in draw() that is causing your map array to be displayed flipped around the -45 angle.
You should be incrementing y when row is incremented and x when column is incremented. Do this and your display will look the same as your map initialization code.
In other words this:
public void draw() {
g.clearRect(0, 0, WIDTH, HEIGHT);
x = 0;
y = 0;
for(column = 0; column <= 7; column++) {
y = 0;
for(row = 0; row <= 7; row++) {
changeColor(row, column, g);
g.fillRect(x, y, 100, 100);
y = y + 100;
}
x = x + 100;
}
...
will make this
int[][] map = {
{1, 1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 1, 0, 0, 1, 1},
{1, 0, 0, 0, 0, 1, 1, 1},
{1, 0, 0, 0, 1, 1, 0, 1},
{1, 0, 0, 1, 1, 0, 0, 1},
{1, 0, 0, 1, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 1},
{1, 1, 1, 1, 1, 1, 1, 1}
};
look like this
instead of this

Colision detecting in java(Tiled map)

Here i have a code with a picture moving around the map.
How to make this picture colide when interacte with map tiles ? I'm a beginer at java so i have no ideas. Any Help or advise is very welcome.
Code:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.Timer;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import org.omg.CORBA.portable.InputStream;
import java.io.Reader;
public class NewTest extends JFrame implements KeyListener {
/**
*
*/
private static final long serialVersionUID = 1L;
private Image TestImage;
private BufferedImage bf;
private BufferedImage bufferedImage;
private int cordX = 100;
private int cordY = 100;
public int mapy=25;
public int mapx=mapy;
public int size= 20;
private boolean down, up, left, right;
private Image wall = Toolkit.getDefaultToolkit().getImage("image/Koala.jpg");
private Image no = Toolkit.getDefaultToolkit().getImage("image/house.jpg");
public static int[][]
map = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 10, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 11},
{0, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3},
{0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3},
{0, 2, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3},
{0, 2, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3},
{0, 2, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3},
{0, 2, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 3, 0, 4, 0, 5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, 0, 0, 0, 0, 0, 0, 0, 3},
{0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3},
{0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3},
{0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3},
{0, 12, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 13}};
public NewTest() throws IOException {
setTitle("Testing....");
setSize(mapy*size+50,mapx*size+50);
imageLoader();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void imageLoader() throws IOException {
TestImage = Toolkit.getDefaultToolkit().getImage("image/Koala.jpg");
addKeyListener(this);
}
public void update(Graphics g){
paint(g);
}
public void paint(Graphics g){
bf = new BufferedImage( this.getWidth(),this.getHeight(), BufferedImage.TYPE_INT_RGB);
try{
animation(bf.getGraphics());
g.drawImage(bf,0,0,null);
}catch(Exception ex){
}
}
public void animation(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
for (int y = 0; y <= mapy; y++){
for (int x = 0; x <= mapx; x++){
int L = x * size;
int U = y * size;
int R = size;
int D = size;
/// g2d.rotate(Math.toRadians(-90));
if (map[y][x] == 1){
//no black wall
g2d.setColor(Color.green);
g2d.fillRect(L, U, R, D);
}else if (map[y][x] == 2){
//on left
g2d.setColor(Color.green);
g2d.fillRect(L, U, R, D);
g2d.setColor(Color.black);
g2d.fillRect(L-size/2 +2, U, 8, size);
}else if (map[y][x] == 3){
//on right
g2d.setColor(Color.green);
g2d.fillRect(L, U, R, D);
g2d.setColor(Color.black);
g2d.fillRect(L+size, U, 8, size);
}else if (map[y][x] == 4){
//on top
g2d.setColor(Color.green);
g2d.fillRect(L, U, R, D);
g2d.setColor(Color.black);
g2d.fillRect(L, U-size/2 + 2, size, 8);
}else if (map[y][x] == 5){
//on bottom
g2d.setColor(Color.green);
g2d.fillRect(L, U, R, D);
g2d.setColor(Color.black);
g2d.fillRect(L, U+size, size, 8);
}else if (map[y][x] == 10){
//on bottom
g2d.setColor(Color.green);
g2d.fillRect(L, U, R, D);
g2d.setColor(Color.black);
g2d.fillRect(L, U-size/2 + 2, size, 8);
g2d.fillRect(L-size/2 +2, U, 8, size );
}else if (map[y][x] == 11){
//on bottom
g2d.setColor(Color.green);
g2d.fillRect(L, U, R, D);
g2d.setColor(Color.black);
g2d.fillRect(L, U+size, size, 8);
}else if (map[y][x] == 12){
//on bottom
g2d.setColor(Color.green);
g2d.fillRect(L, U, R, D);
g2d.setColor(Color.black);
g2d.fillRect(L, U+size, size, 8);
}else if (map[y][x] == 13){
//on bottom
g2d.setColor(Color.green);
g2d.fillRect(L, U, R, D);
g2d.setColor(Color.black);
g2d.fillRect(L, U+size, size, 8);
}
}
}
g.drawImage(TestImage, cordX, cordY,20 , 20, this);
}
public static void main(String[] args) {
try {
new NewTest();
} catch (IOException e) {
e.printStackTrace();
}
}
public void keyPressed(KeyEvent ke) {
switch (ke.getKeyCode()) {
case KeyEvent.VK_RIGHT:
right = true;
break;
case KeyEvent.VK_LEFT:
left = true;
break;
case KeyEvent.VK_DOWN:
down = true;
break;
case KeyEvent.VK_UP:
up = true;
break;
}
updateState();
}
public void keyReleased(KeyEvent ke) {
switch (ke.getKeyCode()) {
case KeyEvent.VK_RIGHT:
right = false;
break;
case KeyEvent.VK_LEFT:
left = false;
break;
case KeyEvent.VK_DOWN:
down = false;
break;
case KeyEvent.VK_UP:
up = false;
break;
}
updateState();
}
protected void updateState() {
if (right) {
cordX += 5;
} else if (left) {
cordX -= 5;
}
if (down) {
cordY += 5;
} else if (up) {
cordY -= 3;
}
if (down && up) {
cordY += 0;
cordX += 0;
}
if (right && left) {
cordX += 0;
cordY += 0;
}
System.out.printf("X:");System.out.println(cordX);
System.out.printf("Y:");System.out.println(cordY);
repaint();
}
public void keyTyped(KeyEvent ke) {
}
}
Thank you for help!
Good approach is to seperate visual and reality model. It means deep in the program, you have your "physics rules" and all objects and based on that model, you draw it.
You can start with creating class like this
public class ObjectInMyGame{
private int posx;
private int posy;
private int width;
private int height;
private Image image;
private int movingX;
private int movingY;
//Note that it is good to use Point or something like that, instead of posx, posy.
}
Then it is good to have some kind of "game controller", which is running your whole world.
public class GameController{
List<ObjectInMyGame> objects;
public updateGame(){
for (ObjectInMyGame object : objects){
object.doSomething(); //sometimes it is good idea to let objects itself do something
}
}
}
So for example, when you move object, you can check, if he collide or not and then decide what to do.

Eliminate default zeros while creating string from byte array

I am getting bytes from IOStream and converting it to string. From that string i am extracting a sequence using substring api.
Size of ByteArray is 128 bytes. If the stream contains only 10 bytes and remaining are filled with zero[initially filled]. I am converting the byte array to string by passing to a string constructor new String(byte[]) and checking the length. The length is 128. Why it is showing 128? Actually it should show for 10 byte character length.
How to eliminate the zero while converting to string. Is there any api's to eliminate the default zeros in byte array. It's creating problem while creating a substring from the constructed string.
byte[] b = { 99, 116, 101, 100, 46, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0}
System.out.println("byte length = " + b.length);
String str;
try {
str = new String(b, "UTF-8");
System.out.println("String length = " + str.length());
System.out.println(str);
System.out.println(" ## substring = " + str.substring(0));
System.out.println(" substring length = "
+ str.substring(0).length());
System.out.println("Done......");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}0, 0, 0 };
To create a String from part of a byte array, use the constructor String(byte[] bytes, int offset, int length, String charsetName). Example:
// uses the first 10 bytes of b
str = new String(b, 0, 10, "UTF-8");
Also, if you're compiling for Java 7 you might as well use StandardCharsets (from the java.nio.charset package), and avoid having to handle UnsupportedEncodingException. Example:
str = new String(b, 0, 10, StandardCharsets.UTF_8);
When you read from an InputStream, it will tell you how many bytes were read. The length of the byte[] itself is mostly irrelevant (other than defining the max number of bytes which could be read in a single call). There should be no need to later go examine the byte[] to try and determine how much of the data is relevant. Pay attention to the return value from read and use that when creating a String.
Additionally, if all of your data is text, consider using an InputStreamReader, perhaps in combination with a BufferedReader.
First an explanation.
Not every byte sequence is valid UTF-8. A binary byte 0 (0x00) is valid, and does not terminate a String as in C.
In fact a terminating \0 was later deplored by either C's Kernighan or Ritchie, as being suboptimal.
To prevent problems, not only Unicode code points above U+007F (0x7f) are multi-byte encoded (whith high bits of bytes set), but also U+0000 in Java's UTF-8, DataOutputSream.
byte[] bytes = get UTF-8 bytes from string
Now bytes could have a multi-byte sequence for the code point 0.
So you might either clean up the bytes, a small loop, or clean up the string:
str = str.replace("\u0000", ""); // All bytes 0
str = str.replaceFirst("\u0000+$", ""); // Only trailing bytes 0, regex
Your code would be like this
byte[] b = { 99, 116, 101, 100, 46, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0};
int nonZeroPos=0;
for (int i = b.length-1; i >0; i--) {
if(b[i]!=0){
nonZeroPos=i;
break;
}
}
System.out.println("byte length = " + b.length);
String str;
try {
str = new String(b, 0, nonZeroPos, "UTF-8");
System.out.println("String length = " + str.length());
System.out.println(str);
System.out.println(" ## substring = " + str.substring(0));
System.out.println(" substring length = "
+ str.substring(0).length());
System.out.println("Done......");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You also could have it done this way -
String zerostring = new String(new byte[]{0});
str=new String(b).replace(zerostring , "");
System.out.println(str);
But disadvantage of this is it will replace 0s coming in the word.

Categories