Character extract challenge - java

MY database value for bus column. 12,34,56,8,9, ... im trying to extract only the bus numbers and not the commas and adding them to a String ArrayList. Anyone have any idea? :
im really confuse. heres my code:
for(int i =0; i< buses1.length() ; i++ )
{
if(buses1.charAt(i) == ',')
{
}
else
{
bus1 += Character.toString(buses1.charAt(i));
buses.add(bus1);
}
}
at this point, the codes are adding like this, "1", "2" , "3" , "4" not "12", "34" ....
Any one have any ideal?

Get rid of your current logic. You just need String#split() with delimeter as "," which returns your bus numbers as a array.
The below line is enough
String[] numbers = columnValue.split(",");
Then your ArrayList delcaration turns
List<String> busesList = new ArrayList<String>(Arrays.asList(numbers));

All you have to do is to split the String by using the ',' delimiter.
List<String> buses = Arrays.asList(buses1.split(","));
EDIT: Make sure that by doing so, buses will be an unmodifiable list( a list where you cannot add/remove elements to/from it). If you need a modifiable list, you can easily wrap it into one :
List<String> buses = new LinkedList<String>(Arrays.asList(buses1.split(",")));

Other answers have explained the recommended what to solve this problem. I just want to point out why your current attempt fails.
To get the effect you describe, it must actually be something like this:
for (int i = 0; i < buses1.length(); i++ ) {
String bus1 = "";
if (buses1.charAt(i) == ',') {
} else {
bus1 += Character.toString(buses1.charAt(i));
buses.add(bus1);
}
}
The problem is that you are adding a "bus" to the list at the wrong point. You need to add it when you've got the last character of a (single- or multi-digit) bus number. But you are adding it for each digit.
Your code actually needs to be something like this:
String bus1 = "";
for (int i = 0; i < buses1.length(); i++ ) {
if (buses1.charAt(i) == ',') {
// When we see a comma, we know that is the end of the bus number.
if (!bus1.isEmpty()) {
buses.add(bus1);
bus1 = "";
}
} else {
// Accumulate the digits of the current bus number.
bus1 += Character.toString(buses1.charAt(i));
}
}
// Deal with stuff after the last comma.
if (!bus1.isEmpty()) {
buses.add(bus1);
}
Note that we could improve on that in a couple of important ways. But it is easier to see the relationship with your (hypothesized) original code with this version.

Related

How to remove phrase from beginning to end

I've been trying for a while now, and I just give up. I want to extract the data from type (regardless whether it's a capital letter or not) to the numbers. Pretty much, I'm trying to get rid of model and birthday in each line, but what makes it even more difficult, is that it's all one string. I spaced it out just to make it easier to read.
I'm trying to find the answer in REGEX java. This is what I was trying but, is deleting of course the whole String after the first number(4,66)
[;][mo].*
Thank you in advance!
Input:
Type:Carro;high:4,66;model:fourDoors;birthday:01/01/1980
type:Truck;high:5,66;model:twoDoors;birthday:29/05/1977
tYpe:motorcycle;high:1,55;model:fiveDoors;birthday:01/01/1980
type:Carro;high:4,66;type:model;birthday:6/12/1887
type:Carro;high:9,66;model:Doors;birthday:05/12/2010
Expected OutPut:
Type:Carro;high:4,66
type:Truck;high:5,66
tYpe:motorcycle;high:1,55
type:Carro;high:4,66
type:Carro;high:9,66
Hopefully this will work for you. There are a few ways to make this code slightly smaller, however, this should at least help to get you on the right path.
I placed it into a main method, but it would be easy to put it into its own function. This would allow you to pass any number of arrays at it.
I added all of the logic in the comments within the code, I hope it helps:
public static void main(String[] args) {
/*Get your strings into an Array*/
String[] str = {"Type:Carro;high:4,66;model:fourDoors;birthday:01/01/1980",
"type:Truck;high:5,66;model:twoDoors;birthday:29/05/1977",
"tYpe:motorcycle;high:1,55;model:fiveDoors;birthday:01/01/1980",
"type:Carro;high:4,66;type:model;birthday:6/12/1887",
"type:Carro;high:9,66;model:Doors;birthday:05/12/2010",
"Expected OutPut:",
"Type:Carro;high:4,66",
"type:Truck;high:5,66",
"tYpe:motorcycle;high:1,55",
"type:Carro;high:4,66",
"type:Carro;high:9,66"
};
/*Create a "final staging" array*/
String[] newStr = new String[str.length - 1];
for (int j = 0; j < str.length - 1; j++) {//For each of your strings
str[j] = str[j].toLowerCase();//set the string to lower
/*If they don't contain a semi-colon and a model or birthday reference go to else*/
if (str[j].contains(";") && str[j].contains("model") || str[j].contains("birthday")) {
/*Otherwise, split the string by semi-colon*/
String[] sParts = str[j].split(";");
String newString = "";//the new string that will be created
for (int i = 0; i < sParts.length - 1; i++) {//for each part of the sParts array
if (sParts[i].contains("model") || sParts[i].contains("birthday")) {//if it contains what is not desired
//Do Nothing
} else {
newString += sParts[i];//otherwise concatenate it to the newString
}
newStr[j] = newString;//add the string to the "final staging" array
}
} else {
newStr[j] = str[j];//if it didn't have semi-colons and birthday or model, just add it to the "final staging" array
}
}
for (String newS : newStr) {// finally if you want to see the "final staging" array data... output it.
System.out.println(newS);
}
}
OUTPUT
type:carrohigh:4,66
type:truckhigh:5,66
type:motorcyclehigh:1,55
type:carrohigh:4,66
type:carrohigh:9,66
expected output:
type:carro;high:4,66
type:truck;high:5,66
type:motorcycle;high:1,55
type:carro;high:4,66
If I happened to miss something in the requirements, please let me know, I would be happy to fix it.
String str = "Type:Carro;high:4,66;model:fourDoors;birthday:01/01/1980,type:Truck;high:5,66;model:twoDoors;birthday:29/05/1977,tYpe:motorcycle;high:1,55;model:fiveDoors;birthday:01/01/1980,type:Carro;high:4,66;type:model;birthday:6/12/1887";
StringTokenizer tokens = new StringTokenizer(str, ",");
while (tokens.hasMoreTokens()) {
String token = tokens.nextToken() ;
StringTokenizer tokens2 = new StringTokenizer(token, ":");
while (tokens2.hasMoreTokens()) {
String key = tokens2.nextToken() ;
if (key.equalsIgnoreCase("type")){
System.out.println("locate: "+key+"\n");
}
}
}

Java/Angularjs - convert variable names to normal English conventions

My goal here is to retrieve the attribute names from a class, which I have already done using JAVA Reflections. But I want to be able to transform the variable naming convention, say firstName to First Name.
My current idea is to use .split() to transform position: 0 (usually a lower-case) to Uppercase, then loop until I find subsequent UpperCases, and push a blank space in between. Are there any better way to do this?
EDIT: This is my current method if any of you are interested:
public List<String> getProfileConstraintTemplateEnglish() {
//what I want to return
List<String> transformedList = new ArrayList<>();
//The reflection that I'm getting
List<ResultProfileConstraintTemplate> tmp = constraintService.getProfileCTml();
//loop each obj in reflection list
for (ResultProfileConstraintTemplate r : tmp) {
//get the letters first from the title in obj
String[] field = r.getTitle().split("");
//this is the transformed string in each tmp.
String transformed = "";
//converting the array to a list for simpler addition.
List<String> fieldString = Arrays.asList(field);
//adding a counter to know which is the "first" position.
int counter = 0;
for (String s : fieldString) {
//first letter
if (counter == 0) {
transformed += s.toUpperCase();
}
//everything else
if (counter != 0 && s.equals(s.toUpperCase())) {
transformed+= " ";
transformed+=s;
}
else if(counter != 0 && s.equals(s.toLowerCase())){
transformed+=s;
}
//increment counter
counter++;
}
//add the transformed word to list.
transformedList.add(transformed);
}
return transformedList;
}
Result:
I think your way is the only way. If you post your code, maybe we can shed more light on the matter.
You can use isUpperCase() method and if it returns true replace it with a space and the letter and always convert first letter i.e indexOf(0) to toUpperCase().

How do I access and manipulate individual values in a String Array when using a while and for loop

Very new to Java: Trying to learn it.
I created an Array and would like to access individual components of the array.
The first issue I am having is how to I print the array as a batch or the whole array as indicated below? For example: on the last value MyValue4 I added a line break so that when the values are printed, the output will look like this: There has to be a better way to do this?
MyValue1
MyValue2
MyValue3
MyValue4
MyValue1
MyValue2
MyValue3
MyValue4
The next thing I need to do is, manipulate or replace a value with something else, example: MyValue with MyValx, when the repeat variable is at a certain number or value.
So when the repeat variable reaches 3 change my value to something else and then change back when it reaches 6.
I am familiar with the Replace method, I am just not sure how to put this all together.
I am having trouble with changing just parts of the array with the while and for loop in the mix.
My Code:
public static String[] MyArray() {
String MyValues[] = { "MyValue1", "MyValue2", "MyValue3", "MyValue4\n" };
return MyValues;
}
public static void main(String[] args) {
int repeat = 0;
while (repeat < 7) {
for (String lines : MyArray()) {
System.out.println(lines);
}
repeat = repeat + 1;
if (repeat == 7) {
break;
}
}
}
Maybe to use for cycle to be shorter:
for (int i = 0; i < 7; i++) {
for (String lines : MyArray()) {
// Changes depended by values.
if (i > 3) {
lines = MyValx;
}
System.out.println(lines); // to have `\n` effect
}
System.out.println();
}
And BTW variables will start in lower case and not end withenter (\n). So use:
String myValues[] = {"MyValue1", "MyValue2", "MyValue3", "MyValue4"};
instead of:
String MyValues[] = { "MyValue1", "MyValue2", "MyValue3", "MyValue4\n" };
and add System.out.println(); after eache inside cycle instead of this:
MyValues[n] = "value";
where n is the position in the array.
You may consider using System.out.println() without any argument for printing an empty line instead of inserting new-line characters in your data.
You already know the for-each loop, but consider a count-controlled loop, such as
for (int i = 0; i < lines.length; i++) {
...
}
There you can use i for accessing your array as well as for deciding for further actions.
Replacing array items based on a number in a string might be a bit trickier. A regular expression will definitely do the job, if you are familiar with that. If not, I can recommend learning this, because it will sure be useful in future situations.
A simpler approach might be using
int a = Integer.parseInt("123"); // returns 123 as integer
but that only works on strings, which contain pure numbers (positive and negative). It won't work with abc123. This will throw an exception.
These are some ideas, you might try out and experiment with. Also use the documentation excessively. ;-)

Java String spilter

I have a string of annotation of country abbreviation , I want to split them out so I can identify the country of each abbreviation. Such that I will have String c = USA; I will output the country name...
currently it doesnt have c = USA but only A
public class Example {
public static void main(String[] args) {
String x = "USAIND";
String c = "";
System.out.print("Country: ");
for (int i = 0; i < 3; i++) {
c = Character.toString(x.charAt(i));
System.out.print(c);
if (c.equals("USA")) {
System.out.println("United State of America");
}
}
System.out.println("");
System.out.print("Country: ");
for (int i = 3; i < 6; i++) {
c = Character.toString(x.charAt(i));
System.out.print(c);
if (c.equals("IND")) {
System.out.println("India");
}
}
System.out.println("");
}
}
You need to append each character to your String and then compare it, otherwise, it'll just keep replacing your String with the last character always.
for (int i = 0; i < 3; i++) {
c += Character.toString(x.charAt(i)); // Appending all the characters one by one
}
System.out.print(c); // Printing the String c after all the characters are appending
if (c.equals("USA")) { // checking if its equal to USA
System.out.println("United State of America");
}
And the same goes with the other half of the process.
c = ""; // re-initialize it to blank
for (int i = 3; i < 6; i++) {
c += Character.toString(x.charAt(i));
}
System.out.print(c);
if (c.equals("IND")) {
System.out.println("India");
}
But the easiest way would be to use String.substring(startIndex, endIndex) for this.
String c = x.substring(0,3); // For USA
String c1 = x.substring(3,6); // For IND
because when you do this
c = Character.toString(x.charAt(i));
the character at the ith position is getting stored in c and as it is in a for loop the only thing that would be stored there would be 'A'
use a substring instead of the for loop and charAt
c = x.substring(0,3); \\which would give you "USA"
You should probably use String.substring(...) for this.
You are iterating through the string, but you only retain the last character because of this snippet:
c = Character.toString(x.charAt(i));
This should be:
c += Character.toString(x.charAt(i));
As this will append the current character iteration to the overall string. Replace the snippets with this fix, for the two loops. The c variable will build up the country code and will pass this condition this time:
if (c.equals("USA")) {
After the first loop and before the second loop, you will need to re-initialize the c variable:
c = "";
Once done, you can put that logic in a method of its own, so you avoid duplicate code within the loops.
This logic could be simplified by using String.substring instead, as others pointed out, as you work in details with the String.charAt which is more tedious. I thought though that pointing out your logic error was worth it, before giving you other pointers.
So talking about other approaches, you could try another one to your country code and name console output. Try to use a HashMap where the keys are the country code and the value is the country's name. You can iterate through the HashMap after that and print out both keys and values. That would be more high-level to your current solution and way shorter in code.
EDIT1: I offered the code to the last suggestion but I removed it, as I realized that giving code to assignment related questions is not encouraged.
I would go another way, either try to add a terminal symbol like ";". If this is not possible you could check with String.contains("USA") if a certain country is set. But beaware it could happen that you will find a country not listed in because the combination of two others.
With your logic, I thing it will be better to use
public String substring(int beginIndex, int endIndex)
Get the substring for a start index and the end index and compare. Currently you are just getting the character .With your current implementation you have to convert each character to String and append.
For the part of splitting, I would use Guava's Splitter, like so:
Splitter.fixedLength(3).split(x)
And for the part of matching abbreviation with full name, I would use an enum instead of equals comparing, it seems a little cleaner. So, a possible full result would be:
public class Example {
public static enum Country {
USA("United States of America"), IND("India");
String fullName;
Country(String fullName) {
this.fullName = fullName;
}
String getFullName() {
return fullName;
}
};
public static void main(String[] args) {
String x = "USAINDUSAIND";
for (String s : Splitter.fixedLength(3).split(x)) {
System.out.println(Country.valueOf(s).getFullName());
}
}
}
EDIT: Sorry about using third party, seemed clean to me. I agree with the other answers in using substring, but I like more thinking of everything as just one process and not two, so you can easily have a string of more than 2 abbreviations, like (example assuming the Enum as above)
public static void main(String[] args) {
String x = "USAINDUSAIND";
for (int i = 0;i < x.length();i += 3) {
System.out.println(Country.valueOf(x.substring(i, i + 3).getFullName());
}
}

Java characters count in an array

Another problem I try to solve (NOTE this is not a homework but what popped into my head), I'm trying to improve my problem-solving skills in Java. I want to display this:
Students ID #
Carol McKane 920 11
James Eriol 154 10
Elainee Black 462 12
What I want to do is on the 3rd column, display the number of characters without counting the spaces. Give me some tips to do this. Or point me to Java's robust APIs, cause I'm not yet that familiar with Java's string APIs. Thanks.
It sounds like you just want something like:
public static int countNonSpaces(String text) {
int count = 0;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) != ' ') {
count++;
}
}
return count;
}
You may want to modify this to use Character.isWhitespace instead of only checking for ' '. Also note that this will count pairs outside the Basic Multilingual Plane as two characters. Whether that will be a problem for you or not depends on your use case...
Think of solving a problem and presenting the answer as two very different steps. I won't help you with the presentation in a table, but to count the number of characters in a String (without spaces) you can use this:
String name = "Carol McKane";
int numberOfCharacters = name.replaceAll("\\s", "").length();
The regular expression \\s matches all whitespace characters in the name string, and replaces them with "", or nothing.
Probably the shortest and easiest way:
String[][] students = { { "Carol McKane", "James Eriol", "Elainee Black" }, { "920", "154", "462" } };
for (int i = 0 ; i < students[0].length; i++) {
System.out.println(students[0][i] + "\t" + students[1][i] + "\t" + students[0][i].replace( " ", "" ).length() );
}
replace(), replaces each substring (" ") of your string and removes it from the result returned, from this temporal string, without spaces, you can get the length by calling length() on it...
The String name will remain unchanged.
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
cheers
To learn more about it you should watch the API documentation for String and Character
Here some examples how to do:
// variation 1
int count1 = 0;
for (char character : text.toCharArray()) {
if (Character.isLetter(character)) {
count1++;
}
}
This uses a special short from of "for" instruction. Here's the long form for better understanding:
// variation 2
int count2 = 0;
for (int i = 0; i < text.length(); i++) {
char character = text.charAt(i);
if (Character.isLetter(character)) {
count2++;
}
}
BTW, removing whitespaces via replace method is not a good coding style to me and not quite helpful for understanding how string class works.

Categories