I'm trying to get the int value from a textView, the value inside will always be a number just in string, I set it like this
int randomNumber = rng.nextInt(6) + 1;
switch (randomNumber) {
case 1:
imageViewDice.setImageResource(R.drawable.dice1);
textView.setText("Tiraste un 1!");
if (player1.getText().equals("")) {
player1.setText("1");
} else {
player2.setText("1");
}
break;
//rest of cases 2, 3, 4, 5, & 6
I need the int value of this to be able to compare then to see which player (1 or 2) has the highest number, something like this
//this doesnt work
int value1 = Integer.parseInt(player1.getText().toString());
int value2 = Integer.parseInt(player2.getText().toString());
if (value1 > value2) {
result.setText("Jugador 1");
} else if (value1 < value2) {
result.setText("Jugador 2");
} else {
result.setText("Empate!");
}
What is the correct way to get the value so that the comparison can be made?
if you set static, you can very easily read in various classes:
player1.setText(Fraction.getP1()+"");
player2.setText(Fraction.getP2()+"");
if(Fraction.getP1()>Fraction.getP2())
result.setText("Jugador 1");
new class
public class Fraction {
private static int p1=0;
private static int p2=0;
public static int getP1(){
return p1;
}
public static int getP2(){
return p2;
}
public static void setP1(int p1fraction){
Fraction.p1 = p1fraction; //Fraction is your class name
}
public static void setP2(int p2fraction){
p2 = p2fraction;
}
}
Related
I have a javascript to calculate combination and works great. But when I tried to work on Android studio code it gets wrong result.
Js
var n=16;
var r=2;
function faktor(sayi) {
var sonuc=1;
for(var i=1;i<=sayi;i++)
{
sonuc*=i;
}
return sonuc;
}
function calculate (){
var sonuc2=faktor(n)/(faktor(r)*faktor(n-r));
console.log(sonuc2);
}
calculate();
Console log = 120
That's how I used in Android Studio
public static int tiklanan = 16;
public static int kombinasyon = 2;
int sonuc2;
private int faktor(int sayi){
int sonuc=1;
for(int i=1;i<=sayi;i++)
{
sonuc*=i;
}
return sonuc;
}
private void posibilityhesapla(){
sonuc2=faktor(tiklanan)/(faktor(kombinasyon)*faktor(tiklanan-kombinasyon));
Toast.makeText(this, "/"+sonuc2, Toast.LENGTH_SHORT).show();
}
sonuc2 always returns -1 but it must 120.
What I'm missing here ?
#Dorbagna your Integer variable has overflowed the value. Converting sonuc from int to long will fix your issue.
faktor(tiklanan) = faktor(16) = 20922789888000
While maximum value int can hold is 2147483647 (Integer.MAX_VALUE)
public static int tiklanan = 16;
public static int kombinasyon = 2;
// Change variable int type to long
long sonuc2;
//change return type to long
private long faktor(int sayi) {
// Change local variable int type to long
long sonuc = 1;
for (int i = 1; i <= sayi; i++) {
sonuc *= i;
}
return sonuc;
}
private void posibilityhesapla() {
sonuc2 = faktor(tiklanan) / (faktor(kombinasyon) * faktor(tiklanan - kombinasyon));
Toast.makeText(this, "/" + sonuc2, Toast.LENGTH_SHORT).show();
}
Im currently working on a little mobile game in which you throw spears at targets, and depending on how many spears you have left at the end of the level you get between one and three Runes (similar to the Star scoring sytem in Angry Birds). The plan is to save the runes and use them to unlock different spear variants in the Main Menu.
At the moment you can see how many runes you got after completeing the level, but the values are not yet being saved.
My question is, how would I go about saving the Runes after each Level? Any ideas? You can see the part of the script Im using for that below. Thanks in advance.
public int totalRunes = 0;
public GameObject rune1;
public GameObject rune2;
public GameObject rune3;
public void RuneCollection()
{
if (currentSpears >= 2)
{
Debug.Log("3 runes collected!");
rune3.SetActive(true);
totalRunes = 3;
}
else if (currentSpears >= 1)
{
Debug.Log("2 runes collected!");
rune2.SetActive(true);
totalRunes = 2;
}
else
{
Debug.Log("1 rune collected!");
rune1.SetActive(true);
totalRunes = 1;
}
}
I would use Unitys PlayerPrefs System.
Example:
Setting Score:
public Text score;
int currentscore = 0;
Increasing Score:
currentscore += 1;
score.text = currentscore.ToString();
Setting HighScore and Loading Menu:
GameManager.SetHighScore(currentscore);
SceneManager.LoadScene("Menu");
Functions to Load/Change PlayerPrefs:
void Start()
{
highscore.text = PlayerPrefs.GetInt("HighScore", 0).ToString();
}
public static void SetHighScore(int score)
{
if (score > PlayerPrefs.GetInt("HighScore", 0))
{
PlayerPrefs.SetInt("HighScore", score);
}
}
Your Code adapted to PlayerPrefs:
public int currentSpears = 0;
public GameObject rune1;
public GameObject rune2;
public GameObject rune3;
void Start()
{
currentSpears = PlayerPrefs.GetInt("CurrentSpears", 0).ToString();
}
public static void IncreaseSpears()
{
int spears = PlayerPrefs.GetInt("CurrentSpears", 0);
PlayerPrefs.SetInt("CurrentSpears", spears++);
}
public void RuneCollection()
{
if (currentSpears >= 2)
{
Debug.Log("3 runes collected!");
rune3.SetActive(true);
totalRunes = 3;
}
else if (currentSpears >= 1)
{
Debug.Log("2 runes collected!");
rune2.SetActive(true);
totalRunes = 2;
}
else
{
Debug.Log("1 rune collected!");
rune1.SetActive(true);
totalRunes = 1;
}
}
You can save your data with PlayerPrefs for some single values or PersistentDataPath for some multiple values such as a class. Find out more with this link, and you can use them as below.
PlayerPrefs:
private int score = 0;
//set value
PlayerPrefs.SetInt("Score", score);
//get value
private int savedScore = PlayerPrefs.GetInt("Score");
PersistentDataPath:
private string savedName;
private int savedHealth;
private string loadedName;
private int loadedHealth;
public void Save(){
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/FileName.dat",
FileMode.Create);
PlayerClass newData = new PlayerClass();
newData.health = savedHealth;
newData.name = savedName;
bf.Serialize(file, newData);
file.Close();
}
public void Load(){
if (File.Exists(Application.persistentDataPath + "/FileName.dat")){
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/FileName.dat", FileMode.Open);
ObjData newData = (ObjData)bf.Deserialize(file);
file.Close();
loadedHealth = newData.health;
loadedName = newData.name;
}
}
[Serializable]
class PlayerClass{
public string name;
public int health;
}
My current data structure is as follows:
public class MyDataTemplate {
long occurenceTime;
int val1;
int val2;
public MyDataTemplate(Long nanoTime, int val1, int val2) {
this.occurenceTime = nanoTime;
this.val1 = val1;
this.val2 = val2;
}
}
List<MyDataTemplate> myData = new ArrayList <MyDataTemplate>();
The occurenceTime(long) above represents the system time which I obtain in Android using System.nanoTime()
If data arrived sequentially by time, I could have very well used the above data structure to store data as and when it arrives:
newOccurence = new MyDataTemplate(System.nanoTime(), 42, 55)
myData.add(newOccurence);
However, since data does not arrive sequentially, I may get a new occurrence earlier than an old occurrence.
My task is to ensure that the myData contains data in ascending order of time, irrespective of when it arrives.
How can I ensure that ?
Froggy Oat...
I have made an attempt which seems to loosely illustrate a potential "solution:"
public class MainActivity extends AppCompatActivity {
public class MyDataTemplate {
long occurenceTime;
int val1;
int val2;
public MyDataTemplate(Long nanoTime, int val1, int val2) {
this.occurenceTime = nanoTime;
this.val1 = val1;
this.val2 = val2;
}
}
class SortByNanoTime implements Comparator<MyDataTemplate> {
public int compare(MyDataTemplate a, MyDataTemplate b) {
if (a.occurenceTime < b.occurenceTime)
return -1;
else if (a.occurenceTime > b.occurenceTime)
return +1;
else
return 0;
}
}
List<MyDataTemplate> myData = new ArrayList<MyDataTemplate>();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myData.add(new MyDataTemplate((long) 30000.2341, 2, 3));
myData.add(new MyDataTemplate((long) 234234.234, 3, 4));
myData.add(new MyDataTemplate((long) 11234234.234, 3, 4));
myData.add(new MyDataTemplate((long) 4.234, 3, 4));
Collections.sort(myData, new SortByNanoTime());
for (MyDataTemplate tempVar : myData) {
Log.i("XXX", "" + tempVar.occurenceTime);
}
}
}
You will want to use a priority queue or a tree set - - since your timestamps are nanos, the Comparator is simply a normal Integer compare.
I am implementing the 'Dijkstra algorithm' in Android for making an app for Metro Network.
When I click on the button to show the path, it stops the app.
I have explicitly defined the graph to store in array adj[][].
MetroRoute class
public class MetroRoute extends Activity implements OnClickListener{
EditText source, destination;
TextView Route;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.metroroute);
source = (EditText) findViewById(R.id.etSource);
destination = (EditText) findViewById(R.id.etDest);
button = (Button) findViewById(R.id.bGetroute);
Route = (TextView) findViewById(R.id.tvRoute);
button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int count, i;
count = findpath(Integer.parseInt(source.getText().toString()), Integer.parseInt(destination.getText().toString()), path, sdist );
if(sdist!=0)
{
Route.setText("Shortest distance is : \n" + sdist);
Route.setText("Shortest Path is : ");
for( i=count;i>1;i--)
Route.setText(path[i] + " -> ");
Route.setText(path[i]);
}
else
Route.setText("There is no path from source to destination node\n");
}
int adj[][] = {{3,2,3,0,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}};
int MAX = 10, TEMP = 0, PERM =1, INFINITY = 9999, path[], sdist=0, n=5 ;
private class Node {
int predecessor[];
int dist[]; /*minimum distance of node from source*/
int status[];
}
int findpath(int s,int d,int path[],int sdist)
{
Node state = new Node();
int i, min=0, count=0, current, newdist, u, v ;
sdist=0;
/* Make all nodes temporary */
for(i=1;i<=n;i++)
{
state.predecessor[i]=0;
state.dist[i] = INFINITY;
state.status[i] = TEMP;
}
/*Source node should be permanent*/
state.predecessor[s]=0;
state.dist[s] = 0;
state.status[s] = PERM;
/*Starting from source node until destination is found*/
current=s;
while(current!=d)
{
for(i=1;i<=n;i++)
{
/*Checks for adjacent temporary nodes */
if ( adj[current][i] > 0 && state.status[i] == TEMP )
{
newdist=state.dist[current] + adj[current][i];
/*Checks for Relabeling*/
if( newdist < state.dist[i] )
{
state.predecessor[i] = current;
state.dist[i] = newdist;
}
}
}
/*Search for temporary node with minimum distance make it current node*/
min=INFINITY;
current=0;
for(i=1;i<=n;i++)
{
if(state.status[i] == TEMP && state.dist[i] < min)
{
min = state.dist[i];
current=i;
}
}
if(current==0) /*If Source or Sink node is isolated*/
return 0;
state.status[current]=PERM;
}
/* Getting full path in array from destination to source */
while( current!=0 )
{
count++;
path[count]=current;
current=state.predecessor[current];
}
/*Getting distance from source to destination*/
for(i=count;i>1;i--)
{
u=path[i];
v=path[i-1];
sdist+= adj[u][v];
}
return (count) ;
}
}
The easiest way to find the problem is to use the console of the adk to see the exceptions thrown by the device. When you start your app from your IDE (Eclipse, Android Studio) in a virtual device, or even your smartphone, you will get logcat-messages, which will contain the exceptions like for example the NullPointerException. You will then find the lines where the exception is thrown and then you can do some further testing (like writing some values to the console (System.Out.println(...) or System.err.println(...)).
You can post your log so we can take a look at it.
You may want to use my Dijkstra-implementation, too:
public static ArrayList<Integer> dijkstra(Graph graph, Integer orig,
Integer dest, TreeMap<Integer, Integer> distance,
ArrayList<Integer> nodesLeft) throws Exception
{
Iterator<Integer> iterator = graph.getNodes().iterator();
Integer next;
TreeMap<Integer, ArrayList<Integer>> paths = new TreeMap<Integer, ArrayList<Integer>>();
while (iterator.hasNext()) {
next = iterator.next();
distance.put(next, -1);
paths.put(next, new ArrayList<Integer>());
}
distance.put(orig, 0);
nodesLeft.addAll(Collections.unmodifiableCollection(graph.getNodes()));
while (!nodesLeft.isEmpty()) {
int u = nodesLeft.get(0);
Collection<Integer> edgesOfU = graph.getEdges(u);
Iterator<Integer> itEdgesOfU = edgesOfU.iterator();
int nextEdge;
while (itEdgesOfU.hasNext()) {
nextEdge = itEdgesOfU.next();
if (nodesLeft.contains(nextEdge)) {
int distU = distance.get(u);
if ((distance.get(nextEdge) == -1)
|| (distU + 1) < distance.get(nextEdge)) {
distance.put(nextEdge, distU + 1);
ArrayList<Integer> tmpList = paths.get(nextEdge);
for (int a : paths.get(u)) {
tmpList.add(a);
}
tmpList.add(nextEdge);
}
}
}
nodesLeft.remove(0);
}
return paths.get(dest);
}
I used some self-defined Graphs with the following Interface:
import java.util.Collection;
public interface Graph {
public Integer addNode();
public void removeNode(Integer id) throws Exception,
UnsupportedOperationException;
public Collection<Integer> getNodes();
public boolean addEdge(Integer orig, Integer dest) throws Exception;
public boolean removeEdge(Integer orig, Integer dest) throws Exception,
UnsupportedOperationException;
public Collection<Integer> getEdges(Integer orig) throws Exception;
}
I need to fill a vector with integers, but I have some troubles, I need to fill it with random numbers, but not two numbers in a row. (ex. not like this: 1,4,4,3,5,9)
I made this code but it does not work well :
# first time loja=1;
but until the game : loja++;
int[] con;
Random Method :
private int nasiqim (int max){
Random nasiqimi = new Random();
int i = 0;
i=nasiqimi.nextInt(max);
return i;
}
Working Code :
int i;
con = new int [loja];
for (i=0; i<loja; i++)
{
con[i] = nasiqim(8);
if(i>0){
while(con[i]==con[i-1])
{
con[i] =nasiqim(8);
}
}
i++;
}
The results are like this:
1
1,4
1,4,1
1,4,1,4
1,4,1,4,1
5,3,5,3,5,3
5,3,5,3,5,3,5
And this is not what I need, I need the numbers to really random, not like this,
Will be great if list will be like this something : 1,5,6,7,3,0,2,4,1,0,2,3...
Thank you!!
private int[] con = null;
private final Random nasiqimi = new Random();
/**
* Test run random.
*/
#Test
public void testRunRandom() {
int loja = 10;
con = new int[loja];
for (int i = 0; i < loja; i++) {
int nextRandom = 0;
while (true) {
nextRandom = nasiqim(8);
if (i == 0 || con[i - 1] != nextRandom) {
con[i] = nextRandom;
break;
}
}
}
}
/**
* Gets the random.
*
* #param max the max
* #return the random
*/
private int nasiqim(int max) {
return nasiqimi.nextInt(max);
}
I've created a sample class
import java.util.*;
public class Foo {
static Random r = new Random();
static int[] con;
static int loja = 8;
private static int randomInt(int max) {
return r.nextInt(max);
}
public static void main(String args[]) {
int i;
con = new int[loja];
for (i = 0; i < loja; i++) {
con[i] = randomInt(8);
if (i > 0) {
while (con[i] == con[i - 1]) {
con[i] = randomInt(8);
}
}
}
System.out.println( Arrays.toString(con));
}
}
All variables are static, notice I get rid of the i++; increment at the end of the for loop.