This question already has answers here:
What is the easiest/best/most correct way to iterate through the characters of a string in Java?
(16 answers)
Closed 4 years ago.
so i am learning how to use the HashMap object. My question is, if I use the scanner object to ask a user for a String and I save that to a String variable. How can I take that String and "compare" it to my HashMap.
For example if a user inputs "abc".
My HashMap has ("a","abra") ("b","blastoise") ("c","charizard")
I want to print to System.out.println the result -- abra blastoise charizard instead of abc.
I will share my code that i have now but i am stuck with the next step and i hope that i am being clear with my question.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String keyboard = "";
HashMap hm = new HashMap();
hm.put("A","Abra");
hm.put("B", "Blastoise");
hm.put("C", "Charizard");
hm.put("D", "Dewgong");
keyboard = sc.nextLine();
Thank you in advanced :)
You can use chars as the key of your Map such put('a', "Abra") then you compare each char.
char[] str = string.toLowerCase().toCharArray();
for(char c : str)
System.out.println(map.get(c));
Also note that 'A' is different from 'a', you need to handle such case the best one would calling toLowerCase() in the string before getCharArray().
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed last year.
I want to know how to compare string to a variable.
For example I want to check if the input taken is run and if it's not print that is not a command
class Main
{
public static void main(String args[])
{
System.out.println("a pokrmon appeard");
System.out.println("what would you like to do");
Scanner scan = new Scanner(System.in);
Random genrator = new Random();
String input =scan.nextLine();
int genrate;
genrate=genrator.nextInt(4);
String fail ="failed to escape";
String escaped ="got away safly";
if (genrate <= 2){
System.out.println(escaped);
}
else{
System.out.println(fail);
}
};
I have tried using some methods like if(input=="run") but it doesn't work
Salam (Hello in Muslim) guy.
To compare a string with another string, you need to call the string1.equals(string2) method.
It compares the value of string1 with string2 and if the values match, it returns true otherwise false.
string1==string2 - compares references to objects of type string, not the values of these objects. You can read more about this here How do I compare strings in Java? . Good luck learning Java. (I'm from Russia, I'm writing from a translator)
This question already has answers here:
How to convert a char array back to a string?
(14 answers)
Closed 3 years ago.
My problem is I have 4 arrays, a[1]=1, a[2]=3, a[3]=4, a[4]=5, and want to save as new string/ char, so the output will be s[ ]={1345}
I try to define like this, but it doesn't works
char s[]= new char [5];
s={'a[1]','a[2]','a[3]','a[4]'};
Instead of initialising the char array s[] and then setting the value in the next line, you can directly initialize the array like: char s[] = {a[0], a[1], a[2], a[3]};
In Java the concept of String is fairly simple. You dont have to define it as a character array. Just take a String variable and concat the array values to it. The below is how you can do it.
public static void main(String[] args) {
int[] a = {1,2,3,4};
String output = a[0]+a[1]+a[2]+a[3];
System.out.println(output);
}
Hope it shall work for you.
This question already has answers here:
Dynamic variable names Java
(3 answers)
Closed 9 years ago.
So say I have a string like "ABC", is there any possible way for me to pull out these characters individually and assign values to those as if they were a variable name?
For instances
String temp = "ABC"; //temp.charAt(1) being 'B' and assigning 5 to
int temp.charAt(1) = 5; //the variable name 'B'
Obviously that syntax is no where near correct, I'm just using it to explain what I'm trying to achieve.
Is this even a possible thought?
Sorry for the trivial question, I'm fairly new to java.
Use a data structure instead, like this:
Map<Character, Integer> vars = new HashMap<Character, Integer>();
String temp = "ABC";
vars.put(temp.charAt(1), 5); // B = 5
System.out.println(vars.get('B')); // 5
System.out.println(vars.get(temp.charAt(1))); // 5
This question already has answers here:
How to shuffle characters in a string without using Collections.shuffle(...)?
(17 answers)
Closed 9 years ago.
How can i randomized each string in Array words... for the word "Position" to "Psioiont". basically what i need to do is i want to display the i an funny way where a person has to think before he can answer...
Hello ---> "hlelo"
public class Rnd {
public static void main(String[] args) {
List list = new ArrayList();
Collections.shuffle(list);
String[] words =new String[]{"Position", "beast", "Hello"};
Collections.shuffle(Arrays.asList(words));
}
}
Just put the characters in each string into a list, then call Collections.shuffle(), then put them back into a string:
String x = "hello";
List<Character> list = new ArrayList<Character>();
for(char c : x.toCharArray()) {
list.add(c);
}
Collections.shuffle(list);
StringBuilder builder = new StringBuilder();
for(char c : list) {
builder.append(c);
}
String shuffled = builder.toString();
System.out.println(shuffled); //e.g. llheo
Convert the each string to an array of chars and call shuffle on that, then create a string again.
Of course, that doesn't actually work with real Unicode - there's no easy way to do it if there could be non-BMP characters or composite characters in there. But it will probably do for the kind of small game this appears to be.
I've researched this subject thoroughly, including questions and answers on this website....
this is my basic code:
import java.util.Scanner;
class StringSplit {
public static void main(String[] args)
{
System.out.println("Enter String");
Scanner io = new Scanner(System.in);
String input = io.next();
String[] keywords = input.split(" ");
System.out.println("keywords" + keywords);
}
and my objective is to be able to input a string like "hello, world, how, are, you, today," and have the program break up this single string into an array of strings like "[hello, world, how, are, you, today]...
But whenever i compile this code, i get this output:
"keywords = [Ljava.lang.String;#43ef9157"
could anyone suggest a way for the array to be outputted in the way i require??
Sure:
System.out.println("keywords: " + Arrays.toString(keywords));
It's not the splitting that's causing you the problem (although it may not be doing what you want) - it's the fact that arrays don't override toString.
You could try using Java's String.Split:
Just give it a regular expression that will match one (or more) of the delimeters you want, and put your output into an array.
As for output, use a for loop or foreach look to go over the elements of your array and print them.
The reason you're getting the output you're getting now is that the ToString() method of the array doesn't print the array contents (as it would in, say, Python) but prints the type of the object and its address.
This code should work:
String inputString = new String("hello, world, how, are, you, today");
Scanner scn = new Scanner(inputString);
scn.useDelimiter(",");
ArrayList<String> words = new ArrayList<String>();
while (scn.hasNext()) {
words.add(scn.next());
}
//To convert ArrayList to array
String[] keywords = new String[words.size()];
for (int i=0; i<words.size(); ++i) {
keywords[i] = words.get(i);
}
The useDelimiter function uses the comma to separate the words. Hope this helps!