import java.util.HashMap;
public class Driver {
public static void main(String[] args) {
// TODO Auto-generated method stub
String location = "memes more memes Virginia";
String test = createStateMap(location);
System.out.println(test);
}
public static String createStateMap(String loc) {
loc = loc.toUpperCase();
String secondLast; // Retrieves potential second to last value
String lastWord; // Retrieves last value
String state = "failed";
String trimmed = loc.trim(); // Take off spaces at the end of String
String o = trimmed.substring(0, trimmed.lastIndexOf(" ")); // Remove last Word in String EX. "SOUTH CAROLINA" = "SOUTH"
String otrim = o.trim(); // Take off spaces at the end of String
if (trimmed.contains("/")){
secondLast = otrim.substring(otrim.lastIndexOf("/")+1);
lastWord = trimmed.substring(trimmed.lastIndexOf("/")+1);
} else {
secondLast = otrim.substring(otrim.lastIndexOf(" ")+1);
lastWord = trimmed.substring(trimmed.lastIndexOf(" ")+1);
}
HashMap<String,String> names = new HashMap<String,String>();
names.put("ALABAMA", "AL");
names.put("ALASKA", "AK");
names.put("ARIZONA", "AZ");
names.put("ARKANSAS", "AR");
names.put("CALIFORNIA", "CA");
names.put("COLORADO", "CO");
names.put("CONNECTICUT", "CT");
names.put("DELAWARE", "DE");
names.put("FLORIDA", "FL");
names.put("GEORGIA", "GA");
names.put("HAWAII", "HI");
names.put("IDAHO", "ID");
names.put("ILLINOIS", "IL");
names.put("INDIANA", "IN");
names.put("IOWA", "IA");
names.put("KANSAS", "KS");
names.put("KENTUCKY", "KY");
names.put("LOUISIANA", "LA");
names.put("MAINE", "ME");
names.put("MARYLAND", "MD");
names.put("MASSACHUSETTS", "MA");
names.put("MICHIGAN", "MI");
names.put("MINNESOTA", "MN");
names.put("MISSISSIPPI", "MS");
names.put("MISSOURI", "MO");
names.put("MONTANA", "MT");
names.put("NEBRASKA", "NE");
names.put("NEVADA", "NV");
names.put("NEWHAMPSHIRE", "NH");
names.put("JERSEY", "NJ");
names.put("MEXICO", "NM");
names.put("YORK", "NY");
names.put("CAROLINA", "NC");
names.put("DAKOTA", "ND");
names.put("OHIO", "OH");
names.put("OKLAHOMA", "OK");
names.put("OREGON", "OR");
names.put("PENNSYLVANIA", "PA");
names.put("RHODEISLAND ", "RI");
names.put("CAROLINA", "SC");
names.put("DAKOTA", "SD");
names.put("TENNESSEE", "TN");
names.put("TEXAS", "TX");
names.put("UTAH", "UT");
names.put("VERMONT", "VT");
names.put("VIRGINIA", "VA");
names.put("WASHINGTON", "WA");
names.put("VIRGINIA", "WV");
names.put("WISCONSIN", "WI");
names.put("WYOMING", "WY");
System.out.println(secondLast);
if (names.containsValue(lastWord)){
state = lastWord;
}
if (names.containsKey(lastWord)){
if (names.get(lastWord).equals("CAROLINA")){ // Differentiate NC and SC
if (secondLast.equals("North")){
state = "NC";
} else { state = "SC"; }
} if (names.get(lastWord).equals("DAKOTA")) { // Differentiate ND and SD
if (secondLast.equals("North")){
state = "ND";
} else { state = "SD"; }
} if (names.get(lastWord).equals("VIRGINIA")) { // Differentiate WV and VA
if (secondLast.equals("West")){
state = "WV";
} else { state = "VA"; }
} else { state = names.get(lastWord); }
}
return state;} }
I am currently having issues with my code that assigns a state's abbreviations to a variable depending on the String passed into the parameter of the createStateMap method. When the lastWord String is either Virginia, Dakota, or Carolina they will always be assigned WV, ND, or NC- even if the secondLast is not North or West.
Any help would be much appreciated, I have been stuck on this one for a while.
names.get(lastWord) already returns "SC" for key "CAROLINA", so your
names.get(lastWord).equals("CAROLINA")
condition will always return false.
It also makes no sense to put the same key twice in the Map, since the second value will overwrite the first value having the same key.
Why not put the full name of the state as key?
names.put("SOUTH CAROLINA", "SC");
names.put("NORTH CAROLINA", "NC");
In that case
state = names.get(fullStateName);
will always work and you can eliminate all of those conditions, as long as fullStateName contains the full name of the state (either a single word or two words).
If you don't know whether you should search for the last word or the last two words in the Map, you can search for the last two words, and if not found, search for the last word :
state = names.get(secondLast + " " + lastWord);
if (state == null) {
state = names.get(lastWord);
}
So, just as an fyi,
names.put("VIRGINIA", "VA");
names.put("WASHINGTON", "WA");
names.put("VIRGINIA", "WV");
You're working with a HashMap here, so you can only have 1 value per key. This means the only value you'll get when you extract VIRGINIA is WV (the last one to be entered). Just put in the full state name, as Eran suggested. I mean, you're already putting in NEWHAMPSHIRE, which is technically two words, so I don't see why you don't want to do the same thing for the Carolinas, Dakotas, and Virginias.
Related
I want to get the text from multiples checked radiobuttons, and retrieve it in one edittext... but dont know how is the best way to do it. What is better? saving results in string or a list?
Anyway the result should appear in one single editext with the space beetwen each text. For example... Dog, Cat, Mouse.
if (radioButton.isChecked()){
String obs2 = radioButton.getText().toString();
texto.setText(obs2);
}
if (radioButton3.isChecked()){
String obs2 = radioButton3.getText().toString();
texto.setText(obs2);
}
if (radioButton4.isChecked()){
String obs2 = radioButton4.getText().toString();
texto.setText(obs2);
}
if (radioButton5.isChecked()){
String obs2 = radioButton5.getText().toString();
texto.setText(obs2);
}
if (radioButton6.isChecked()){
String obs2 = radioButton6.getText().toString();
texto.setText(obs2);
}
if (radioButton7.isChecked()){
String obs2 = radioButton7.getText().toString();
texto.setText(obs2);
}
if (radioButton8.isChecked()){
String obs2 = radioButton8.getText().toString();
texto.setText(obs2);
}
editText1 = here should get the text of each radio button checked
new try:
if (radioButton.isChecked()){
obs2 = checkNullAndAppend(obs2, (String) radioButton.getText());
} else if (radioButton3.isChecked()){
obs2 = checkNullAndAppend(obs2, (String) radioButton3.getText());
} else if (radioButton4.isChecked()){
obs2 = checkNullAndAppend(obs2, (String) radioButton4.getText());
} else {
texto.setText(obs2);
}
If you want event-driven code then using a list may be easier to manage depending on how many buttons you have and how you do it. But in the case of your exact example, a string is more than enough. As suggested in comments you can simply append the text texto.setText(texto.getText() + "," + obs2);.
If you want to avoid issues with null values or reduce duplicate code, then there are many different ways you can do this, but one is to create a simple method:
public static String checkNullAndAppend(String existing, String toAppend){
//Check null
if (existing == null || existing.equals(""))
return toAppend;
//Otherwise add a comma and space
else
return existing + ", " + toAppend;
}
Then you can simply call the method inside your if statements:
if (radioButton.isChecked()){
texto = checkNullAndAppend(texto, radioButton3.getText());
}
if (radioButton3.isChecked()){
texto = checkNullAndAppend(texto, radioButton3.getText());
}
...
editText1 = texto;
...
I have three input fields.
First Name
Last item
Date Of Birth
I would like to get random data for each input from a property file.
This is how the property file looks. Field name and = should be ignored.
- First Name= Robert, Brian, Shawn, Bay, John, Paul
- Last Name= Jerry, Adam ,Lu , Eric
- Date of Birth= 01/12/12,12/10/12,1/2/17
Example: For First Name: File should randomly select one name from the following names
Robert, Brian, Shawn, Bay, John, Paul
Also I need to ignore anything before =
FileInputStream objfile = new FileInputStream(System.getProperty("user.dir "+path);
in = new BufferedReader(new InputStreamReader(objfile ));
String line = in.readLine();
while (line != null && !line.trim().isEmpty()) {
String eachRecord[]=line.trim().split(",");
Random rand = new Random();
//I need to pick first name randomly from the file from row 1.
send(firstName,(eachRecord[0]));
If you know that you're always going to have just those 3 lines in your property file I would get put each into a map with an index as the key then randomly generate a key in the range of the map.
// your code here to read the file in
HashMap<String, String> firstNameMap = new HashMap<String, String>();
HashMap<String, String> lastNameMap = new HashMap<String, String>();
HashMap<String, String> dobMap = new HashMap<String, String>();
String line;
while (line = in.readLine() != null) {
String[] parts = line.split("=");
if(parts[0].equals("First Name")) {
String[] values = lineParts[1].split(",");
for (int i = 0; i < values.length; ++i) {
firstNameMap.put(i, values[i]);
}
}
else if(parts[0].equals("Last Name")) {
// do the same as FN but for lastnamemap
}
else if(parts[0].equals("Date of Birth") {
// do the same as FN but for dobmap
}
}
// Now you can use the length of the map and a random number to get a value
// first name for instance:
int randomNum = ThreadLocalRandom.current().nextInt(0, firstNameMap.size(0 + 1);
System.out.println("First Name: " + firstNameMap.get(randomNum));
// and you would do the same for the other fields
The code can easily be refactored with some helper methods to make it cleaner, we'll leave that as a HW assignment :)
This way you have a cache of all your values that you can call at anytime and get a random value. I realize this isn't the most optimum solution having nested loops and 3 different maps but if your input file only contains 3 lines and you're not expecting to have millions of inputs it should be just fine.
Haven't programmed stuff like this in a long time.
Feel free to test it, and let me know if it works.
The result of this code should be a HashMap object called values
You can then get the specific fields you want from it, using get(field_name)
For example - values.get("First Name"). Make sure to use to correct case, because "first name" won't work.
If you want it all to be lower case, you can just add .toLowerCase() at the end of the line that puts the field and value into the HashMap
import java.lang.Math;
import java.util.HashMap;
public class Test
{
// arguments are passed using the text field below this editor
public static void main(String[] args)
{
// set the value of "in" here, so you actually read from it
HashMap<String, String> values = new HashMap<String, String>();
String line;
while (((line = in.readLine()) != null) && !line.trim().isEmpty()) {
if(!line.contains("=")) {
continue;
}
String[] lineParts = line.split("=");
String[] eachRecord = lineParts[1].split(",");
System.out.println("adding value of field type = " + lineParts[0].trim());
// now add the mapping to the values HashMap - values[field_name] = random_field_value
values.put(lineParts[0].trim(), eachRecord[(int) (Math.random() * eachRecord.length)].trim());
}
System.out.println("First Name = " + values.get("First Name"));
System.out.println("Last Name = " + values.get("Last Name"));
System.out.println("Date of Birth = " + values.get("Date of Birth"));
}
}
I am currently working on a Java program that crawls a webpage and prints out some information from it.
There is one part that I can't figure out, and thats when I try to print out one specific String Array with some information in it, all it gives me is " ] " for that line. However, a few lines before, I also try printing out another String array in the exact same way and it prints out fine. When I test what is actually being passed to the "categories" variable, its the correct information and can be printed out there.
public class Crawler {
private Document htmlDocument;
String [] keywords, categories;
public void printData(String urlToCrawl)
{
nextURL=urlToCrawl;
crawl();
//This does what its supposed to do. (Print Statement 1)
System.out.print("Keywords: ");
for (String i :keywords) {System.out.print(i+", ");}
//This doesnt. (Print Statement 2)
System.out.print("Categories: ");
for (String b :categories) {System.out.print(b+", ");}
}
public void crawl()
{
//Gather Data
//open up JSOUP for HTTP parsing.
Connection connection = Jsoup.connect(nextURL).userAgent(USER_AGENT);
Document htmlDocument = connection.get();
this.htmlDocument=htmlDocument;
System.out.println("Recieved Webpage "+ nextURL);
int guacCounter = 0;
for(Element guac : htmlDocument.select("script"))
{
if(guacCounter==5)
{
//String concentratedGuac = guac.toString();
String[] items = guac.toString().split("\\n");
categories = processGuac(items);
break;
}
else if(guacCounter<5) {
guacCounter++;
}
}
}
public String[] processKeywords(String totalKeywords)
{
String [] separatedKeywords = totalKeywords.split(",");
//System.out.println(separatedKeywords.toString());
return separatedKeywords;
}
public String[] processGuac(String[] inputGuac)
{
int categoryIsOnLine = 6;
String categoryData = inputGuac[categoryIsOnLine-1];
categoryData = categoryData.replace(",","");
categoryData = categoryData.replace("'","");
categoryData = categoryData.replace("|",",");
categoryData = categoryData.split(":")[1];
//this prints out the list of categories in string form.(Print Statement 3)
System.out.println("Testing here: " + categoryData.toString());
String [] categoryList=categoryData.split(",");
//This prints out the list of categories in array form correctly.(Print statement 4)
System.out.println("Testing here too: " );
for(String a : categoryList) {System.out.println(a);}
return categoryList;
}
}
I cut out a lot of the irrelevant parts of my code so there might be some missing variables.
Here is what my printouts look like:
PS1:
Keywords: What makes a good friend, making friends, signs of a good friend, supporting friends, conflict management,
PS2:
]
PS3:
Testing here: wellbeing,friends-and-family,friendships
PS4:
Testing here too:
wellbeing
friends-and-family
friendships
I have trouble splitting a name by a space, and I can't seem to figure out why. Could someone please provide me with a solution?
My code is like this:
public void getPlayerNames(int id){
try {
Document root = Jsoup.connect("http://www.altomfotball.no/element.do?cmd=team&teamId=" + id).get();
Element table = root.getElementById("sd_players_table");
Elements names = table.getElementsByTag("a");
for(Element name : names){
getPlayers().add(new Player(name.text()));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
which returns the name of football players as a string. The names are retrieved such as Mario Balotelli, Steven Gerrard, and so on, and I assumed I could use string.split(" "); to get me the first and last names, but whenever I try to access the second space of the string array it gives me an index out of bounds exception. Here is the code trying to fetch me the first name
/**
* Method to get the first name of a player
*/
public static String getFirstName(String name){
String[] nameArray = name.split(" ");
return nameArray[0];
}
Thanks for answers!
Sindre M
EDIT ######
So I got it to work, but thanks for the effort. The problem was that even though I could not see it in a simple sysout statement, the names actually contained a " "; character, so I solved it by running a replaceAll("  ;" , " ") on the names for a better formatting.
If you're trying to write a screen-scraper you need to be more defensive in your code... Definitely test the length of the array first and log any unexpected inputs so you can incorporate them later...
public static String getFirstName(String name) {
String[] nameArray = name.split(" ");
if (nameArray.length >= 1) { // <== check length before you access nameArray[0]
return nameArray[0];
} else {
// log error
}
return null;
}
Additionally java.util.Optional in Java 8 provides a great alternative to returning null...
public static Optional<String> getFirstName(String name) {
String[] nameArray = name.split(" ");
if (nameArray.length >= 1) {
return Optional.of(nameArray[0]);
} else {
// log error
}
return Optional.empty();
}
You might be getting in the actual string as you are retrieving from html page. try to debug and check.
package com.appkart.examples;
public class SplitProgram {
public void firstNameArray(String nameString) {
String strArr[] = nameString.split(",");
for (String name : strArr) {
String playerName = name.trim();
String firstName = playerName.substring(0, playerName.indexOf(" "));
System.out.println(firstName);
}
}
public static void main(String[] args) {
String nameString = "Mario Balotelli, Steven Gerrard";
SplitProgram program = new SplitProgram();
program.firstNameArray(nameString);
}
}
I think that the correct answer should be:
String[] nameArray = name.split("\\s+");
But to be honest, there are couple of answers at stackoverflow.
Eg.
How to split a String by space
How do I split a string with any whitespace chars as delimiters?
First try to replace white space as
string.replace(" ","");
then try to split with [,] as
String strAr[] = string.split(",");
I am trying to add an object inside an object using recursion. My object contains an arrayList and I am trying to add my objects to this arrayList. But instead of adding a new object, my objects are being replaced.
My code which is doing this: This is where the logic of adding an object is being done. But it is being replaced instead.
private ArrayList<SubChapters> recursiveSubChapters(ReportingTree tree, LinkedHashMap<String, HashMap<String, String>> linkedHashMap, Boolean isSubTree){
SubChapters subChapters = new Subchapters();
ArrayList<SubChapters> alchildUnits = new ArrayList<SubChapters>();
final String chapterId = linkedHashMap.get(tree.getUnitID()).get("unit_num");
final String chapterName= linkedHashMap.get(tree.getUnitID()).get("unit_name");
if (!isSubTree) {
subChapters.set(chapterId);
subChapters.setTreeName(chapterName);
}
final ArrayList<ReportingTree> branches = tree.getBranches();
if (branches != null) {
subChapters.hasSubUnits(true);
for (ReportingTree subTree: branches) {
subChapters.setSubChapters(recursiveSubChapters(subTree, linkedHashMap, false));
//This is where the logic of adding an object is being done. But it is being replaced instead.
}
alchildUnits.add(subChapters);
}
return alchildUnits;
}
My guess is that I am messing somewhere in the loop here but I am not able to figure out where I am messing up. Thanks in advance for any suggestions or help.
My subChapters class:
public String subChapterID;
public String subChapterName;
public boolean isSubTree= false;
public ArrayList<SubChapters> subChapters;
and getters and setters.
I have coded the same solution to return a string and see the order on a jsp. It works just fine. I am not able to apply the same to my issue here.
private String recursive(ReportingTree tree, LinkedHashMap<String, HashMap<String, String>> listUnitInfo, boolean isTop) {
final String unitID = tree.getUnitID();
final HashMap<String, String> unit = listUnitInfo.get(unitID);
String output = "";
if (!isTop) {
output += "<li>" + unit.get("unit_num") + "/" + unit.get("unit_name") + "";
}
final ArrayList<ReportingTree> branches = tree.getBranches();
if (branches != null) {
if (isTop) {
output += "<li>" + unit.get("unit_num") + "/" + unit.get("unit_name") + "";
}
output += "<ul>\n";
for (ReportingTree subTree : branches) {
output += recursive(subTree, listUnitInfo, false);
}
output += "</ul>";
} else {
if (isTop) {
output += "<li>No units match your criteria.";
}
}
output += "</li>\n";
return output;
}
What you're doing is subChapters.setSubChapters, what I think you're trying to do is
subChapters.addSubChapters.
The reason why it works with the strings is because you're using += to add
the new string to the old string. Doing setSubChapters would be the same as using = with the strings.
addSubChapters would be a method that should add something to an ArrayList variable inside your subChapters class.