How to remove square brackets on either side of string value - java

When I choose a row on the table it prints out the selected item in a string as shown. How do I remove the square brackets from either side of the string.
Below is my code to populate TextFields with the data. You can see it populates successfully but with the [].
the table and output
tableView.getSelectionModel().selectedItemProperty().addListener((v, oldValue, newValue) -> {
String input = newValue.toString();
String[] str_array = input.split(", ");
String code = str_array[0];
String name = str_array[1];
String lecturer = str_array[2];
String year = str_array[3];
String semester = str_array[4];
codeInput.setText(code);
nameInput.setText(name);
lectureInput.setText(lecturer);
yearInput.setText(year);
semesterInput.setText(semester);
System.out.println(input);
});

You newValue should be an Object. Let's say it's an object of SchoolInfo with variables of String code, String name, String lecturer, int year, and int semester. Your Object should have Getters and Setters. You should do something like.
Warning: Some of those other answers may get the job done but are very bad ideas. The way you are trying to handle this data is a bad idea.
tableView.getSelectionModel().selectedItemProperty().addListener((v, oldValue, newValue) -> {
SchoolInfo tempSchoolInfo = (SchoolInfo)newValue;
String code = tempSchoolInfo.getCode();
String name = tempSchoolInfo .getName();
String lecturer = tempSchoolInfo.getLecturer;
int year = tempSchoolInfo.getYear();
int semester = tempSchoolInfo.getSemester();
codeInput.setText(code);
nameInput.setText(name);
lectureInput.setText(lecturer);
yearInput.setText(Integer.toString(year));
semesterInput.setText(Integer.toString(semester));
System.out.println(input);
});

You can either remove the first and last character with input.substr(1, input.length - 1) or just remove them with input.replace("[","").replace("]","") if no other occurrences are possible.

Arrays.stream(str_array).collect(Collectors.joining(","));
this produces desired result without need of 'post processing'

Related

Converting EditText Value to int

My program sets a numeric value to an editText field..I am trying to convert the edittext values to an integer..I have failed in all the attempts i have tried..Here is how the editText field receives the value:
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
DogExpenditure dogExpenditure = postSnapshot.getValue(DogExpenditure.class);
totalAmount[0] += dogExpenditure.getAmount();
textView3.setText(Integer.toString(totalAmount[0] ));
}
}
textView3.setText(Integer.toString(totalAmount[0] I am doing this because the totalAmount[0] cannot be accessed anywhere else other than inside that program so i decided to pull it from the editText(not sure about this) though i havent succeeded. i get java.lang.NumberFormatException: Invalid int: "" error:
Here is how i tried :
String diff = String.valueOf(textView3.getText());
Integer x = Integer.valueOf(diff);
String saley = String.valueOf(textView5.getText());
Integer v = Integer.valueOf(saley);
NB: the textView5 and textView5 are both EditText fields..
A NumberFormatException tell you the String is not a number.
Here, the String is empty so this can't be parse. A solution would be to check for that specific value, like Jesse Hoobergs answer.
But this will not prevent an exception if I input foobar. So the safer solution is to catch the exception. I let you find the correct solution to manager the value if this is not a numerical value.
Integer number;
try{
number = Integer.valueOf(s);
} catch(NumberFormatException nfe){
number = null; //Just an example of default value
// If you don't manage it with a default value, you need to throw an exception to stop here.
}
...
At startup, the value of the editText seems to be an empty string ("").
I think you can best check for empty strings or make sure the initial value isn't an empty string.
String diff = String.valueOf(textView3.getText());
Integer x = null;
if(!diff.trim().isEmpty())
x = Integer.valueOf(diff);
an example that may help you
boolean validInput = true;
String theString = String.valueOf(textView3.getText());
if (!theString.isEmpty()){ // if there is an input
for(int i = 0; i < theString.length(); i++){ // check for any non-digit
char c = theString.charAt(i);
if((c<48 || c>57)){ // if any non-digit found (ASCII chars values for [0-9] are [48-57]
validInput=false;
}
}
}
else {validInput=false;}
if (validInput){// if the input consists of integers only and it's not empty
int x = Integer.parseInt(theString); // it's safe, take the input
// do some work
}
Ok i found out a better way to deal with this..On startup the values are null..so i created another method that handles the edittext fields with a button click after the activity has been initialised..and it works..
private void diffe() {
String theString = String.valueOf(textView3.getText().toString().trim());
String theStringe = String.valueOf(textView5.getText().toString().trim());
int e = Integer.valueOf(theString);
int s = Integer.valueOf(theStringe);
int p = s - e ;
textView2.setText(Integer.toString(p));
}

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

How can I create a string from the parent string from some int position in parent string?

Ok let me give an example:
String parentString = "HelloThisIsAString";
int stringPos = parentString.indexOf("String"); //Will return the position of the text "String" of the parentString.
String string = //Here the problem arises.
In python I do it like this:
string = parentString[stringPos:#to some certain text]
How to do it in Java.
You can use substring method, like this:
String parentString = "HelloThisIsAString";
int stringPos = parentString.indexOf("String");
String string = parentString.substring(stringPos, toSomePos);
// ^^^
// |
// This is optional
Dropping the last parameter gives you a substring from the specific position to the end of the original string.

Java Map Matching Key

i am facing a problem which is:
I have map containing string and string. When i print that map i can see that there is a key
"0-8166-3835-7". But when i am trying to get it, there is nothing to get returned, like no matching found...
My code:
//Open a stream to read from file with isbn's AND titles
Scanner IsbnTitle = new Scanner(new FileReader("C:/Users/Proskopos/Documents/NetBeansProjects/ReadUrl/IsbnTitle.txt"));
//Create a Map to save both ISBN's and Titles
Map <String,String> IsbnTitleMap = new HashMap();
while(IsbnTitle.hasNext()){
String recordIsbnTitle = IsbnTitle.nextLine();
UrlFunctions.AddToMap(Recognised , recordIsbnTitle, IsbnTitleMap);
}
.....
.....
Set IsbnSet = new HashSet();
while (IsbnFile.hasNextLine()) {
String isbn = IsbnFile.nextLine();
IsbnSet.add(isbn);
}
//Create an Iterator for IsbnSet
Iterator IsbnIt =IsbnSet.iterator();
String suffix = IsbnIt.next().toString();
String OPACIALtitle = UrlFunctions.GetOpacTitle(suffix, IsbnTitleMap);
The code above is the only part in main about MAP and below are the functions i call:
static String GetOpacTitle(String opIsbn, Map IsbnTitle) {
String OpacTitle = null;
String isbn = opIsbn;
Map isbnMap = IsbnTitle;
System.out.println(isbn);
if ( isbnMap.containsKey(isbn)){
System.out.println("AAAAAAAAAAAAAAAA");
}
//String tade = isbnMap.get(isbn).toString();
//System.out.println("*************" + tade);
return OpacTitle;
}
static void AddToMap(int Recognise, String recordIsbnfollowed, Map IsbnfollowedMap) {
Map isbnsth = IsbnfollowedMap;
String records = recordIsbnfollowed;
int recs= Recognise;
if (recs == 0 || recs == 3) {
String isbn = records.substring(0, 10);
String title = records.substring(10);
isbnsth.put(isbn, title);
// System.out.println(isbn);
}else if (recs == 1) {
String isbn = records.substring(0, 14);
String title = records.substring(14);
isbnsth.put(isbn, title);
// System.out.println(isbn);
}
}
I cant understand where the problem is.. Maybe it is something like encoding of the suffix cames from a set, and the key from a map? they are both string.. dont think so..!!!
So? Can you help?
EDIT: I am trully sorry if you find the code difficult to read :\ I will follow your advices!!
BUT in case that anyone else has the same problem the solution was what Brand said below.. (I re-post it)
You probably have some whitespace in the Strings that you are reading form the file and storing in the Map. If this is the case use String.trim() before storing the value in the Map, and also before querying for the same string. – Brad 3 hours ago
Thank you all
Just to add to my comment that identified the problem. When comparing Keys in a Map you must be very careful about white space and case sensitivity. These types of issues commonly occure when reading data from Files because it's not always obvious what characters are being read. Even looking in your debugger whitepsace cna be an issue.
Always try to "normalize" your data by trimming leading and trailing whitespace before storing it in a Map.

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