I have an applet that I am trying to make read a file. It throws an exception, but I am passing it the correct path so I am not sure where I am going wrong. I am using this to read numbers and use those numbers to change a multidimensional array, if you were wondering. Heres the code:
public class Save {
public void loadSave(File loadPath) {
try {
Scanner loadScanner = new Scanner(loadPath);
while(loadScanner.hasNext()){
for(int y = 0; y < Screen.room.block.length;y++){
for(int x = 0; x < Screen.room.block[0].length;x++){
Screen.room.block[y][x].groundID = loadScanner.nextInt();
System.out.println(loadScanner.nextInt());
}
}
for(int y = 0; y < Screen.room.block.length;y++){
for(int x = 0; x < Screen.room.block[0].length;x++){
Screen.room.block[y][x].airID = loadScanner.nextInt();
}
}
}
loadScanner.close();
} catch (Exception e) { e.printStackTrace();}
}
}
How I access it:
save.loadSave(new File(frame.getClass().getResource("mission1.tdm").toString()));
Ok, I used the edited code up above and it still says that it cannot find the file, even though the error spits out the exact path that it is in.
Related
I have suddenly been having a problem in regards to using an iterator while looping where it only goes through about ⅔ (two thirds) of the array before it seemingly just fails to work properly the last 20,000 elements or so after having worked with the same code previously. The relevant code block is as follows:
private void loadInvTable(){
ArrayList<InventoryData.InventoryObject> invArray = new ArrayList<>();
int rowCount = dtm.getRowCount();
try {
invArray = AllJsonData.allQuantityParserTest();
} catch (Exception e) {
e.printStackTrace();
}
Iterator<InventoryData.InventoryObject> invIt = invArray.iterator();
for(int i = 0; i < rowCount; i++){
String upc = dtm.getValueAt(i, dtm.findColumn("UPC")).toString();
while (invIt.hasNext()){
InventoryData.InventoryObject invObj = invIt.next();
String test = invObj.getUpc().toString();
if(invObj.getUpc().equals(upc)){
System.out.println(invObj.getUpc());
dtm.setValueAt(invObj.getNm(), i, dtm.findColumn("NM"));
dtm.setValueAt(invObj.getLp(), i, dtm.findColumn("LP"));
dtm.setValueAt(invObj.getMp(), i, dtm.findColumn("MP"));
dtm.setValueAt(invObj.getHp(), i, dtm.findColumn("HP"));
dtm.setValueAt(invObj.getDam(), i, dtm.findColumn("DAM"));
invIt.remove();
break;
}
}
}
invArray.clear();
}
The data it is comparing is an array parsed from a file and a JTable each with about 100,000 rows. The problem being is that when I do it in other ways it takes much longer but works properly:
private void loadInvTable() {
ArrayList<InventoryData.InventoryObject> invArray = new ArrayList<>();
try {
invArray = AllJsonData.allQuantityParserTest();
} catch (Exception e) {
e.printStackTrace();
}
int rowCount = dtm.getRowCount();
for(InventoryData.InventoryObject inv : invArray){
for(int i = 0; i < rowCount; i++){
if(dtm.getValueAt(i, dtm.findColumn("UPC")).toString().equals(inv.getUpc())){
dtm.setValueAt(inv.getNm(), i, dtm.findColumn("NM"));
dtm.setValueAt(inv.getLp(), i, dtm.findColumn("LP"));
dtm.setValueAt(inv.getMp(), i, dtm.findColumn("MP"));
dtm.setValueAt(inv.getHp(), i, dtm.findColumn("HP"));
dtm.setValueAt(inv.getDam(), i, dtm.findColumn("DAM"));
break;
}
}
}
}
private void loadInvTable() {
ArrayList<InventoryData.InventoryObject> invArray = new ArrayList<>();
InventoryData.InventoryObject invObj;
try {
invArray = AllJsonData.allQuantityParserTest();
//System.out.println(ints);
} catch (Exception e) {
e.printStackTrace();
}
Iterator<InventoryData.InventoryObject> invIt = invArray.iterator();
int count = 0;
int rowCount = dtm.getRowCount();
while(invIt.hasNext()){
invObj = invIt.next();
for(int i = 0; i < rowCount; i++){
if(dtm.getValueAt(i, dtm.findColumn("UPC")).toString().equals(invObj.getUpc())){
dtm.setValueAt(invObj.getNm(), i, dtm.findColumn("NM"));
dtm.setValueAt(invObj.getLp(), i, dtm.findColumn("LP"));
dtm.setValueAt(invObj.getMp(), i, dtm.findColumn("MP"));
dtm.setValueAt(invObj.getHp(), i, dtm.findColumn("HP"));
dtm.setValueAt(invObj.getDam(), i, dtm.findColumn("DAM"));
invIt.remove();
break;
}
}
count++;
}
}
I tried to both rewrite and debug the problem section of the program, but I can't seem to find a way to code it so that it works nearly as quickly the first block and when debugging the code it seems to either hang on the code block and I need to kill the program or it runs and just skips/repeats one of the the rest of the elements in the array.
I have no idea what exactly I'm doing wrong and am even having trouble pinpointing what could be causing the issue or what had changed to break it and have been trying for days to get it working again. I was hoping for some help if anyone can point where the mistake is. If this question has already been asked elsewhere I apologize. I couldn't find a similar question anywhere. Thanks in advance for any help anyone can provide.
I am trying to create a program in Java that calculates the average cost of winning the lottery and saves that average to reference when it runs again (my goal is to be able to create a more accurate outcome every time i run it). The average successfully saves to my txt file, but when I run the program it uses 0 as the previous average every time. Any help is greatly appreciated! Thanks!
(Number of times it runs can be changed by changing the 'runs' variable)
public class WinningTheLottery
{
public static final int SIZE = 5;
public static void main(String[] args)
{
int[] winningNums = new int[SIZE];
int[] guessNums = new int[SIZE];
int spent, runs = 1;
double oldAvg = 0;
double newAvg;
int totalSpent = 0;
NumberFormat currency = NumberFormat.getCurrencyInstance();
try
{
Scanner fileScanner = new Scanner(new File("average.txt"));
PrintWriter fileWriter = new PrintWriter(new File("average.txt"));
while (fileScanner.hasNextDouble())
{
oldAvg = fileScanner.nextDouble();
}
for (int i = 0; i < runs; i++)
{
spent = 0;
randomlyAssignedNumbers(winningNums);
// Arrays.toString(nameOfArray) => built in method to print an array
System.out.println("\n[" + (i+1) + "] Todays winning numbers:\n" + Arrays.toString(winningNums).replace("[", "").replace("]", ""));
do
{
randomlyAssignedNumbers(guessNums);
spent++;
} while (howManyCorrect(winningNums, guessNums) < 5);
System.out.println("After spending " + currency.format(spent) + ", you won the Fantasy 5 lottery $75,000 prize!");
totalSpent += spent;
}
newAvg = ((totalSpent/runs) +oldAvg)/2;
fileWriter.println(newAvg);
System.out.println("\nAverage Cost to win the Lottery: " + currency.format(newAvg)
+ "\n(Previous Average: " + currency.format(oldAvg) + ")");
fileScanner.close();
fileWriter.close();
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
public static void randomlyAssignedNumbers(int[] anyArray)
{
Random rng = new Random();
for (int i = 0; i < anyArray.length; i++)
{
anyArray[i] = rng.nextInt(36) + 1;
}
}
public static int howManyCorrect(int[] a1, int[] a2)
{
if (a1.length != a2.length)
return -1;
int count = 0;
for (int i = 0; i < a1.length; i++)
{
if (a1[i] == a2[i])
count++;
}
return count;
}
}
Your code is opening the file in overwrite mode, default of many programming languages, before scanner can read the content, thus deleting the content before fileScanner.hasNextDouble() read. Move your PrintWriter instantiation after Scanner read, and it will work.
Note: To open the file in append mode, which I don't think you need here. But in Java you use new FileWriter("average.txt", true) and then wrap a PrintWriter around it.
Try not constructing the PrintWriter until after you read the previous value. As noted in the Javadoc the file will be truncated by creating the PrintWriter.
Language:
Java.
Aim:
give variable name from object rooms[] (class: Room) the same value as variable nameGuest from object guest1 (class: Guest).
problem:
this doesn't work
void printRooms(){
for(int i = 0; i < rooms.length; i++){
rooms[i].roomNr = ""+(i+1);
for(int j = 0; j < 2; j++){
a = guest1.getName();
rooms[i].name = a;
}//end for
}//end for
}//end void
Reviewing:
I've tried rooms[i].name = guest1.nameGuest. That did not work. Making a method getName to return nameGuest didn't work either. Same goes for making a pit-stop variable a to store the value.
I'm new to inter-class coding and am currently trying to read more about how to do it on https://docs.oracle.com/javase/tutorial/java/javaOO/ and http://www.tutorialspoint.com/java/java_object_classes.htm But it's not working out.
Question:
How do you give object2.variable value to object1.variable
In this case, hotel must have a method printRooms that gives room[i] a number and the name(s) of the guest(s).
Here's my full code:
public class Hotel2 {
Guest[] guest;
Room[] rooms;
String a;
void execute() {
rooms = new Room[10];
Guest guest1 = new Guest("Alain");
Guest guest2 = new Guest("Jantje");
for (int i = 0; i < 9; i++) {
rooms[i] = new Room(guest1);
}
//2 guests in 1 room
rooms[9] = new Room(new Guest[]{guest1, guest2});
System.out.println(Arrays.toString(rooms));
printRooms();
}
void printRooms() {
for (int i = 0; i < rooms.length; i++) {
rooms[i].roomNr = "" + (i + 1);
for (int j = 0; j < 2; j++) {
a = guest1.getName();
rooms[i].name = a;
}//end for
}//end for
}//end void
public static void main(String[] args) {
(new Hotel2()).execute();
}
}
class Room {
Guest[] guests;
String roomNr;
String name;
//1 guest constructor
Room(Guest g) {
guests = new Guest[1];
guests[0] = g;
}
//several guests constructor
Room(Guest[] g) {
guests = g;
}
}
class Guest {
String nameGuest;
Guest(String n) {
nameGuest = n;
System.out.println(nameGuest);
}
String getName() {
return nameGuest;
}
}
It's really hard to understand what you're asking.
Your problem seems to be with this code:
void printRooms() {
for (int i = 0; i < rooms.length; i++) {
rooms[i].roomNr = "" + (i + 1);
for (int j = 0; j < 2; j++) {
a = guest1.getName();
// ^^^^^^ Compiler error: cannot resolve symbol "guest1"
rooms[i].name = a;
}
}
}
Notice the comment ^^^^^ I put in there.
The code doesn't compile,
because the variable guest1 is undefined.
It's not defined inside the method,
and it's not defined as a field of the class.
If your intention is to overwrite each room's name using the first guest's name, this would be it:
void printRooms() {
for (int i = 0; i < rooms.length; i++) {
rooms[i].roomNr = "" + (i + 1);
rooms[i].name = room.guests[0].getName();
}
}
But this doesn't make sense for a method called printRooms,
as it prints nothing.
But I hope that based on this you'll figure out how to do what you really want to do.
So I'm working on an assignment for my game design class to build a pacman clone, it'll be throughout the semester.
Currently I've got a text file that is the pacman maze
see below :
WWWWWWWWWWWWWWWWWWWWWWWWWWWW
W............WW............W
W.WWWW.WWWWW.WW.WWWWW.WWWW.W
W*WWWW.WWWWW.WW.WWWWW.WWWW*W
W.WWWW.WWWWW.WW.WWWWW.WWWW.W
W..........................W
W.WWWW.WW.WWWWWWWW.WW.WWWW.W
W.WWWW.WW.WWWWWWWW.WW.WWWW.W
W......WW....WW....WW......W
WWWWWW.WWWWW.WW.WWWWW.WWWWWW
WWWWWW.WWWWW.WW.WWWWW.WWWWWW
WWWWWW.WW..........WW.WWWWWW
WWWWWW.WW.WWWWWWWW.WW.WWWWWW
WWWWWW.WW.WWWWWWWW.WW.WWWWWW
..........WWWWWWWW..........
WWWWWW.WW.WWWWWWWW.WW.WWWWWW
WWWWWW.WW.WWWWWWWW.WW.WWWWWW
WWWWWW.WW..........WW.WWWWWW
WWWWWW.WW.WWWWWWWW.WW.WWWWWW
WWWWWW.WW.WWWWWWWW.WW.WWWWWW
W............WW............W
W.WWWW.WWWWW.WW.WWWWW.WWWW.W
W*WWWW.WWWWW.WW.WWWWW.WWWW*W
W...WW................WW...W
WWW.WW.WW.WWWWWWWW.WW.WW.WWW
WWW.WW.WW.WWWWWWWW.WW.WW.WWW
W......WW....WW....WW......W
W.WWWWWWWWWW.WW.WWWWWWWWWW.W
W.WWWWWWWWWW.WW.WWWWWWWWWW.W
W..........................W
WWWWWWWWWWWWWWWWWWWWWWWWWWWW
the idea is that this is read in, line by line by a reader from the java io package and then used to populate a 2d array, I think then I can use a loop to specify where to print images using the paint class with the data in the array.
My problem currently is the paint method, it doesnt seem to be working at all but I cant find what's wrong with it at the moment. Can anyone point me in the right direction?
(My codes formatting has been messed up a tad by indentation required here, I'm also new to the java IO package, first time I've seen exception handling!)
Thanks in advance for any help!
//imports
import java.awt.*;
import java.io.*;
import javax.swing.*;
public class Maze extends JFrame
{
//V.Decleration
private static final Dimension WindowSize = new Dimension (600,600);
static char[][] Amaze = new char[28][31];
//default constructor
public Maze()
{
this.setTitle("Pacman");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension screensize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
int x = screensize.width/2 - WindowSize.width/2;
int y = screensize.height/2 - WindowSize.height/2;
setBounds(x, y, WindowSize.width, WindowSize.height);
setVisible(true);
}
public void paint (Graphics g)
{
String line = null;
try
{
BufferedReader reader = new BufferedReader(new FileReader("G:\\Game Design\\Pacman\\src\\Maze.txt"));
for (int i=0; i<=31; i++)
{
do
{
try
{
line=reader.readLine();
for (int y=0; y<=28; y++)
{
Amaze[y][i]=line.charAt(y);
}
}catch (IOException e) { }
}
while (line!= null);
try
{
reader.close();
} catch (IOException e) { }
}
} catch (FileNotFoundException e) {}
}
//main
public static void main (String [] args)
{
Maze maze = new Maze();
for (int i=0;i<=28;i++)
System.out.print(Amaze[i][31]);
}
}
You are creating an array that is too small for the loop. Namely: new char[28][31]; will only allow for a maximum index of 27 and 30. Your for loops are:
for (int i=0; i<=31; i++)
for (int y=0; y<=28; y++)
Use i<31 and y<28, or increase your array to be [29][32]. Either one of these should solve your current problem.
Three suggestions:
It may be less misleading to separate your functions to do just one job at a time. So there should be a function to read the file and then another to paint the results.
Put more System.out.println() statements in your code when you're trying to debug. That's a good way to check whether each part did what you intended. For example, printing the line variable after reading it in would at least let you know whether you were reading the file correctly.
Always print out your exceptions. They will tell you what went wrong and where.
That said, this code will load and print your maze:
import java.io.*;
public class Read2DArray {
private final int WIDTH = 28;
private final int HEIGHT = 31;
private char[][] maze = new char[WIDTH][HEIGHT];
public static void main(String[] args) {
Read2DArray array = new Read2DArray();
array.loadFile("maze.txt");
array.printArray();
}
public void loadFile(String fname) {
try {
BufferedReader reader = new BufferedReader(new FileReader(fname));
String line;
int col = 0, row = 0;
while((line = reader.readLine()) != null && row < HEIGHT) {
for(col = 0; col < line.length() && col < WIDTH; col++) {
maze[col][row] = line.charAt(col);
}
row++;
}
reader.close();
} catch(IOException e) {
e.printStackTrace();
}
}
public void printArray() {
for(int row = 0; row < HEIGHT; row++) {
for(int col = 0; col < WIDTH; col++) {
System.out.print(maze[col][row]);
}
System.out.println();
}
}
}
I am working on a distributed animation of moving BALLS with RMI.
My goal is to move multiple balls in a way, so that multiple clients observe the same movement/position of balls, i m using ball object which is remote object.
The ball is moving fine, when it is only one, but when i m trying to increase the number of balls, i m failing.
here are some code snippets where i applied loops to work for multiple balls:
on server:
b[0] = new BallImpl(0, 50, 2, 3 ,Color.YELLOW,20);
b[1] = new BallImpl(50, 50, 4, 3,Color.BLUE,10);
b[2] = new BallImpl(40, 40, 5, 5, Color.PINK,30);
b[3] = new BallImpl(60, 70, 4, 6, Color.GREEN,40);
for (int i = 0; i < currentNumBalls; i++) {
Naming.rebind ("rmi://localhost/BouncingBall", b[i]); // registers Ball object
System.out.println ("remote ball object registered.");
}
on client site :
that how i look up for remote balls:
for (int i = 0; i < currentNumBalls; i++) {
try {
this.aBall[i] = (Ball) Naming.lookup("rmi://localhost/BouncingBall");
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
start();
thats moving balls code:
public void moveballs() {
for (int i = 0; i < currentNumBalls; i++) {
try {
aBall[i].setBounds(pit.getWidth(), pit.getHeight());
aBall[i].move();
pit.repaint();
} catch (Exception e) {
e.printStackTrace();
}
}
}
and that's the drawing code:
public void drawballs(Graphics g) {
for (int i = 0; i < currentNumBalls; i++) {
try {
g.setColor(aBall[i].getColor());
g.fillOval(aBall[i].getX(), aBall[i].getY(), aBall[i].getradius(), aBall[i].getradius());
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
Can somebody please guide me why i can see only one ball moving, what about other balls or there is some problem in this design and i m using the RMI in wrong way? or recommend me some design by which i can accomplish my goal.
thanks a lot,
jibby
It looks like you are binding all of your balls under the same name. You need to give them different names, like this:
for (int i = 0; i < currentNumBalls; i++) {
Naming.rebind ("rmi://localhost/BouncingBall"+i, b[i]); //add index to the name
System.out.println ("remote ball object registered.");
}
Then when looking them up, use this:
for (int i = 0; i < currentNumBalls; i++) {
try {
this.aBall[i] = (Ball) Naming.lookup("rmi://localhost/BouncingBall"+i);
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}