Java: Highscore method - java

I have a program and want to create a simple highscore method for it. The method will only tell if the current amount of points is higher than the ones before.
public class Highscore {
public static int Highscore(int poang) {
int count = 0;
int poäng1 = 0;
int poäng2 = 0;
As you see in above, the counter is set to 0;. This is to save the first entry. However, it resets to 0 every time the method is being used. How can i recode this? Here is the rest of the code:
if (count == 0) {
poäng1 = poang;
count++;
} else if (count > 0) {
if (poäng2 > poäng1) {
poäng1 = poäng2;
}
}
return poäng1;
}
}

Local variables are redefined (and re-initialized) every time the block (in your case - a static method) is entered. If you want them to keep their value beyond the scope of that block, they should be defined outside of it.
In this case, you could have count as a (static) member:
private static int count = 0;
public static int Highscore(int poang) {
// Code comes here

Related

System.out.println doesn't show text in console (IntelliJ)

I am writing a program which part is presented below:
public class Portal {
private String name;
private int[] positions; // positions of "ship"
private static int moves = 0; // moves made by player to sink a ship
public static int shot; // the value of position given by player
private int hits = 0; // number of hits
private int maxSize = 4; // max size of ship (the size will be randomized)
int first; // position of 1st ship block
int size; // real size of ship (randomized in setPortal method)
public void checkIfHit(){
for (int i : positions){
if (i == shot){
System.out.println("Hit confirmed");
hits++;
} else if (hits == positions.length){
System.out.println("Sunk");
} else {
System.out.println("Missed it");
}
}
moves++;
}
public void setPortal(){
size = 1 + (int)Math.random()*maxSize;
for (int i = 0; i < size - 1; i++){
if (i == 0){
positions[i]= 1 + (int)Math.random()*positions.length;
first = positions[i];
System.out.println(positions[i]);
continue;
}
positions[i]= first + 1;
System.out.println(positions[i]);
}
}
}
public class Main{
public static void main(String[] args){
// write your code here
Portal p1 = new Portal();
p1.setPortal();
}
}
code is split in two Java .class files.
The problem I'm dealing with is that using p1.setPortal(); doesn't show up text in IntelliJ console. The program works though and returns 0.
I don't have such problem in another program when I've put System.out.println in method other than main (also in separate class file).
What may be the cause of such issue?
It should properly throw an exception, because you forgot to initialize the integer array.
Have a look at this thread: Do we need to initialize an array in Java?
The Java's default value is null for an integer array. So your for wont even loop trough. The only thing that wonders me is why there is no exception..

Instance Variable Changing

I would like to make movement of a square with only using Instance Variable. I'm having troubles this is my code :
I have one for Variables.JAVA for Variables :
public class Variables {
String name;
int Playerx;
int Playery;
int Playerw;
int Playerh;
}
and one where it is the main but doesn't change the variables above. (simplified)
public static void main(String args[]) throws InterruptedException {
while (true) {
Variables P = new Variables(){
synchronized (c) {
c.clear();
first_level();
P.Playerx = 50;
P.Playery = 50;
P.Playerw = 100;
P.Playerh = 100;
c.drawRect(P.Playerx, P.Playery, P.Playerw, P.Playerh);
}
Thread.sleep(25);
// Controls
if (c.isKeyDown(Console.VK_UP)) {
P.Playery -= 10;
}
else if (c.isKeyDown(Console.VK_DOWN)) {
P.Playery += 10;
}
else if (c.isKeyDown(Console.VK_LEFT)) {
P.Playerx -= 10;
}
else if (c.isKeyDown(Console.VK_DOWN)) {
P.Playery += 10;
}
}
The P.Player(x,y,w,h) don't change?
How can this be solved?
You are setting the defaults in every iteration, your code is synchronic and therefore responding to the keys is done after you draw, and in the next iteration you are overriding the values again so you will never see any changes.
In addition you instantiate a new P object every time and not keeping the previous instances alive, therefore they are GC.

Java Min-Heap Implementing Priority Queue - Iteration

I'm trying to use this code to implement a Priority Queue. There are a number of questions regarding this implementation on the site, but given how many different ways you can write code to do essentially the same thing I am still at a loss after looking through a handful of other examples.
There are some missing lines in this code, but I am limited to editing only the four marked lines and so I find myself stuck on one particular aspect. I can't seem to understand how 'quantity' is incremented.
From my understanding main creates a new object of maxSize = 5. Then calls the insertItem method passing the value of 130. This should be placed into the root (I had put queArray[quantity] = item; into the first blank) at which point the insertItem method exits and is then called again with the next value. So at what point is 'quantity' incremented? Maybe I am missing something incredibly simple, or maybe there is another way of solving this that may not be apparent or known to beginners like me?
I would think you would want to increment quantity under the initial if statement, but that doesn't seem to be an option, so as far as I can tell the else statement can never be executed as quantity doesn't change. I know I am incorrect, but I don't know how, some help would be greatly appreciated.
public class Main {
/**
* #param args the command line arguments
*/
// array in sorted order, from max at 0 to min at size-1
private int maxSize;
private long[] queArray;
private int quantity;
public Main(int s) {
maxSize = s;
queArray = new long[maxSize];
quantity = 0;
}
public void insertItem(long item) {
int i;
if (quantity == 0)
__________; // insert at 0
else
{
for (i = quantity - 1; i >= 0; i--) // start at end,
{
if (item > queArray[i]) // if new item larger,
__________; // shift upward
else
// if smaller,
break; // done shifting
}
__________; // insert it
__________;
} // end else (quantity > 0)
}
public boolean PQEmpty(){
return (quantity == 0);
}
public long removeItemPQ(){
return queArray[--quantity];
}
public long peekMin(){
return queArray[quantity - 1];
}
public static void main(String[] args) {
Main thePQ = new Main(5);
thePQ.insertItem(130);
thePQ.insertItem(450);
thePQ.insertItem(110);
thePQ.insertItem(430);
thePQ.insertItem(280);
while (!thePQ.PQEmpty()) {
long item = thePQ.removeItemPQ();
System.out.print(item + " ");
}
System.out.println("");
}
}
It isn't a style I'd recommend, but you could use queArray[quantity++] = item;.

Constructor is ignoring "for" loop(Java)

So I feel kind of stupid, because it looks like I'm missing something trivial and I've used loops before, but now we're at the stage in our class where we're using them a lot and I can't seem to find the problem after trying many different combinations, so here goes :
public class BusStop
{
private BusArrival[] _buses;
private int _noOfBuses;
final int MAX_ARRAY_SIZE = 1000;
//================================ CONSTRUCTORS ============================//
public BusStop(int size){ // THIS
_buses = new BusArrival[size]; // IS
// THE
for(int i=0; i< size; i++){ // PROBLEMATIC
if(_buses[i] != null){ // LOOP
_noOfBuses ++;
}
}
}
//=============================== METHODS =================================//
public int getNoOfBuses(){
return _noOfBuses;
}
public boolean add (int line, int pass, Time1 t){ // adds a BussArrival object to an empty array (if there's any).
for (int i=0; i < _buses.length; i++){
if(_buses[i] == null){
_buses[i] = new BusArrival(line, pass, t);
return true;
}
}
return false;
}
Here's a constructor of the BusArrival class, just so you have a general idea :
public BusArrival(int lineNum, int pass, Time1 t){
_lineNumber = lineNum;
_noOfPassengers = pass;
_arrivalTime = t;
}
And here's Time1 constructor from a saparate class, just for this to make sense :
public Time1(int h, int m, int s)
_hour = h;
_minute = m;
_second = s;
}
Here's my main method :
public class Test
{
public static void main (String [] args){
BusStop first = new BusStop(4);
Time1 one = new Time1(10,30,0);
Time1 two = new Time1(10,0,0);
first.add(1,2,one);
first.add(2,3,two);
System.out.println(first.getNoOfBuses());
}
}
Unfortunately the output is "0" when I do that.
Any help would be appreciated.
Thanks.
Here's the problem.
Number of buses is only assigned in the initializer, but in the initializer you aren't adding any buses. Hence you get 0 buses.
When you add a bus, you are not updating number of buses. So you get 0.
You should do _noOfBuses++; when you successfully added a bus. Also, take out that loop in the initializer. When you initialized an array all the entries are null, so the loop is useless :)
Edit:
You seem to be confused about the order of execution of your code.
In your main function, you are first initializing a BusStop. This means he initializer code is ran (which includes the loop in your initializer).
Then you added the two buses. However, note that the loop is already executed, it won't be executed again, because the initializer is only run once.
Therefore, your loop is never going to increment _noOfBuses
You need to increase the number of busses every time that you add a new one.
public BusStop(int size){ // THIS
_buses = new BusArrival[size]; // IS
// THE
for(int i=0; i< size; i++){ // PROBLEMATIC
if(_buses[i] != null){ // LOOP
_noOfBuses ++;
}
}
}
In the above code the array _buses just gets created with all the items pointing to null. In your for-loop you are using if statement to check if there is any non-null value (which in this case does not exist because there are no items in the array). so your _noOfBuses ++; is not reachable.
First Add another constructor with no arguments to your BusArrival class. Just like this.
public BusArrival() {}
Second Modify the BusStop constructor to the following
public BusStop(int size){
_buses = new BusArrival[size];
for(int i=0; i<_buses.length; i++) {
_buses[i] = new BusArrival();
_noOfBuses ++;
}
}

Correcting and Condensing Java Program

I think I've almost figured out my java program. It is designed to read a text file and find the largest integer by using 10 different threads. I'm getting this error though:
Error:(1, 8) java: class Worker is public, should be declared in a file named Worker.java
I feel my code may be more complex than it needs to be so I'm trying to figure out how to shrink it down in size while also fixing the error above. Any assistance in this matter would be greatly appreciated and please let me know if I can clarify anything. Also, does the "worker" class have to be a seperate file? I added it to the same file but getting the error above.
import java.io.BufferedReader;
import java.io.FileReader;
public class datafile {
public static void main(String[] args) {
int[] array = new int[100000];
int count;
int index = 0;
String datafile = "dataset529.txt"; //string which contains datafile
String line; //current line of text file
try (BufferedReader br = new BufferedReader(new FileReader(datafile))) { //reads in the datafile
while ((line = br.readLine()) != null) { //reads through each line
array[index++] = Integer.parseInt(line); //pulls out the number of each line and puts it in numbers[]
}
}
Thread[] threads = new Thread[10];
worker[] workers = new worker[10];
int range = array.length / 10;
for (count = 0; count < 10; count++) {
int startAt = count * range;
int endAt = startAt + range;
workers[count] = new worker(startAt, endAt, array);
}
for (count = 0; count < 10; count++) {
threads[count] = new Thread(workers[count]);
threads[count].start();
}
boolean isProcessing = false;
do {
isProcessing = false;
for (Thread t : threads) {
if (t.isAlive()) {
isProcessing = true;
break;
}
}
} while (isProcessing);
for (worker worker : workers) {
System.out.println("Max = " + worker.getMax());
}
}
}
public class worker implements Runnable {
private int startAt;
private int endAt;
private int randomNumbers[];
int max = Integer.MIN_VALUE;
public worker(int startAt, int endAt, int[] randomNumbers) {
this.startAt = startAt;
this.endAt = endAt;
this.randomNumbers = randomNumbers;
}
#Override
public void run() {
for (int index = startAt; index < endAt; index++) {
if (randomNumbers != null && randomNumbers[index] > max)
max = randomNumbers[index];
}
}
public int getMax() {
return max;
}
}
I've written a few comments but I'm going to gather them all in an answer so anyone in future can see the aggregate info:
At the end of your source for the readtextfile class (which should be ReadTextile per java naming conventions) you have too many closing braces,
} while (isProcessing);
for (Worker worker : workers) {
System.out.println("Max = " + worker.getMax());
}
}
}
}
}
The above should end on the first brace that hits the leftmost column. This is a good rule of thumb when making any Java class, if you have more than one far-left brace or your last brace isn't far-left you've probably made a mistake somewhere and should go through checking your braces.
As for your file issues You should have all your classes named following Java conventions and each class should be stored in a file called ClassName.java (case sensitive). EG:
public class ReadTextFileshould be stored in ReadTextFile.java
You can also have Worker be an inner class. To do this you could pretty much just copy the source code into the ReadTextFile class (make sure it's outside of the main method). See this tutorial on inner classes for a quick overview.
As for the rest of your question Code Review SE is the proper place to ask that, and the smart folks over there probably will provide better answers than I could. However I'd also suggest using 10 threads is probably not the most efficient way in to find the largest int in a text file (both in development and execution times).

Categories

Resources