How to add two string array members into one string variable - java

I've been trying to figure out how to add an extra string array member to a string variable with no luck. Here is the code.
myDirString = myDirString.trim();
String[] myDirStringParts = myDirString.split(" +");
MySize = myDirStringParts[0];
MyNum = myDirStringParts[1];
Total = myDirStringParts[2];
MyName = myDirStringParts[3];
Basically I want myDirStringParts[2]; to also be included into MyName.

MyName = myDirStringParts[3] + myDirStringParts[2];
will work.

Simply
MyName = myDirStringParts[3] + myDirStringParts[2];
should do the trick.
However, i notice a few things about your code that i would like to point out:
Declare the variables MyName, Total, MyNum, MySize.
Make sure that myDirStringParts contains atleast 3 elements after the split(" +") call.
You can do this by the following code snippet:
if(myDirStringParts.length >= 4) {
MySize = myDirStringParts[0];
MyNum = myDirStringParts[1];
Total = myDirStringParts[2];
MyName = myDirStringParts[3] + myDirStringParts[2];
} else {
// print out an error message.
System.err.println("myDirString does not contain all the required data!");
}

Related

Get Portion of String

I need to get the values after "Swap:".
I've already developed a method to get the output from a shell command so I have a string that contains everything you see in the picture but now from the string I want to get ONLY the value after the Swap: How can i do this? These value are variable and can be even all three 0.
Let's say you have the text stored in a String called textContent. Assuming the Swap-line is the last part of your String, then you could do something like this:
int index = textContent.indexOf("Swap:");
index += "Swap:".length();
textContent.subString(index);
Try this:
String[] stringParts = text.substring(text.indexOf("Swap:") + 5).trim().split("( )+");
int[] parts = new int[stringParts.length];
for (int i = 0; i < stringParts.length; i++)
parts[i] = Integer.parseInt(stringParts[i]);
It will fill an integer array will the values after the "Swap" part.
Since you have already stored the output of the shell command, you simply need to do some string manipulation to search and extract the relevant information. The following particular string manipulation methods might be of interest to you: trim(), indexOf(), and substring().
Below is a simple example code on how to extract the value under the total's column using the above String methods:
public class ShellOutput {
public ShellOutput() {
final String extract = "Swap:"; // the keyword to search
String shellOutput = "Swap: 75692 29657 0"; // your shell output
int position = shellOutput.indexOf(extract); // get the position of the Swap: text
if (position != -1) {
String swapLine = shellOutput.substring(position + extract.length()); // remove everything except the swap line
String numbers = swapLine.trim(); // assuming they are spaces, otherwise do some operations to remove tabs if used
int firstSpace = numbers.indexOf(' '); // get the first space or change to a tab character if it is used
String totalNumber = numbers.substring(0, firstSpace); // remove up to the first found after the number
System.out.println("Total = " + totalNumber);
} else {
System.out.println("No '" + extract + "' segment found.");
}
}
public static void main(String[] args) {
new ShellOutput();
}
}
Output: Total = 75692

Unexpected Type errors

I'm getting two small unexpected type errors which I'm having trouble trying to solve.
The errors occur at:
swapped.charAt(temp1) = str.charAt(temp2);
swapped.charAt(temp2) = temp1;
Any advice?
public class SwapLetters
{
public static void main(String[] args)
{
System.out.println("Enter a string: ");
String str = new String(args[0]);
String swapped = str;
char[] charArray = str.toCharArray();
System.out.println("Enter a position to swap: ");
int Swap1 = Integer.parseInt(args[1]);
System.out.println("Enter a second position to swap: ");
int Swap2 = Integer.parseInt(args[2]);
char temp1 = str.charAt(Swap1);
char temp2 = str.charAt(Swap2);
swapped.charAt(temp1) = str.charAt(temp2);
swapped.charAt(temp2) = temp1;
System.out.println("Original String = " + str);
System.out.println("Swapped String = " + swapped);
}
}
You can assign values to variables, not other values. Statements like 5 = 2 or 'a' = 'z' don't work in Java, and that's why you're getting an error. swapped.charAt(temp1) returns some char value you're trying to overwrite, it's not a reference to a particular position inside the String or a variable you can alter (also, mind that Java Strings are immutable so you can't really change them in any way after creation).
Refer to http://docs.oracle.com/javase/7/docs/api/java/lang/String.html for information on using String, it should have a solution for what you're trying to do.
Your code may even throw IndexOutOfBoundsException - if the index argument is negative or not
less than the length of this string. Check the length of each string.
The left side of your assignment cannot receive that value.
Description of String#charAt(int):
Returns the char value at the specified index
It returns the value of the character; assigning values to that returned value in the following lines is the problem:
swapped.charAt(temp1) = str.charAt(temp2);
swapped.charAt(temp2) = temp1;
Also, String#charAt(int) expects an index of a character within the String, not the character itself (i.e. chatAt(temp1) is incorrect), so your method will not work as expected even if you fix the former problem.
Try the following:
String swapped;
if(swap1 > swap2) {
swap1+=swap2;
swap2=swap1-swap2;
swap1-=swap2;
}
if(swap1!=swap2)
swapped = str.substring(0,swap1) + str.charAt(swap2) + str.substring(swap1, swap2) + str.charAt(swap1) + str.substring(swap2);

Separate Multiple Integers from a String

I've got a question about making a save function.
I'm trying to have a string be saved as a single file to set specific settings on a game. So saveFile would read "002007...", having 002 be a player's location, then 007 a player's level, for example.
I understand how to compile the various variables into a single string, but how would I return it to individual variables?
You better go with SQLite or SharedPreferences if you really want to save settings for a game on Android.
On the other hand, if you have to stick with saving a String on a file, you might want to use a delimiter(ie \r\n or # or | would do it) between numbers. So while parsing back delimiters will help you a lot, but beware when things get complicated a single String won't do the thing nicely. Then you might want to use JSON (for simplicity I would prefer gson) to encode your settings into one String and vice verse.
You could use a delimiter between the values like this:
int location = 02;
int level = 3;
int powerUps = 46;
... and so on
String saveString = location + "#" + level + "#" + powerUps + "#" + ...
Then to load the String back into variables:
String[] values = saveString.split("#");
location = values[0];
level = values[1];
powerUps = values[2];
... and so on
My advice is to check out Shared Preferences and you can read Android's documentation on it here.
If you did want to use your single String, file method, I suggest using delimiters. That simply means to put commas, or other types of delimeters in between different integer values. Instead of "002007", save it as "002,007". Example:
String s = "002,007"
String[] values = s.split(","); // values[0] is "002" and values[1] is "007"
Using the .split(String) command will return a String array with each element in the array containing parts of the String that was split up by the parameter, in this case: ,
If you wanted to separate values per person, something like this could be done:
String s = "002,007;003,008";
String[] people = s.split(";"); // people[0] is "002,007", people[1] is "003,004"
String[][] person = new String[people.length][people[0].split(",").length];
for (int i = 0; i < people.length; i++)
{
person[i] = people[i].split(",");
}
Here is what the array would then contain:
person[0][0] is "002"person[0][1] is "007" person[1][0] is "003" person[1][1] is "008"
// print it for your own testing
for (String ppl[] : person)
{
for (String val : ppl)
{
System.out.print(val + " ");
}
System.out.println("");
}

How can I parse a jagged array to individual variables in Java?

I have a jagged array that has a minimum of three elements, and I need to parse out the first five elements, filling any nulls with a space.
// there will ALWAYS be three elements
String whiconcatC = scrubbedInputArray[0];
String whiconcatD = scrubbedInputArray[1];
String whiconcatE = scrubbedInputArray[2];
// there MAY be a fourth or fifth element
if (scrubbedInputTokens > 3) {
String whiconcatF = scrubbedInputArray[3];
} else {
String whiconcatF = " ";
}
//
if (scrubbedInputTokens > 4) {
String whiconcatG = scrubbedInputArray[4];
} else {
String whiconcatG = " ";
}
While the above code does not generate errors during compile, subsequent lines referencing whiconcatF or whiconcatG will error out during compile with cannot find symbol.
I've tried using forEach and StringTokenizer (after converting the array to a delimited string), but can't figure out how to work a default value in the instance that there's no value in spots 4 & 5.
I've not been able to figure out any other way to do this nor why my if logic is failing. Suggestions?
Thats because they have local scope and are defined inside brackets. Thus the die when you close the brackets and are not reachable. Define them outside and you should be fine.
String whiconcatC = scrubbedInputArray[0];
String whiconcatD = scrubbedInputArray[1];
String whiconcatE = scrubbedInputArray[2];
String whiconcatF = "";
String whiconcatG = "";
// there MAY be a fourth or fifth element
if (scrubbedInputTokens > 3) {
whiconcatF = scrubbedInputArray[3];
} else {
whiconcatF = " ";
}
//
if (scrubbedInputTokens > 4) {
whiconcatG = scrubbedInputArray[4];
} else {
whiconcatG = " ";
}
Declare the whiconcatF outside the if-else for them to visible beyond it. Currently both the String variables are within the scope of if and else only. Once its moved above the if, it gets the method level scope(I hope this whole snippet is not within any other block), and thus you can access them anywhere in the method.
String whiconcatF = " "; // Default value
if (scrubbedInputTokens > 3) {
whiconcatF = scrubbedInputArray[3];
}
String whiconcatG = " "; // Default value
if (scrubbedInputTokens > 4) {
whiconcatG = scrubbedInputArray[4];
}
Since you have default values now, you can remove the else part for both the if.

to get the unique name by using starting letter of a string and concatenate with an integer

I need to get the unique name from a string and concatenate with an integer in java.So I want to take first letter of the string and increment that letter with an integer.
Example: tenant name:
"ani,raj,rob" and i need to get the
schema name like a001,r001,r002
here r value will be incremented because of repetition.So I request you to help me find answer for this.I am getting the first letter from a string but I need to concatenate that with an integer.
String name = new String(tenantName);
char sc=tenantName.charAt(0);
String whereClause="tenant_id= select max(tenant_id) from tenant_connection_details
tcd1 where schema_name like'"+sc+"%'";
tenantList= tenantImpl.getAllTenantsByWhereClause(whereClause);
List<String> myNames = new ArrayList<String>();
myNames.add("ani");
myNames.add("raj");
myNames.add("rob");
myNames.add("jigar");
int counter=1;
for(String str:myNames){
System.out.println(str.charAt(0)+String.format("%04d", i));
counter++;
}
if i understand you correctly, it should be something like this (not safe or checked or anything!!):
private List<String> list = new ArrayList<String>();
private void strangeConcat(String name){
int index = 1;
while(this.list.contains(String.valueOf(name.charAt(0))
+ this.getThreeDigitIndex(index))){
index++;
}
this.list.add(String.valueOf(name.charAt(0)) + this.getThreeDigitIndex(index));
}
Something like the following:
char sc=tenantName.charAt(0); // May use Character.toLowerCase() here, if only lowercase letters are allowed
String whereClause="tenant_id= select max(tenant_id) from tenant_connection_details
tcd1 where schema_name like'"+sc+"%'";
tenantList= tenantImpl.getAllTenantsByWhereClause(whereClause);
int number = tenentList.size() + 1;
String result = Character.toString(sc) + String.format("%04d", number);

Categories