Easy and Smart Amounts String/int using java [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
Improve this question
Basically I am working with a game, so I want an easy way to identify items amounts..
for Example I am creating an ArrayList<Item>(); and I am identifying the items like:
//Item(itemId, itemAmount);
new Item(ItemsList.COINS, 1_000_000);//this is 1m of coins
new Item(ItemsList.FISH, 2000);//this is 2k of fish
I want an easier way instead of writing the amounts to be like
new Item(ItemsList.COINS, Amounts.1M);
new Item(ItemsList.FISH, Amounts.2k);`
like this, I want guide on how do I create the class Amounts and go on about it?
Of course I am not going to be creating an enum with all values like what's the smart way of doing this task. Please help me thanks!

You may want to try something like this:
class Amounts {
public static int k(int amount){
return amount * 1_000;
}
public static int M(int amount){
return amount * 1_000_000;
}
(...)
}
And then you could use it like this:
new Item(ItemList.COINS, Amounts.M(1));
new Item(ItemList.FISH, Amounts.k(2));
However, I personally prefer just using constants (and inserting _ after three digits) like:
new Item(ItemList.COINS, 1_000_000);
Or something like
new Item(ItemList.COINS, 1 * Amounts.MILLION);
(and define a static constant public static int MILLION = 1_000_000; in class Amounts)

You can use below function to convert number into your format and can use in your code with some changes as per your requirement -
public static String formatNumber(double value) {
String suf = " kmbt";
NumberFormat formatter = new DecimalFormat("#,###.#");
int power = (int)StrictMath.log10(value);
value = value/(Math.pow(10,(power/3)*3));
String result =formatter.format(value);
result = result + suf.charAt(power/3);
return result .length()>4 ? result .replaceAll("\\.[0-9]+", "") : result ;
}

Related

Keeping a running average of values in java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 11 months ago.
Improve this question
I am trying to calculate the average of values given via repeated function calls.
Actually Bluej allows me to put the number to rate but if i am trying to put again it replaces the previous one, i want to be stored and after that an average to be shown.
I can't figure out how to do it
This is the part of code:
public int getRate() // here i put an int number
{
return this.rate;
}
public void setRate(int rate) // here i change it but i think i don't need it
{
this.rate = rate;
}
I can't use strange or complex commands because i am allowed to only use this type of commands like get/set and arraylists.
It is a school assignment.
Thanks
An easy way to keep an average of inputs is to keep track of:
The sum of all inputs received so far.
The number of inputs you have received.
Every time you call setRate to update the rate, you add to the sum and increment the count. You also need a special case for when no rates have been added yet, to avoid division by zero:
private int ratesSum = 0;
private int rateCount = 0;
public int getRate()
{
return this.rate;
}
public void setRate(int rate)
{
this.rate = rate;
this.ratesSum += rate;
this.rateCount++;
}
// Gets the average of all rates so far, or returns zero if no rates
// have been set yet.
public float getAverageRate()
{
// Do not divide by zero
if (rateCount == 0) return 0;
return ((float)ratesSum) / ((float)rateCount);
}

Is it okay to declare a Random object as a private static final attribute? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I have the following class:
public class CardGenerator {
private static final Random random = new Random();
private CardGenerator() {
}
public static long generateNumber() {
int identifier = random.nextInt(1_000_000_000 - 100_000_000 + 1)
+ 100_000_000; //9 digits
long number = 400_000 * 1_000_000_000L
+ identifier; //15 digits
int checksum = Luhn.getChecksum(number);
number = number * 10 + checksum; //16 digits
return number;
}
public static int generatePIN() {
return random.nextInt(10_000 - 1_000 + 1) + 1_000; //4 digits
}
}
or is it better practice to create a new Random object in every method?
"Better" always depends on your exact requirements.
The things to consider:
do you want your code to be testable (the above is only to a certain degree)
do you want your code to work in a multi threaded environment, and should the different threads see the same random numbers
In other words, the distinct non-answer: you have to understand the contract that your code will be used for. Then you can decide what is appropriate.
The above is probably okay on a "throw away after single exercise" level, but not more.
You might be thinking, that generating a new Random object might create numbers more, eh, randomly. But this is not the case. Calling next() always changes the seed used to create random numbers.
protected int next(int bits) { // is called by nextInt()
long oldseed, nextseed;
AtomicLong seed = this.seed;
do {
oldseed = seed.get();
nextseed = (oldseed * multiplier + addend) & mask;
} while (!seed.compareAndSet(oldseed, nextseed));
return (int)(nextseed >>> (48 - bits));
}
So you have no advantages in creating a new Random object each time but you have a bit less performance because you are always creating a new object.
So yes, it's totally okay to stick with one Random object.

Magic number constant name convention for tests ONE, TWO,.. ONE_HUNDRED vs _1 , _2, _100 [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
so I'm doing some code refactoring/sonar fixes, and there are some tests that contain magic numbers, 5, 123, 567 or whatever, i wanted to create a NumberConstant class where we save numbers used in tests, everything is good we have something like this
public static final int ZERO = 0;
public static final int ONE = 1;
public static final int TWO = 2;
public static final int THREE = 3;
public static final int FOUR = 4;
public static final int FIVE = 5;
the problem is when doing the refactoring, the code is "ok" for SonarQube, but something seems off, the code somehow becomes "cluttered",
i mean just compare these two lines
before
private LocalDateTime endtDateOfFiscalYear2018 = LocalDate.of(2018, Month.DECEMBER, 31).atTime(LocalTime.MAX);
after
private LocalDateTime endtDateOfFiscalYear2018 = LocalDate.of(TWO_THOUSAND_EIGHTEEN, Month.DECEMBER, THIRTY_ONE).atTime(LocalTime.MAX);
I thought a good compromise would be :
private LocalDateTime endtDateOfFiscalYear2018 = LocalDate.of(_2018, Month.DECEMBER, _31).atTime(LocalTime.MAX);
and having my NumberConstant class like this
public static final int _0 = 0;
public static final int _1 = 1;
public static final int _2 = 2;
public static final int _3 = 3;
public static final int _4 = 4;
public static final int _5 = 5;
is this a good compromise or is the whole approach incorrect? what is your approach to keeping your test clean and understandable?
I think the whole approach is incorrect.
What do you gain from introducing a named constant where the name just rephrases the value?
Introducing a constant from a literal value generally has some benefits:
Instead of some magic number you see a meaningful name.
It groups together the situations where that very same value has the same meaning. E.g. you might encounter lots of places using the number 10, some as a digit representation radix, some as the base of a logarithm value, some representing the month of October, and so on.
If you find out later that a different value better represents the intended meaning, you can change that at one central place.
All this doesn't work if you replace all occurrences of a literal 10 with a constant named TEN or _10. E.g. you'll hopefully never change TEN to have a value of 20.
So, what's needed is more than just some automated, blind replacement of values. You need to understand what that specific occurrence of the literal means, and then introduce an appropriate name for this concept, replacing all occurences of the same concept with a common name.
The original developer should have done that. If now you just blindly introduce names like TEN, you just hide the deficiency, and it'll never be improved. So I'd rather have Sonar permanently remind me of the problem than to hide it forever.
And sometimes, especially in test cases, I'd even prefer to see a literal 4711 than a constant named SOME_RANDOM_FOUR_DIGIT_NUMBER.

Telling string to equal an int in android studio [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Basically, I'm creating an app where users choose pass, merit or distinction for 18 different units (school basically). My problem is that I can't figure out how to tell the spinner that if the string in it is "Pass", that string equals the integer 70 (Merit = 80 and distinction = 90). I am using a string array and adapters for the spinners. I am currently trying to do this with an If statement:
if (spinner1.toString().equals("Pass")){}
I just have no idea what I should do to tell the string to equal an int.
To reiterate, I want Pass to = 70, Merit = 80, Distinction = 90.
Any guidance and help on this is much appreciated. :)
hope this helps, it's a little vague...
you mean, you have a few string<->int conversion to do?
public YourConstructor() {
/*Map<String, Integer>*/ theMap = new HashMap<String, Integer>();
theMap.put("Pass", 10);
theMap.put("Merit", 70);
theMap.put("distinction ", 90);
...
}
public int getNumber(String text) {
return theMap.get(text);
// I hope this will be, one day, forgotten. This is BAD.
//for (String s : theMap.keySet())
// if (text.equals(s))
// return theMap.get(s);
// return 0; // default for "item not found", or throw
}
thus final String yourString = ""+getNumber(spinner.getSelectedItem().toString());
Conversion::String to integer is done by:
int integer = Integer.parseInt(text);
integer to String
String theString = ""+integer;
Create a Map like below:
Map<String,int> gradeScoreMap=new HashMap<String,int>();
gradeScoreMap.put("PASS",70);
gradeScoreMap.put("MERIT",70);
gradeScoreMap.put("DISTINCTION",70);
The above map will contains the mapping for your grade with score
create a getter for Map:
public String getgradeScoreMap(String grade) {
return gradeScoreMap.get(grade);
}
the above method will be used to fetch the score based on input grade.
Now use:
int score=-1;
if (spinner1.toString().equals("Pass")){
score =getgradeScoreMap(spinner1.toString());
}
The score will be your equivalent value for "PASS" i.e 70

HashMap Help Needed [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Program 1: You are a runner, and you are in training for a race. You'd like to keep track of all of your times for your training runs. You only like to run around lakes. Here's some example data,
Calhoun, 45.15
Calhoun, 43.32
Harriet, 49.34
Harriet, 44.43
Harriet, 46.22
Como, 32.11
Como, 28.14
Please write a program which enables you to enter the names of lakes and times, and store it all of this data in data structure(s). Don't store it in individual variables. Your program should still work if you started running around another lake too (e.g. Cedar or Phalen).
Your program should be able to analyze the data that you have stored, and print your fastest time for each lake you ran around. So, for this data, your program will display
Calhoun, 43.32
Harriet, 44.43
Como, 32.11
Your program should use input validation.
You should use methods to organize your program.
This was what I was trying to do by using a HashMap but it doesn't seem to work.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Creating a HaspMap as String for Key and Double for value
HashMap<String, Double> map = new HashMap<String, Double>();
String lakeName;//Variable to store lake name
double time;//Variable to store time
while (true){
System.out.println("What is the lake name: ");
lakeName = input.next();
System.out.println("How many minutes did you run: ");
time = input.nextDouble();
map.put(lakeName, time);//Addding Lake Name to and time to theHaspMap
if (lakeName.equalsIgnoreCase("A") || time ==1)//A condition to exit the loop
{
break;
}
}
System.out.println();
}
}
Using a HashMap<String, Double> allows you to store just one result for each lake. If you change it to HashMap<String, List<Double>>, you'll be able to store multiple results for each lake, and find the fastest result for a given lake.
Instead of
map.put(lakeName, time);
you'll have something like :
List<Double> times = map.get(lakeName);
if (times == null) {
times = new ArrayList<Double>();
map.put(lakeName,times);
}
times.add(time);
You cannot use a Map<String, Double> you need to use a Map<String, List<Double>> to store ALL times in of each lake.
When stored, you must retrieve lake times:
List<Double> times = map.get("Harriet");
And get lower value of the list.
Double bestTime = Double.MAX_VALUE;
for (Double time : times) {
if (bestTime > time) bestITime = time;
}

Categories