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
Related
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 ;
}
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 8 years ago.
Improve this question
Hi In my code I am having following arrays:-
String[] Category = {Rental, Gifts, Gifts};
float[] Amount = {14.76, 15.0, 20.0};
My problem is I want find out same element from first array as there is "Gifts". And according to that convert second one.
So the output will be as:-
Category = {Rental,Gifts};
Amount = {14.76, 35.0};
Will anybody tell me how to achieve this in java?
You should use Map here: Category value should be mapped to Amount value (I would name them in lowercase according to Java coding style):
Map<String, Float> costs = new HashMap<>();
for (int i = 0; i < category.length; ++i) {
Float initial = costs.get(category[i]);
if (initial == null)
initial = 0f;
costs.put(category[i], initial + amount[i]);
}
After these actions, costs map would contain something like (Rental -> 14.76, Gifts -> 35.0)
To get the arrays back (not sure, why it can be useful), you should just iterate through Map's items and write them into an array:
category = new String[costs.size()];
amount = new Float[costs.size()];
int i = 0;
for (Map.Entry<String, Float> entry: costs.entrySet()) {
category[i] = entry.getKey();
amount[i] = entry.getValue();
++i;
}
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 8 years ago.
Improve this question
I have a list of Portfolio objects in java collection. This Portfolio object has a property called scoringRule. I want to calculate how much percentage of Portfolio objects are present in the list for each type of scoringRule. Actually, I have only 2 different types of scoring rules. The scoringRUle property can be either "single" or "double". How can I do this?
Class Portfolio{
private String name;
private String type;
private String scoringRule;
}
List<Portfolio> portfolios = new ArrayList<Portfolio>();
This is your solution.
double single = 0;
double doublee = 0;
for (Portfolio pobj : portfolios) {
if(pobj.scoringRule.equals("single"))
single++;
else
doublee++;
}
System.out.println("single Percentage : " +(single / list.size() )*100);
System.out.println("doublee Percentage : " + (doublee / list.size())*100);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How do I assign a numeric value to a string in Java? I'm using cards from Ace to king, and I want to assign the value 11 to "Jack" so I can compare it to, say, "Six".
Any ideas?
If you're using a language which supports enums, those are probably your best bet. For instance, in C#, you could do (this is rough and untested):
public enum CardDeck
{
1 = 1,
2 = 2,
3 = 3,
...
Jack = 10,
Queen = 11,
King = 12,
Ace = 13
}
You can then compare (if (int)Ace == (int)1) {}
Use HashMaps:
Map<String,Integer> map = new HashMap<>();
map.put("Jack", 11);
You have a few options. You can, say, store the strings in an array and search for them, returning the index:
List<String> names = new ArrayList<String>();
names.add("ace");
names.add("two");
names.add("three");
int number = names.indexOf("ace");
You could use a map of strings to numbers and do a lookup, this allows use of nonconsecutive numbers:
Map<String,Integer> names = new HashMap<String,Integer>();
names.put("ace", 1);
names.put("jack", 11);
names.put("queen", 12);
int number = names.get("ace");
You could also use an enum with properties, e.g.:
enum CardValue {
ACE(1),
JACK(11),
QUEEN(12);
final int value;
CardValue (int value) { this.value = value; }
int getValue () { return value; }
}
int number = Enum.valueOf(CardValue.class, "ace".toUpperCase()).getValue();
Or in the above you could use ordinal() if they are consecutive.
Add error handling as necessary.
You could also just use a brute force large if, or use a switch block (since Java 1.7):
int value (String name) {
switch (name.toLowerCase()) {
case "ace": return 1;
case "jack": return 11;
case "queen": return 12;
default: return -1;
}
Personally, I'd go for the array or map approach in your case. It is simple to code and allows easy conversion of string to value and back, and, unlike the enum technique, doesn't tie compile-time type names to user input strings (e.g. difficult if you, say, add support for another language).
The switch block is easy to code as well.
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 9 years ago.
Improve this question
public Integer[] imgs = new Integer[]{
R.drawable.ic_launcher,R.drawable.ic_launcher
};
String s_img = "R.drawable.img_test";
i want
imgs[0] = s_img
imgs[0] == R.drawable.img_test
true !!
What shall I do?
Try this:
s_img = "img_test";//not "R.drawable.img_test" just the name of the image
if(getResources().getIdentifier(s_img, "drawable", getPackageName()) == imgs[0]){
return true;
}else{
return false;
}
You want an array of drawables, right?
Integer[] drawables = {R.drawable.image1, R.drawable.image2, ....};
And you can access values by:
drawables[0] == R.drawable.image1
drawables[1] == R.drawable.image2
And you loop them aswel.
for comparing Object do not use "=="
try
"R.drawable.img_test".equals(Integer.toString(imgs[0]));
Put them in an Enum instead of array.
tell me is that exactly what you need or not ,i think i git what you need .
public Integer[] imgs = new Integer[]{
R.drawable.ic_launcher,R.drawable.ic_launcher
};
String s_img;
s_img = Integer.toString(x);