Does one need getters and setters for calculation methods? - class

import javax.swing.JOptionPane;
public class BeerStoreBP
{
private String name;
private double custAge;
private double numBeers = 0;
private double beerDisc = 0;
private double beerType = 0;
private double theBeerBrand;
private double total = 0;
private double beer = 0;
public void setAge(double theAge)
{
custAge = theAge;
}
public void setName(String theName)
{
name = theName;
}
public void setNumBeers(double theNumBeers)
{
numBeers = theNumBeers;
}
public void setBeerType(double theBeerType)
{
beerType = theBeerType;
}
public double getAge()
{
return custAge;
}
public String getName()
{
return name;
}
public double getNumBeers()
{
return numBeers;
}
public double calcNumBeersValid()
{
String numBeersStr;
while (numBeers < 3 || numBeers > 6)
{
numBeersStr = JOptionPane.showInputDialog("You must pick 3-6 " +
"beers");
numBeers = Double.parseDouble(numBeersStr);
}
return numBeers;
}
public double calcBeerPrice()
{
final double LAGIMRED = 1.90;
final double DESINIPA = 2.00;
final double BELBEBRN = 1.80;
final double SCHOATST = 2.50;
final double BOULFHSAISN = 2.75;
final double GANDANCPRTR = 1.75;
if (theBeerBrand == 1)
beer = LAGIMRED;
else if (theBeerBrand == 2)
beer = DESINIPA;
else if (theBeerBrand == 3)
beer = BELBEBRN;
else if (theBeerBrand == 4)
beer = SCHOATST;
else if (theBeerBrand == 5)
beer = BOULFHSAISN;
else
beer = GANDANCPRTR;
return beer;
public double calcBeerTotal()
{
String beerTypeStr;
double count = 1;
while (count <= numBeers)
{
beerTypeStr = JOptionPane.showInputDialog("Please choose between "
+ "these fine selections:\n1 - Lagunitas Imperial Red - " +
"$1.90\n2 - Deschutes Inversion IPA - $2.00\n3 - " +
"Bell's Best Brown Ale - $1.80\n4 - Schlafly's Oatmeal " +
"Stout - $2.50\n5 - Boulevard's Farmhouse Saison - $2.75"
+ "\n6 - Gandy Dancer Porter - $1.75");
beerType = Double.parseDouble(beerTypeStr);
beerType = theBeerBrand;
total += beer;
count++;
}
return total;
}
public double getBeerTotal()
{
double theTotal;
theTotal = total;
return theTotal;
}
public double calcBeerDisc()
{
if (numBeers == 6)
beerDisc = .10;
else if (numBeers >= 4)
beerDisc = .05;
else
beerDisc = .00;
return beerDisc;
}
public double calcFinalPrice()
{
double finalPrice;
finalPrice = total-(total * beerDisc);
return finalPrice;
}
Noob here, so please shed some mercy. The point of the above program is to gather the amount of beers(must be 3-6), provide the customer with a choice for each beer, calculate the total amount of beers, and apply a discount(depends on # of beers). Pretty simple stuff, yet I've hit a brick wall.
My problem lies with calculating the final price. I can't seem to figure out why nothing from by calcBeerTotal method is getting passed to my calcFinalPrice method. My output displays the amount of beers just not the final price.
So my main question is: do I need some sort of setter and getter method for my calc methods? I've tried some setter and getter methods and I still wasn't getting a final price (method located above calcBeerDisc). I'm of limited programming knowledge so please keep from getting any more complicated than what I've written. If it's something aside from setters and getters please keep away from arrays and the like as I do not fully understand them either. Any help is much appreciated!

Rewritten:
import javax.swing.JOptionPane;
public class BeerStoreBP {
private String name;
private double custAge;
private double numBeers = 0;
private double beerDisc = 0;
private double total = 0;
// This only exists in one method. There is no need for it to be global
//private double beerType = 0;
// This only exists in one method. There is no need for it to be global
//private double theBeerBrand;
// This only exists in one method. There is no need for it to be global
//private double total = 0;
// This only exists in one method. There is no need for it to be global
//private double beer = 0;
public void setAge(double theAge)
{
custAge = theAge;
}
public void setName(String theName)
{
name = theName;
}
public void setNumBeers(double theNumBeers)
{
numBeers = theNumBeers;
}
// Your functionality is parsed by your dialog. There is no need for this.
//public void setBeerType(double theBeerType)
//{
// beerType = theBeerType;
//}
public double getAge()
{
return custAge;
}
public String getName()
{
return name;
}
public double getNumBeers()
{
return numBeers;
}
public double calcNumBeersValid()
{
String numBeersStr;
while (numBeers < 3 || numBeers > 6)
{
numBeersStr = JOptionPane.showInputDialog("You must pick 3-6 " +
"beers");
numBeers = Double.parseDouble(numBeersStr);
}
return numBeers;
}
public double calcBeerPrice(int beerBrand)
{
final double LAGIMRED = 1.90;
final double DESINIPA = 2.00;
final double BELBEBRN = 1.80;
final double SCHOATST = 2.50;
final double BOULFHSAISN = 2.75;
final double GANDANCPRTR = 1.75;
double beerPrice;
if (beerBrand == 1)
beerPrice = LAGIMRED;
else if (beerBrand == 2)
beerPrice = DESINIPA;
else if (beerBrand == 3)
beerPrice = BELBEBRN;
else if (beerBrand == 4)
beerPrice = SCHOATST;
else if (beerBrand == 5)
beerPrice = BOULFHSAISN;
else
beerPrice = GANDANCPRTR;
return beerPrice;
}
public void calcBeerTotal()
{
String beerTypeStr;
double count = 1;
double beerPrice;
// No need to be double
int beerBrand;
while (count <= numBeers)
{
beerTypeStr = JOptionPane.showInputDialog("Please choose between "
+ "these fine selections:\n1 - Lagunitas Imperial Red - " +
"$1.90\n2 - Deschutes Inversion IPA - $2.00\n3 - " +
"Bell's Best Brown Ale - $1.80\n4 - Schlafly's Oatmeal " +
"Stout - $2.50\n5 - Boulevard's Farmhouse Saison - $2.75"
+ "\n6 - Gandy Dancer Porter - $1.75");
beerBrand = Integer.parseInt(beerTypeStr);
beerPrice = calcBeerPrice(beerBrand);
total += beerPrice;
count++;
}
}
public double getBeerTotal()
{
return total;
}
public double calcBeerDisc()
{
if (numBeers == 6)
beerDisc = .10;
else if (numBeers >= 4)
beerDisc = .05;
else
beerDisc = .00;
return beerDisc;
}
public double calcFinalPrice()
{
double finalPrice;
finalPrice = total-(total * beerDisc);
return finalPrice;
}
}
This is in a working state, but may I recommend you take the UI portions out of this class and include them elsewhere.

Related

Item in ScrollView is not seen in Scene, but it shows in hierarchy

I am trying to display a list, generated dinamically. I created a prefab with the things I need in it (a TextView, 3 TMP_InputFields and 2 Buttons.)
To manage the different list items, I created a script (SkillManager, since the items represents skill the player can choose), which I attached to the prefab.
Then, I add every item (currently I am adding only one for testing purposes) to a List, iterate that list, and add the prefab to the Content of a ScrollView:
for(int i = 0; i < listaSkills.Count; i++)
{
GameObject listItem = Instantiate(SkillPrefab) as GameObject;
listItem.GetComponent<SkillManager>().skill = listaSkills[i];
//listItem.transform.SetParent(SkillsContent.transform, false);
listItem.transform.parent = SkillsContent.transform;
}
When I run this, no item is seen in the ScrollView, but I can see the SkillItem added to the hierarchy:
If I move to Scene tab after playing, I see a square with red lines crossing it:
Why is my item not displaying? Why the red cross? How can I populate my ScrollView?
EDIT:
This is the code of SkillManager, the script added to SkillPrefab:
public class SkillManager : MonoBehaviour
{
public TMP_InputField toSpend;
public TMP_InputField rangos;
public TMP_InputField modificadores;
public TMP_InputField total;
public Button plusButton;
public Button minusButton;
public TMP_Text nombre;
public Skill skill;
private int modificador;
private int pointsToSpend;
private int totalPoints;
// Start is called before the first frame update
void Start()
{
print("Start");
if(total!=null)
total.text = "0";
if(modificadores!=null)
modificadores.text = "0";
if (toSpend != null)
{
toSpend.GetComponent<TMP_InputField>().text = GetSkillPoints();
totalPoints = int.Parse(total.GetComponent<TMP_InputField>().text);
pointsToSpend = int.Parse(toSpend.GetComponent<TMP_InputField>().text);
}
else
{
GameObject GameObjectToSpend = GameObject.FindGameObjectWithTag("tospend");
toSpend = GameObjectToSpend.GetComponent<TMP_InputField>();
if (toSpend == null)
{
print("Sigue siendo nulo");
}
else
{
toSpend.text= GetSkillPoints();
//totalPoints = int.Parse(total.GetComponent<TMP_InputField>().text);
if(total!=null)
totalPoints = int.Parse(total.text);
if(toSpend!=null)
pointsToSpend = int.Parse(toSpend.text);
}
}
if (skill != null)
{
modificador = GetModificador(skill);
string sModificador = modificadores.GetComponent<TMP_InputField>().text;
int iModificador = int.Parse(sModificador);
modificadores.GetComponent<TMP_InputField>().text = iModificador.ToString();
}
if (plusButton != null)
{
plusButton.onClick.AddListener(PlusButtonClicked);
minusButton.onClick.AddListener(MinusButtonClicked);
}
}
private string GetSkillPoints()
{
return "1";
}
public void MinusButtonClicked()
{
string ranks = rangos.GetComponent<TMP_InputField>().text;
int ranksInt = int.Parse(ranks);
if (ranksInt > 0)
{
int newRank = ranksInt - 1;
pointsToSpend += 1;
rangos.GetComponent<TMP_InputField>().text = newRank.ToString();
toSpend.GetComponent<TMP_InputField>().text = pointsToSpend.ToString();
total.GetComponent<TMP_InputField>().text = (newRank + modificador).ToString();
skill.Puntos = newRank;
}
}
public void PlusButtonClicked()
{
string ranks=rangos.GetComponent<TMP_InputField>().text;
int ranksInt = int.Parse(ranks);
Character character = Almacen.instance.Character;
int level = character.CharacterLevel;
if (ranksInt < level && pointsToSpend > 0)
{
int newRank = ranksInt + 1;
rangos.GetComponent<TMP_InputField>().text = newRank.ToString();
pointsToSpend -= 1;
toSpend.GetComponent<TMP_InputField>().text = pointsToSpend.ToString();
total.GetComponent<TMP_InputField>().text = (newRank + modificador).ToString();
skill.Puntos = newRank;
}
}
private int GetModificador(Skill skill)
{
int retorno=0;
if (skill.Clasea)
{
retorno += 3;
}
else
{
retorno += 0;
}
retorno += GetModificadorCaracteristica();
return retorno;
}
private int GetModificadorCaracteristica()
{
Utils utils = new Utils();
int retorno = 0;
int characteristic=0;
switch (skill.Caracteristica)
{
case "Fue":
characteristic = Almacen.instance.Character.EffectiveStr;
break;
case "Des":
characteristic = Almacen.instance.Character.EffectiveDex;
break;
case "Con":
characteristic = Almacen.instance.Character.EffectiveCon;
break;
case "Int":
characteristic = Almacen.instance.Character.EffectiveInt;
break;
case "Sab":
characteristic = Almacen.instance.Character.EffectiveWis;
break;
case "Car":
characteristic = Almacen.instance.Character.EffectiveCha;
break;
}
retorno = utils.GetCharModifier(characteristic);
return retorno;
}
}
it looks like you instantiate the object as a GameObject. but this will not be seen in the canvas because it isn't a UI component. you may want to add a sprite or image to the component and instantiate that into the Canvas. it will look something like this:
public class SkillPrefab
{
//put all your variables here!!!
public Sprite skillSprite;
}
public class YourClassName : MonoBehaviour
{
[SerializeField]
public List<SkillPrefab> skills = new List<SkillPrefab>();
private void Update()
{
Sprite listItem = Instantiate(skills[0].skillSprite); //the index is the skill you want to spawn in the list.
}
}
this does take into account that you have made your skills into a list of skills that you can acces.

Are there any examples of pedestrian modelling in repast simphony?

Are there any examples of pedestrian modelling in repast simphony? I am novice in repast and was trying to model a simple pedestrian movement simulation. Any pointers to useful resources/ examples?
Andrew Crook's blog GIS and Agent-Based Modeling (http://www.gisagents.org/) has lots of interesting links to pedestrian models. I think there are even some specific to Repast.
Repast isn't the best for open libraries, but I've had some luck searching GitHub. Here's a basic ped agent I built once, you'll have to build a context with a scheduler class to call the pedestrians:
context:
public class RoadBuilder extends DefaultContext<Object> implements ContextBuilder<Object> {
context.setId("driving1");
ContinuousSpaceFactory spaceFactory =
ContinuousSpaceFactoryFinder.createContinuousSpaceFactory(null);
ContinuousSpace<Object> space =
spaceFactory.createContinuousSpace("space",context, new SimpleCartesianAdder<Object>(),
new StrictBorders(), roadL, worldW);
clock = RunEnvironment.getInstance().getCurrentSchedule();
flowSource = new Scheduler();
context.add(flowSource);
return context;
}
the scheduler:
public class Scheduler {
static ArrayList<Ped> allPeds;
#ScheduledMethod(start = 1, interval = 1, priority = 1)
public void doStuff() {
Ped addedPed = addPed(1);
allPeds.add(addedPed);
for (Ped a : allPeds) {
a.calc();}
for (Ped b : allPeds) {
b.walk();}
public Ped addPed(int direction) {
Context<Object> context = ContextUtils.getContext(this);
ContinuousSpace<Object> space = (ContinuousSpace<Object>) context.getProjection("space");
Ped newPed = new Ped(space,direction);
context.add(newPed);
space.moveTo(newPed,xPlacement,yPlacement);
newPed.myLoc = space.getLocation(newPed);
return(newPed);
}
The pedestrians - This is based on a "generalized force model" (source: Simulating Dynamical Features of Escape Panic - Helbing, Farkas, and Vicsek - https://arxiv.org/pdf/cond-mat/0009448.pdf)
and here's the pedestrian class
public class Ped {
private ContinuousSpace<Object> space;
private List<Double> forcesX, forcesY;
private NdPoint endPt;
private Random rnd = new Random();
private int age;
private double endPtDist, endPtTheta, critGap;
private double side = RoadBuilder.sidewalk;
private double wS, etaS, wV, etaV, sigR; //errors
private double m, horiz, A, B, k, r; //interactive force constants (accT is also)
public NdPoint myLoc, destination;
public double[] v, dv, newV;
public double xTime, accT, maxV, xLoc, yLoc;
public int dir; // dir = 1 walks up, -1 walks down
public void calc() {
myLoc = space.getLocation(this);
dv = accel(myLoc,dir,destination);
newV = sumV(v,dv);
newV = limitV(newV);
}
public void walk() {
v = newV;
move(myLoc,v);
}
public double[] accel(NdPoint location, int direct, NdPoint endPt) {
forcesX = new ArrayList<Double>();
forcesY = new ArrayList<Double>();
double xF, yF;
double[] acc;
xF = yF = 0;
//calculate heading to endpoint
endPtDist = space.getDistance(location, endPt);
double endPtDelX = endPt.getX()-location.getX();
endPtTheta = FastMath.asin((double)direct*endPtDelX/endPtDist);
if (direct == -1) {
endPtTheta += Math.PI;}
//calculate motive force
Double motFx = (maxV*Math.sin(endPtTheta) - v[0])/accT;
Double motFy = (maxV*Math.cos(endPtTheta) - v[1])/accT;
forcesX.add(motFx);
forcesY.add(motFy);
//calculate interactive forces
//TODO: write code to make a threshold for interaction instead of the arbitrary horizon
for (Ped a : Scheduler.allPeds) {
if (a != this) {
NdPoint otherLoc = space.getLocation(a);
double otherY = otherLoc.getY();
double visible = Math.signum((double)dir*(otherY-yLoc));
if (visible == 1) { //peds only affected by those in front of them
double absDist = space.getDistance(location, otherLoc);
if (absDist < horiz) {
double delX = location.getX()-otherLoc.getX();
double delY = location.getY()-otherLoc.getY();
double delXabs = Math.abs(delX);
double signFx = Math.signum(delX);
double signFy = Math.signum(delY);
double theta = FastMath.asin(delXabs/absDist);
double rij = r + a.r;
Double interFx = signFx*A*Math.exp((rij-absDist)/B)*Math.sin(theta)/m;
Double interFy = signFy*A*Math.exp((rij-absDist)/B)*Math.cos(theta)/m;
forcesX.add(interFx);
forcesY.add(interFy);}}}}
//sum all forces
for (Double b : forcesX) {
xF += b;}
for (Double c : forcesY) {
yF += c;}
acc = new double[] {xF, yF};
return acc;
}
public void move(NdPoint loc, double[] displacement) {
double[] zero = new double[] {0,0};
double yl = loc.getY();
if (displacement != zero) {
space.moveByDisplacement(this,displacement);
myLoc = space.getLocation(this);}
}
public double[] limitV(double[] input) {
double totalV, norm;
if (this.dir == 1) {
if (input[1] < 0) {
input[1] = 0;}}
else {
if (input[1] > 0) {
input[1] = 0;}}
totalV = Math.sqrt(input[0]*input[0] + input[1]*input[1]);
if (totalV > maxV) {
norm = maxV/totalV;
input[0] = input[0]*norm;
input[1] = input[1]*norm;}
return input;
}
public double[] sumV(double[] a, double[] b) {
double[] c = new double[2];
for (int i = 0; i < 2; i++) {
c[i] = a[i] + b[i];}
return c;
}
public Ped(ContinuousSpace<Object> contextSpace, int direction) {
space = contextSpace;
maxV = rnd.nextGaussian() * UserPanel.pedVsd + UserPanel.pedVavg;
dir = direction; // 1 moves up, -1 moves down
v = new double[] {0,(double)dir*.5*maxV};
age = 0;
//3-circle variables - from Helbing, et al (2000) [r from Rouphail et al 1998]
accT = 0.5/UserPanel.tStep; //acceleration time
m = 80; //avg ped mass in kg
horiz = 5/RoadBuilder.spaceScale; //distance at which peds affect each other
A = 2000*UserPanel.tStep*UserPanel.tStep/RoadBuilder.spaceScale; //ped interaction constant (kg*space units/time units^2)
B = 0.08/RoadBuilder.spaceScale; //ped distance interaction constant (space units)
k = 120000*UserPanel.tStep*UserPanel.tStep; //wall force constant
r = 0.275/RoadBuilder.spaceScale; //ped radius (space units)
}
}

My Program Creates 1 Ball not 2

I made a program that creates a frame and then creates 2 balls and moves them around seperately, my problem is that somehow the first or second ball is getting the coordinates of the other, and therefore are being painted on each other, sorry for the bad indentation this is my first time posting a question .
Main Class:
public class Game extends JPanel {
Ball ball01 = new Ball();
Ball ball02 = new Ball();
int ball01x = 0,ball01y = 0,ball02x = 0,ball02y = 0;
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.fillOval(ball01x, ball01y, 10, 10);
g2d.setColor(Color.RED);
g2d.fillOval(ball02x, ball02y, 10, 10);
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("Sample Frame");
Game game = new Game();
frame.add(game);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.createBalls();
while (true) {
game.getCoords();
game.updateBalls();
game.repaint();
System.out.println("Ball01 x: " + game.ball01x + " Ball02 x " + game.ball02x);
Thread.sleep(10);
}
}
public void getCoords(){
ball01x = ball01.getX();
ball01y = ball01.getY();
ball02x = ball02.getX();
ball02y = ball02.getY();
}
public void createBalls(){
ball01.create(300,300);
ball02.create(50,20);
}
public void updateBalls(){
ball01.Ball();
ball02.Ball();
}
}
Ball Class:
public class Ball{
private static int x;
private static int y;
private static int xSize = 30;
private static int ySize = 30;
static boolean xright = true,ydown = true;
static boolean grow = false;
public void Ball(){
this.moveBall();
this.ballSize();
}
public void create(int startX, int startY){
this.x = startX;
this.y = startY;
}
private void moveBall() {
if(this.x >= 370){
xright = false;
}
if(this.x <= 0){
xright = true;
}
if(this.y >= 370){
ydown = false;
}
if(this.y < 0){
ydown = true;
}
if(xright == true){
this.x = this.x + 1;
}else if (xright == false){
this.x = this.x - 1;
}
if(ydown == true){
this.y = this.y + 1;
}else if (ydown == false){
this.y = this.y - 1;
}
}
private void ballSize(){
if (xSize <= 5 && ySize <= 5){
grow = true;
}else if (xSize >= 10 && ySize >= 10){
grow = false;
}
if (grow == true){
xSize = xSize + 1;
ySize = ySize + 1;
//System.out.println("Debug");
}else if (grow == false){
xSize--;
ySize--;
//System.out.println("Debug");
}
}
public int getX(){
return x;
}
public int getY(){
return y;
}
}

While/if Loop is not working in class

I'm learning java and I'm having an issue with my if code not running.
In the following code I'm trying to determine if a number (variable num) is a triangle number (1,3, 6, 10 etc). The code should run through and give the "Is Triangle". However it keeps spitting out Null.
I understand this is not the most effective way to do this code, but I am trying to learn how to use Classes.
public class HelloWorld {
public static void main(String[] args) {
class NumberShape {
int num = 45;
int tri = 0;
int triplus = 0;
String triresult;
public String triangle() {
while (tri < num) {
if (tri == num) {
triresult = "Is a Triangle";
System.out.println("Is a Triangle");
} else if (tri + (triplus + 1) > num){
triresult = "Is Not a Triangle";
} else {
triplus++;
tri = tri + triplus;
}
}
return triresult;
}
}
NumberShape result = new NumberShape();
System.out.println(result.triangle());
}
}
Thanks for any help provided.
Try this code :
public class HelloWorld {
public static void main(String[] args) {
class NumberShape {
int num = 10;//Try other numbers
int tri = 0;
int triplus = 0;
int res = 0;
String triresult = "Is Not a Triangle";
int[] tab= new int[num];
public String triangle() {
//to calculate the triangle numbers
for(int i = 0; i<num; i++){
res = res + i;
tab[i]=res;
}
//To check if num is a triangle or not
for(int i = 0; i<tab.length; i++){
System.out.println(">> " + i + " : " + tab[i]);
if(tab[i]== num){
triresult = num + " Is a Triangle";
break;//Quit if the condition is checked
}else{
triresult = num + " Is Not a Triangle";
}
}
return triresult;
}
}
NumberShape result = new NumberShape();
System.out.println(result.triangle());
}
}
Hope this Helps.
Step through the loop carefully. You'll probably see that there is a case where
(tri < num)
fails, and thus you fall out of the loop, while
(tri == num)
and
(tri + (triplus + 1) > num)
both fail too, so no text gets set before you fall out.
You probably want to do your if-tests within the method on just tri, not a modification of tri, so as to reduce your own confusion about how the code is working.

How to limit a float to give one or no value after the decimal

I'm working in Eclipse and using float for my variables and values. The only issue I am getting is the huge number of digits (1.563524354) after the decimal. Can I somehow limit them to one digit after the decimal like (1.5) or no digit or decimal at all simply like 1. ?
My code:
float nCurrentSpeed;
private long startTime;
private int count;
private int pointAverage;
private Float nMaxSpeed = 0F;
DecimalFormat df = new DecimalFormat("#");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager lm = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
this.onLocationChanged(null);
}
#Override
public void onLocationChanged(Location location) {
TextView tv = (TextView) findViewById(R.id.textView1);
TextView tvd = (TextView) findViewById(R.id.textView5);
if (location == null) {
startTime = System.currentTimeMillis();
count = 0;
pointAverage = 0;
actualizeTextField();
tv.setText("0.0");
} else {
nCurrentSpeed = location.getSpeed();
tv.setText(nCurrentSpeed + "");
count += 1;
pointAverage += location.getSpeed();
actualizeTextField();
if (nMaxSpeed < nCurrentSpeed) {
nMaxSpeed = nCurrentSpeed;
}
}
tvd.setText(nMaxSpeed.toString());
}
private void actualizeTextField() {
// TODO Auto-generated method stub
TextView tf = (TextView) findViewById(R.id.textView3);
if (count > 0) {
long timeOver = System.currentTimeMillis() - startTime;
tf.setText(String.valueOf(pointAverage / (timeOver / 1000)));
} else {
tf.setText("0.0");
}
}
DecimalFormat df = new DecimalFormat("#.#");
df.format(0.91231);
returns:
0.9
If you don't want decimal places, why don't you cast it to int then?
Like this :
double d = 1.234567;
DecimalFormat df1 = new DecimalFormat("#.##"); // set your format
System.out.print(df1.format(d))
If you don't need point values, why are you using float? Check this one.
float nCurrentSpeed;
private long startTime;
private int count;
private int pointAverage;
private int nMaxSpeed = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager lm = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
this.onLocationChanged(null);
}
#Override
public void onLocationChanged(Location location) {
TextView tv = (TextView) findViewById(R.id.textView1);
TextView tvd = (TextView) findViewById(R.id.textView5);
if (location == null) {
startTime = System.currentTimeMillis();
count = 0;
pointAverage = 0;
actualizeTextField();
tv.setText("0.0");
} else {
nCurrentSpeed = location.getSpeed();
tv.setText(nCurrentSpeed + "");
count += 1;
pointAverage += location.getSpeed();
actualizeTextField();
if (nMaxSpeed < nCurrentSpeed) {
nMaxSpeed = (int)nCurrentSpeed;
}
}
tvd.setText(String.valueOf(nMaxSpeed));
}
private void actualizeTextField() {
// TODO Auto-generated method stub
TextView tf = (TextView) findViewById(R.id.textView3);
if (count > 0) {
long timeOver = System.currentTimeMillis() - startTime;
tf.setText(String.valueOf(pointAverage / (timeOver / 1000)));
} else {
tf.setText("0.0");
}
}