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.
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
In java, I need a hash function or algorithm that generate the number from the specified input string in such a way that the generated number should be in the range like 1000 to 6000.
Condition to satisfy : 1) The algorithm should always reproduce the same number for same string. 2) Algorithm should generate unique positive number for each different strings 3) The number of input string is restricted to the range. i.e if range is 5000, then i will allow only 5000 input strings to algorithm
Thanks in advance.
Is there any built in API available, please refer that also.
You could do something like this:
public class MyDataStructure {
private int size, counter = 0, start;
private Map<String, Integer> map;
public MyDataStructure(int size, int start) {
this.size = size;
this.start = start;
map = new HashMap<>();
}
public int add(String s) throws LimitExceededException {
if (map.containsKey(s)) {
return map.get(s);
} else if (counter >= size) {
throw new LimitExceededException();
} else {
map.put(s, counter + start);
return counter++ + start;
}
}
}
So in your case you would initialize with new MyDataStructure(5000, 1000) and then you add strings or get their corresponding number with the add function.
Your Second condition is impossible.
2) Algorithm should generate unique number for each different strings
Assume a hash function produces an unique integer number for each string. There are only 5000 possible integer numbers in range 1000 to 6000.
So it can support maximum 5000 different strings.
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
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I have two integers that I want to compare. The first integer is created from a byte of utf-8 and the second integer is the one I want to check to see if it equals.
int a = 106;
int b = (int)byteArray[0]; //which actually equals 106 when you printstatement it
but....
(a==b) //always equals false
int i = 0; While(b != i) { println(i); i++;} //eventually escapes the loop and is true
Are primitives also referenced when created? And why does a never equal b unless I count all the way up to 106?
Is there a better way to compare bytes? because I've tried all forms of variables and they do not work either.
The problem is somewhere else in your code (in the part that you are not showing). This is why you are being suggested to provide an SSCCE.
The following works as expected (i.e. prints true):
public class Test
{
public static void main(String[] args) throws Exception
{
byte[] byteArray = new byte[] { 106 };
int a = 106;
int b = (int) byteArray[0];
if (a == b)
System.out.println("true");
}
}
Most probably, in your code byteArray[0] does NOT contain 106. An SSCCE would show this.
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
Disclaimer: This is not a homework problem. I stumbled upon this puzzle here and I also have the answer. However, I am not able to figure out an approach to arrive at the solution.
The puzzle is as given below:
The product of the ages of David's children is the square of the sum of their ages. David has less than eight children. None of his children have the same age. None of his children is more than 14 years old. All of his children is at least two years old. How many children does David have, and what are their ages?
The answer happens to be 2,4,6,12.
Please suggest a way to solve this problem programmatically.
In Python (Which is not what you asked, but you're more asking for an algorithm):
import operator
import itertools
possible_ages = range(2,15)
# If the list of ages passed to this function returns true, then this solves the puzzle.
def valid(ages):
product_of_ages = reduce(operator.mul, ages, 1)
square_of_sum_of_ages = reduce(operator.add, ages, 0) ** 2
return product_of_ages == square_of_sum_of_ages
for number_of_children in range(1, 9):
for ages in itertools.combinations(possible_ages, number_of_children):
if valid(ages):
print ages
And that prints, almost immediately:
(2, 4, 6, 12)
You don't specify that the ages are all integers, but I'm going to assume that's true. If so, there are only about 1e9 possible combinations of those ages among 8 children. Simply enumerate (for(age1=2; age1<15; age1++) { for(age2=2; age2<15; age2++) { ...) them all and test. Your computer should finish that task within a few minutes even in a script interpreter.
There are optimizations to be applied, because hard-coding "8" loops is clumsy, and because the age lists are order-independent (having children of "4 and 2" is the same thing as "2 and 4"), but frankly I don't think that's worth it here. Your time taken coding the extra steps will take more time than you'll save at runtime.
I solved it in java using a recursive approach.
First the program prints all the combinations, then gives the correct combination (that matches the specified criteria) at last.
This program instantly gives the output
(2, 4, 6, 12)
just as you have specified in your question.
public class Tackle {
static int[] ages = {2,3,4,5,6,7,8,9,10,11,12,13,14}; // Since the program uses a recursive function,
static StringBuffer sb = new StringBuffer(""); // the variables are declared as static
static int x=0,occurances=0;
static int sum,pdt=1,count=0;
static String[] instances = new String[100];
static void recurse(int a[], int k, int n) throws Exception
{
if(k==n) // This program obtains various combinations using binary technique
{
for(int i=0;i<n;i++)
if(a[i] == 1){
System.out.print(ages[i]+" "); // Displays all the combinations available
sum = sum + ages[i];
pdt = pdt * ages[i];
count++;
sb.append(String.valueOf(ages[i]+" "));
}
if(Math.pow(sum, 2) == pdt && count<8){ // Checking the criteria
instances[occurances++] = sb.toString();
}
sb = new StringBuffer("");
count = 0;
sum = 0;
pdt = 1;
System.out.println("");
}
else for(int i=0;i<=1;i++)
{
a[x++] = i;
recurse(a,k+1,n);
x--;
}
}
public static void main(String[] args) throws Exception {
int[] a = new int[10000];
recurse(a,0,ages.length);
if(occurances>0)
{
System.out.println("No of combinations matching: " + occurances);
for(int i=0;i<occurances;i++)
System.out.println("The combination of ages is [ " + instances[i] + "]");
}
else
System.out.println("No combination matches the criteria. ");
}
}
The output obtained was
[All possible combinations are listed here]
No of combinations matching: 1
The combination of ages is [ 2 4 6 12 ]
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I've just started learning Java and I've been playing around with a few ideas. I've written the following small piece of code which when run outputs a different room in a house. The room is decided by a random integer between the value of 1 and 3. The code seems to work just fine. However, as I am new to programming my concern is that I may have misunderstood one of the tutorials informing my work and used an inefficient way to complete it.
Can anyone tell me if am I using the best practises to achieve my desired result and explain any changes I could make to make the code better?
import java.util.Random;
public class Rooms {
public static void main(String[] args) {
Random random = new Random();
int roomNumber = random.nextInt(3) + 1;
String getRoom = "";
if (roomNumber == 1) {
getRoom = "Living Room";
} else if (roomNumber == 2) {
getRoom = "Kitchen";
} else if (roomNumber == 3) {
getRoom = "Bathroom";
}
System.out.println(getRoom);
}
}
Thanks for reading this.
You could simply put the rooms into an array:
String[] rooms = { "Living Room", "Kitchen", "Bathroom" };
int roomNumber = random.nextInt(rooms.length);
System.out.println(rooms[roomNumber]);
Background: Random.nextInt(n) takes an int argument as the upperbound which returns an integer between 0 and (but not including) n. Using rooms.length here will allow you to select a random index from the array without causing an ArrayIndexOutOfBoundsException.
Your code is just fine. The only thing I can recommend is: Using switch instead of multiple-if's with else's is faster, but as you run this random once, that doesn't really matter. That switch if you need:
switch (roomNumber) {
case 1: getRoom = "Living Room";
break;
case 2: getRoom = "Kitchen";
break;
case 3: getRoom = "Bathroom";
break;
default: getRoom = "Error!";
break;
}
Also you can use List or Arrays. Arrays will speed you up too, always use arrays if you have defined number of elements.
String[] rooms = new String[]{"Living Room", "Kitchen", "Bathroom"};
getRoom = rooms[random.nextInt(rooms.length)];