I'm using a for loop to append an "m" on to a string array, then passing each string to a DDE connection to download a stock quote.
String[] symbols = {"AUDUSD", "EURUSD", "GBPUSD", "USDJPY"};
String ibfxSym[] = new String[symbols.length];
for(int i = 0; i<symbols.length;i++) {
ibfxSym[i] = symbols[i] + "m";
}
// start DDE
for (int i = 0; i < connections.length; i++) {
try {
connections[i].getQuote(ibfxSym[i]);
} catch (Exception e) {
System.out.println("error");
}
That does not work, but if I pass in:
String[] ibfxSym = {"AUDUSDm", "EURUSDm", "GBPUSDm", "USDJPYm"};
instead of the loop it works just fine. I've tried printing each string as it is created in the loop, and they look the same. Is there some weird formatting the loop is adding that I can't see? I even tried:
ibfxSym[i] = String.valueOf(ibfxSym[i].trim());
to see if there was maybe a carriage return or something being appended that I couldn't see. Any ideas about what's going wrong here?
Thanks.
You're not reading from the same array that you're modifying...
ibfxSym[i] = symbols[i] + "m";
for (int i = 0; i < connections.length; i++) {
try {
connections[i].getQuote(ibfxSym[i]);
In other words, you are assuming that i, being derived from iterating over connections, is also a valid index for ibfxSym.
Your loop is working just fine, the connection loop instead would work only if your connections array maps your ibfxSym array though..
if
connections.length
is bigger than
ibfxSym.length
or in this case 4, you should get an array index out of bounds exception i think.
Have you tried to do this:
for(int i = 0; i<symbols.length;i++) {
ibfxSym[i] = new String(symbols[i] + "m");
}
Related
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");
}
}
}
I am unable to delete all my upper case characters in my string. Any insight is appreciated.
if I input MANDY as str, I get output as AD. I am not sure why it is has this behavior.
StringBuilder outString = new StringBuilder(str);
for(int i = 0; i<outString.length(); i++){
if(Character.isUpperCase(outString.charAt(i))){
outString.deleteCharAt(i);
}
}
return outString.toString();
Thanks
By deleting the characters you change the indexes, so every uppercase character after another is not deleted.
A simple "trick" is to iterate the buffer the other way around (starting at the end). That way you only affect the indexes of already processed characters
for(int i = outString.length()-1; i>=0; i--){
if(Character.isUpperCase(outString.charAt(i))){
outString.deleteCharAt(i);
}
}
You can do this using regex:
String s = "MANDYs";
s = s.replaceAll("[A-Z]", "");
System.out.println(s);
You are increasing index while you are deleting items from the String you are iterating. I would call it a case of Concurrent Modification, though StringBuilder doesn't give any exception.
Better is to do this:
int i = 0;
while (i < outString.length()) {
if (Character.isUpperCase(outString.charAt(i))) {
outString.deleteCharAt(i);
} else {
i++;
}
}
This is for homework. I can't seem to return the correct code when my method gets executed. I'm not sure if my for loop is iterating properly or if i'm supposed to use the enhanced for loop. This is my code:
/**
* Replaces the words in the string so that every last character is upper case
*/
public void lastToUpperCase()
{
for(int i=0;i>list.size();i++)
{
String chopped = list.get(i);
String chopped1 = chopped.substring(chopped.length()-1,chopped.length());
String screwed1 = chopped.substring(0,chopped.length()-1);
String chopped2 = chopped1.toUpperCase();
String frankenstein = screwed1 + chopped2;
System.out.print(frankenstein);
}
}
This is what is supposed to be printed:
[PeteR, PipeR, pickeD, A, pecK, oF, pickleD, peppers.]
I would start with a for-each loop and use a StringBuilder (for setCharAt(int, char)) and something like
for (String str : list) {
StringBuilder sb = new StringBuilder(str);
sb.setCharAt(sb.length() - 1, Character.toUpperCase(//
sb.charAt(sb.length() - 1)));
System.out.print(sb);
}
The issue with
for(int i=0;i>list.size();i++)
is that i is not >list.size() so your loop isn't entered.
for(int i=0;i<list.size();i++)
To elaborate on others' comments about the for: The second expression is treated like a "while" condition; that is, the loop keeps going while the expression is true. As soon as the expression becomes false, the loop terminates, and the program goes to the statement after the loop. The way you wrote this (note that it's easier to read with extra spaces, instead of all jammed together):
for (int i = 0; i > list.size(); i++)
i starts out as 0. But then 0 > list.size() is false, so it exits the loop immediately--that is, it never executes the list body even once.
I figured it out:
/**
* Replaces the words in the string so that every last character is upper case
*/
public void lastToUpperCase()
{
for(int i=0; i<list.size(); i++)
{
String chopped = list.get(i);
String screwed = chopped.substring(chopped.length()-1,chopped.length());
String frankenstein = screwed.toUpperCase();
String von = list.set(i, chopped.substring(0, chopped.length()-1) + frankenstein);
}
}
I am trying to convert a string to an array then back to a string again. I am trying to achieve this in C# but as i have not done C# in a while i am having issues. I created the following code in Java and it works fine:
String sHtml = "test1\r\ntest2\r\ntest3\r\ntest4\r\ntes5t\r\ntest6\r\ntest7\r\ntest8\r\ntest9\r\ntest10\r\ntest11\r\ntest12\r\ntest13\r\ntes14t\r\n";
int temp = 0;
List<String> emailText = new ArrayList<String>();
for(int x = 0; x<sHtml.length();x++){
if(sHtml.charAt(x)=='\n'){
emailText.add(sHtml.substring(temp, x));
temp = x;
}
}
String testingString="";
for(String words:emailText){
//System.out.println(words);
testingString+=words;
}
System.out.println(testingString);
This works fine in Java. The following code is what i have for C#:
int temp = 0;
List<string> emailText = new List<string>();
for (int x = 0; x < sHtml.Length; x++)
{
if (sHtml[x].Equals("\\n"))
{
emailText.Add(sHtml.Substring(temp, x));
temp = x;
}
else
{
}
}
string testingString = "";
//sHtml = string.Join("\r\n", emailText.ToArray());
foreach (String word in emailText)
{
testingString += word;
}
Console.WriteLine(testingString);
The java code outputs fine but i am getting no output from the C# code. I have a feeling i am missing something small from the C# code but i am not sure what, Can someone please help?
Thanks in advance
You don't get output in C# because you don't output anything :-) You omitted the Java System.out.println statement without adding the C# equivalent:
Console.WriteLine(testingString);
BTW: Once you're replacing your Java code by C# code, you can also make use of the .NET framework's features (as others already mentioned). This way you can reduce your program to one line:
Console.WriteLine(string.Join(string.Empty, sHtml.Split('\n')));
Try this: although i would recommend using a string builder for larger strings as they're immutable.
string yourString = "this,is,a,example,string";
string newString = "";
string[] array = yourString.Split(',');
foreach (string s in array)
{
newString += s;
}
Console.WriteLine(newString);
Why don't you use this to split the string:
string[] List = sHtml.split("\\n");
And this to do something with the arraylist of strings to do something:
for (String s in List){
//Do something with each separate String s
}
Why not use split and join?
var arr = str.Split('\n');
var newStr = string.Join("", arr);
Your 'for' loop has 2 mistakes - you should keep the character '\n' and Java 'substring' doesn't have the same second parameter that .NET 'Substring' has, so you need to adjust that:
for (int x = 0; x < sHtml.Length;x++)
{
if (sHtml[x] == '\n')
{
emailText.Add(sHtml.Substring(temp, x - temp));
temp = x;
}
}
I have a parameter which is obtained as a string
String Dept_ID[] = request.getParameterValues("dept_id"))
in jsp. I have to insert the string in the db whose type is numeric
#DEPT_ID NUMERIC(10,0)).
How to perform the conversion?
Your code is receiving an array of strings. You can convert an entry from the array into a number using Integer.parseInt or Long.parseLong as appropriate.
For example:
String Dept_ID[] = request.getParameterValues("dept_id"));
int[] ids = null;
if (Dept_ID != null) {
ids = new int[Dept_ID.length];
for (int index = 0; index < Dept_ID.length; ++index) {
ids[index] = Integer.parseInt(Dept_ID[index]);
}
}
If the number uses a different radix (number base) than 10, you can supply the radix as a second arg (see the links for details).
The above answer is correct, but it doesn't take into account what happens when your getting letters as input that can't be converted. You wanna use a try and catch method for that part if you ask me.
Something like (assuming your using the code above):
String Dept_ID[] = request.getParameterValues("dept_id"));
int[] ids = null;
if (Dept_ID != null) {
ids = new int[Dept_ID.length];
for (int index = 0; index < Dept_ID.length; index++) {
try {
ids[index] = Integer.parseInt(Dept_ID[index]);
}
catch ( NumberFormatException e ) {
System.out.println("Invalid crap.");
}
}
}
Also notice that I put the ++index part the other way around to index++, if you don't do this you will keep missing the first index in the array all the time.