My save:
static final String PREFS_NAME = "ScoreGame";
Preferences preferences;
one variable temp
to output to the Class A
**Preferences preferences;**
int tempGameScore = 0;//class B
int dropsGatchered = 0;
**in create**
preferences = Gdx.app.getPreferences(Drop.PREFS_NAME);
in game scene i make this , class B
if ((raindrop.y < 0) && !(index >= 15)) {
iter.remove();
game.tempGameScore = game.dropsGatchered;
game.preferences.putInteger("score", game.tempGameScore);
game.preferences.flush();
game.dropsGatchered = 0;
stopGame();
}
Class C
I get the value and draw on the screen
#Override
public void create() {
game.tempGameScore = game.preferences.getInteger("score");
}
textFont.draw(game.batch, " " + game.tempGameScore, (Drop.WIDTH / 2) - 55,
(Drop.HEIGHT / 2) + 50);
When I close the app that my speed is lost and I want her to recover their variable game.tempGameScore
Your code and the comment seem disjointed. Why are you doing a getInteger("Save"), that doesn't line up with your code of putInteger("score").
In create(), you initialize your preferences, that is fine:
game.preferences = Gdx.app.getPreferences(Drop.PREFS_NAME);
But your get/put need to line up. They work like a hashmap, so you have to use the same key.
game.tempGameScore = game.preferences.getInteger("score");
Then later, to "save":
game.preferences.putInteger("score", game.tempGameScore);
game.preferences.flush();
Related
As you can see that I am trying to increment the variable 'c' when the accelerometer z-axis value greater than 12. But I can do it at one time, it will change the value 0 to 1 after executing the program. But I want to collect how many times the z-axis value becomes more than 12.
#Override
public void onSensorChanged (SensorEvent event) {
textView.setText(event.values[0] + "");
textView1.setText(event.values[1] + "");
textView2.setText(event.values[2] + "");
String s = new String();
s = textView2.getText().toString().trim();
Float t = Float.parseFloat(s);
int c = 0;
if (t > 11) {
c++;
txt.setText(Integer.toString(c));
}
}
int counter = 0;
#Override
public void onSensorChanged (SensorEvent event) {
textView.setText(event.values[0] + "");
textView1.setText(event.values[1] + "");
textView2.setText(event.values[2] + "");
String s = new String();
s = textView2.getText().toString().trim();
Float t = Float.parseFloat(s);
int c = 0; // ???
if (t > 11) {
c++;
counter++;
txt.setText(Integer.toString(c));
System.out.println("I need to learn how to use global
variables.\n
also the thing has been greater than \"12\"
"+counter" times."
);
}
}
Also maybe using more meaningful variable names other than "textView#" would make it less of a pain for people to figure out what you're trying to do.
You can define the variable c as a field member like below:
public class MainActivity {
private int c = 0;
(...)
#Override
public void onSensorChanged (SensorEvent event) {
textView.setText(event.values[0] + "");
textView1.setText(event.values[1] + "");
textView2.setText(event.values[2] + "");
String s = new String();
s = textView2.getText().toString().trim();
Float t = Float.parseFloat(s);
if (t > 11) {
c++;
txt.setText(Integer.toString(c));
}
}
}
So as the title says im struggling to add a value to an integer and then pass it to another class that uses it, then this class will pass it to the next and then that one will pass it over to the main class. Its an integer that changes the stat template of the enemies in my small game im writing.
I have tried to make constructors in two of my classes as I thought that was the problem, Ive tried to see if they work by passing some messages in them.
The problem seems to be that when I save something in the "private int l" It dosnt actually change the value of that int and I cant figure out why that is.
Here is my code, its probably not very pretty so if you have any suggestions to structure changes that I might wanna do please feel free too let me know!
Thanks in advance!
import java.util.Scanner;
public class Stor {
public static void main(String[] args) {
Scanner user_Input = new Scanner(System.in);
Menu user = new Menu();
EnemyValue monster = new EnemyValue();
user.namn();
user.AnvNamn = user_Input.next();
user.introMeny();
user.difficulty();
System.out.println(“Your enemy has " + monster.HP + " HP and " +
monster.DMG + " Damage" );
user_Input.close();
}
}
class Menu {
Scanner user_Input = new Scanner(System.in);
String AnvNamn;
String difficultySvar;
String nivåSvar;
int svar;
private int i; /
private int l;
public int getL() {
return l;
}
boolean difficultyLoop = true;
boolean felLoop = true;
void introMeny() {
System.out.println(“Welcome " + AnvNamn + "!");
}
void namn() {
System.out.print(“Pick a name: “);
}
void difficulty() {
do {
System.out.println("\nWhat level do you want ?\n1 = Easy.\n2 =
Medium.\n3 = Hard.”);
svar = user_Input.nextInt();
if (svar == 1) {
System.out.println(“Your not very brave are you ? Are you sure
this is how you wanna play ?”);
difficultySvar = user_Input.next();
if (difficultySvar.equalsIgnoreCase(“Yes”)) {
difficultyLoop = false;
l = 1;
} // If ja 1
else if (difficultySvar.equalsIgnoreCase(“Nej”)) {
System.out.println(“Ahh good! I figuerd you would change
your mind.”);
}
else
System.out.println(“I don’t understand….”);
} // if 1
else if (svar == 2) {
System.out.println(“Not to hard or to easy, a good choice! But
maybe you want to go for something harder ? Or maybe easier ?");
difficultySvar = user_Input.next();
if (difficultySvar.equalsIgnoreCase(“Yes”)) {
difficultyLoop = false;
l = 2;
} // if ja 2
else if (difficultySvar.equalsIgnoreCase(“No”)) {
System.out.println(“I sure hope you don’t pick the easy
way…..”);
}
else
System.out.println("I don’t understand….");
} // Else if 2
else if (svar == 3) {
System.out.println(“Damn! We have a big player here! Are you
sure you can handle this ?");
difficultySvar = user_Input.next();
if (difficultySvar.equalsIgnoreCase(“Yes”)) {
difficultyLoop = false;
l = 3;
} // If ja 3
else if (difficultySvar.equalsIgnoreCase(“No”)) {
System.out.println(“Wuss.”);
}
else
System.out.println(“I don’t understand….”);
} // Else if 3
else {
if (i == 0) {
System.out.println(“Ha you thought you could fool the system?!
The system fools you!”);
System.out.println(“Nah but seriously, you can only choose
between 1-3…..“);
i++;
} // if i 0
else if (i == 1) {
System.out.println(“Alright I get that its hard but
COMEON!”);
i++;
} // if i 1
else if (i == 2) {
System.out.println(“OKEY YOU GET ONE LAST CHANCE!!”);
i++;
} // if i 2
else if (i == 3) {
System.out.println(“Alright thats it…. GET OUT!”);
System.exit(0);
} // if i 3
} // Else
} // do while loop
while(difficultyLoop == true);
} //Difficulty metod.
} // Menu class.
class Nivå {
//Menu level = new Menu();
//int levelChoice = level.getL();
int levelChoice;
private int enemyLife;
public int getenemyLife() {
return enemyLife;
}
private int enemyDMG;
public int getenemyDMG() {
return enemyDMG;
}
Nivå(){
Menu level = new Menu();
levelChoice = level.getL();
System.out.println("testNivå");
}
void fiendeLiv() {
if (levelChoice == 1)
enemyLife = 100;
else if (levelChoice == 2)
enemyLife = 150;
else if (levelChoice == 3)
enemyLife = 200;
} // fiendeliv method
void fiendeDMG() {
if (levelChoice == 1)
enemyDMG = 5;
else if (levelChoice == 2)
enemyDMG = 10;
else if (levelChoice == 3)
enemyDMG = 15;
} // fiendeDMG method
} // Nivå class
class EnemyValue {
public int HP;
public int DMG;
int maxLife;
int maxDMG;
EnemyValue(){
Nivå stats = new Nivå();
maxLife = stats.getenemyLife();
maxDMG = stats.getenemyDMG();
System.out.println("TestEnemyValue");
}
void rank1() {
HP = maxLife;
DMG = maxDMG;
} // rank1 easy method
} // EnemyValue class
You say that when you save something in l (poor choice of a variable name, by the way) it does not save the value. How do you know that? Where in the code do you check whether the value is saved?
In the constructor for class Nivå you create a new Menu and then call getL() on that menu before you have ever set the value of that variable.
Everything runs at the start of your public static void main(String[] args) method, and nothing will run if its instructions are not in there. For example, you are not actually creating any Niva objects in the main method, so the Niva constructor is never called. That is one issue. The other is your constructors are creating new instances of objects and then getting their values; this gives you empty values from a brand new object:
Nivå(){
Menu level = new Menu(); // Don't do this. This is an empty menu
levelChoice = level.getL(); // Getting the blank L value from the empty menu
System.out.println("testNivå");
}
Instead, you need to define constructors with parameters to pass the values into the class like this:
Nivå(int level){ // add an int parameter
levelChoice = level; // Direct assignment
fiendeDMG(); // Call this in the constructor to set up your last value
System.out.println("testNivå");
}
Then, when you call the constructor (which you must if you want it to exist), include the parameter. Inside the Stor class:
public static void main(String[] args) {
Scanner user_Input = new Scanner(System.in);
Menu user = new Menu();
user.namn();
user.AnvNamn = user_Input.next();
user.introMeny();
user.difficulty(); // Run this before creating the other classes; you need the l value
Nivå niva = new Nivå(user.getL()); // Creates new Niva while also assigning l to the levelChoice and then getting DMG
EnemyValue monster = new EnemyValue(/*add some parameters for life and dmg*/);
}
There is still more that needs to be done, like modifying the constructor of the EnemyLevel. Just remember that methods are never called unless they connect to something running from main and use parameters in functions and constructors to pass on data to other objects. Hope this helps.
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..
I got a really annoying problem with my realtime graph. It works really pretty with MpAndroidChart library, but I guess I'm running out of memory. Because my realtime lineChart-graph become slower the longer it's running, until it get stuck. I didn't find any solution that works.
This is my linecharts screenshot
This is my code to enter values into charts,
( test01 - test04 are possible solution from other posts, I tried )
private void addEntry(double[][] pts) {
// System.out.println("######### addEntry #########");
if (mLineChartObj != null) {
int anzLineChartObj = mLineChartObj.size();
// System.out.println("######### Anzahl LineChartObj: " + anzLineChartObj);
for (int i = 0; i < anzLineChartObj; i++) {
LineChartObject ob = mLineChartObj.get(i);
LineData data = ob.lineChart.getData();
if (data != null) {
data.addXValue((ob.set).getEntryCount() + "");
data.addEntry(new Entry((float) pts[ob.rootNodePos][0], (ob.set).getEntryCount()), 0);
// data.addEntry(new Entry((float) (Math.random() * 9) + 0.45f, (ob.set).getEntryCount()), 0);
}
// °°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°
if (data.getXValCount() > 1400) {
System.out.println("X-ValueCount: " + ob.lineChart.getXValCount() + " EntryValueCount: " + ob.set.getEntryCount() + " ###############################");
// Test 01 °°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°
// for (int j = 0; j < 400; j++) {
// data.removeXValue(0);
// ob.set.removeEntry(0);
// }
// Test 02 °°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°
// runOnUiThread(new Runnable() {
// #Override
// public void run() {
// ob.lineChart.clearValues();
// }
// });
// Test 03 °°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°
// for (int j = 400; j > 0; j--) {
// data.removeXValue(j + 999);
// ob.set.removeEntry(j + 999);
// }
// Test 04 °°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°
// data.removeXValue(0);
// ob.set.removeEntry(0);
System.out.println("X-ValueCount: " + ob.lineChart.getXValCount() + " EntryValueCount: " + ob.set.getEntryCount() + " ###############################");
}
// °°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°
// notify chart data have changed
ob.lineChart.notifyDataSetChanged();
// limit number of visible entries
float range = 200f;
// ob.lineChart.setVisibleXRange(0f, range);
ob.lineChart.setVisibleXRangeMaximum(range);
// scroll the last entry
ob.lineChart.moveViewToX(data.getXValCount() - (range + 1f));
}
}
}
If I remove x-values from data or entries from set, several strange things happens. Sometimes the app gets crash, or the line of the charts begin to repeat itself, or sometimes I get more than one line per chart. I'm looking forward of a solution to remove old values from the chart.
EDIT 2: %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
The output of my linechart is like the following picture...It moves like a realtime graph, until xValues an amount of reach 1400, now my programm begins to remove entries and my linechart get stuck. After a while, the line begin to dissapear from the left side. At picture 1 it get stuck, at the next three pictures you can see how it dissapears.
I've been stuck with exactly the same problem today as I'm writing an app that visualizes sensor data. I just came up with the following makeshift solution that works for me:
// (following code snippet is from an event listener)
final ArrayList<Float> values = event.getValues();
final LineData data = mChart.getData();
// add data entry
if (mIndex < MAX_PLOT_SIZE) {
maxValue = 0f;
data.addXValue("" + mIndex);
for (int i = 0; i < values.size(); i++) {
final Float val = values.get(i);
final LineDataSet set = data.getDataSetByIndex(i);
set.addEntry(new Entry(val, mIndex));
}
mIndex++;
} else {
// shift values down
for (int i = 0; i < values.size(); i++) {
final LineDataSet set = data.getDataSetByIndex(i);
final List<Entry> yVals = set.getYVals();
final int size = yVals.size();
for (int j = 0; j < size - 1; j++) {
yVals.get(j).setVal(yVals.get(j + 1).getVal());
}
// add new value
final Float val = values.get(i);
yVals.get(size - 1).setVal(val);
}
}
It's admittedly a hack and there should be an easier way to do it, but at least it gets the job done. I guess you could try and adjust the xVal-Strings in the same manner ...
Recently, I've been assigned to do a file by my teacher to make a program that simulates a TV.
I am supposed to add volume when the raiseVolume method is called. However, upon calling it, it looks like volume is not being affected whatsoever.
I have no clue as to why this could be.
(myTv is the object of the constructor in Tv)
Here is the Code for the TV Driver Class-
System.out.println ("Crank it up!");
int oldVolume = myTv.getVolume();
do {
oldVolume = myTv.getVolume();
myTv.raiseVolume();
} while (myTv.getVolume() != oldVolume);
System.out.println ("\t\tThe TV is " + myTv.getPower() +
" on channel " + myTv.getChannel() +
" at volume " + myTv.getVolume());
System.out.println ("That's a bit too loud");
myTv.lowerVolume();
myTv.lowerVolume();
and here is my code for the Tv Class-
private int volume = 0;
...
//Volume
public int getVolume(){
return volume;
}
public void raiseVolume(){
volume+=5;
}
public void lowerVolume(){
volume-=1;
if (volume > 0){
volume = 0;
}
}
If you need additional code, I will post it!
I've been called out for putting entire classes in here before, I don't wish to make the same error!
Because when you call lowerVolume after raiseVolume:
public void lowerVolume(){
volume-=1;
if (volume > 0){
volume = 0;
}
}
it will always set the volume to 0, as volume > 0 (at least 5) at that moment, you should change it to:
if (volume < 0){
volume = 0;
}
The two values will never be equal, and your while loop just terminates. Print the volume before and after the call and you'll see that it changes (assuming you're using the code you've posted)
System.out.printf("oldVolume = %d%n", myTv.getVolume());
myTv.raiseVolume();
System.out.printf("newVolume = %d%n", myTv.getVolume());
Also, your lowerVolume method always sets volume to 0 (if it's greater than zero). I think you mean less than
public void lowerVolume(){
volume--; // <-- does - 1
if (volume < 0){ // <-- less than
volume = 0;
}
}
It might be a good idea to add a max for raiseVolume(). Finally, I suggest you set the increment (and decrement) to be the same value (or pass that value in to the method); that is something like
private static final int MAX_VALUE = 100;
private static final int MIN_VALUE = 0;
public void lowerVolume(int change) {
volume -= change;
volume = Math.max(volume, MIN_VALUE);
}
public void raiseVolume(int change) {
volume += change;
volume = Math.min(volume, MAX_VALUE);
}
Or,
public void lowerVolume() {
volume--;
volume = Math.max(volume, MIN_VALUE);
}
public void raiseVolume() {
volume++;
volume = Math.min(volume, MAX_VALUE);
}
try something along the lines of a start volume of 0 so when you getVolume you can write in something like
if(tv.getvolume == 0){
volume++
}