Trying to make a calculator, here's the button method when the line with the * is ran it comes up with the error "operator + cannot be applied to java.lang.charsequence". If any one know's a way around this please help.
public void Button_Click(View view) {
TextView result = (TextView) findViewById(R.id.result);
Button b = (Button)view;
if ((result.getText() == "0")||(operation_pressed))
result.setText("");
operation_pressed = false;
if (b.getText() == ".") {
result.getText() = result.getText() + b.getText()); ***
}
}
Thanks
In order to convert a charsequence to a String apply .toString() to the CharSequence Object and you should be fine to use + operators:
[https://docs.oracle.com/javase/7/docs/api/java/lang/CharSequence.html][1]
Also it looks like you have a syntax error:
result.getText() = result.getText() + b.getText()); *** the last ) is too much
Furthermore you cannot write into getText() .. Getters (indicated by getXXX()) should be used to get values while Setters (indicated by setXXX()) should be used to store values into an object.
result.setText(result.getText().toString() + b.getText().toString())
Related
We are trying to correct the spelling of words in a TextArea
We have tried two methods onRemoveTwo failed with an IndexOutOfBoundsException
The other method onRemove works but it does a replaceAll we use replace in our code
Here are the results from both methods
Results from using onRemoveTwo
Initial text Take = Cariage NOT ME Carriag add missing voel to Carriage
Request was to correct "Cariage"
First correction results Take = Carriage NOT ME Carriag add missing voel to Carriage
With sb = sb.replace(from, to);
Request was to correct "Carriag"
Second correction results Take = Carriagee NOT MEg add missing voel to Carriage
We have this error Caused by: java.lang.IndexOutOfBoundsException
Caused by this line of code which we understand
while is finding two occurrence of the word
txaInput.replaceText(match.start(),match.end(),txtReplacementWord.getText());
Results from using onRemove
Initial text Take = Cariage NOT ME Carriag add missing voel to Carriage
Request was to correct "Cariage"
First correction results Take = Carriage NOT ME Carriag add missing voel to Carriage
Request was to correct "Carriag"
Second correction results Take = Carriagee NOT ME Carriage add missing voel to Carriagee
Notice both "Carriage" were changed to "Carriagee"
So our question is how to be more specific about the word to be corrected?
private void onRemoveTwo(){
if(txtReplacementWord.getText().isEmpty()){
txtMessage.setText("No Replacement Word");
return;
}
cboMisspelledWord.getItems().remove(txtWordToReplace.getText());
// Line Above Removes misspelled word from cboSelect
// ==================================================
String text = txaInput.getText();
String wordToFind = txtWordToReplace.getText();
Pattern word = Pattern.compile(wordToFind);
Matcher match = word.matcher(text);
while(match.find()){
///System.out.println("Found "+word+" "+ match.start() +" - "+ (match.end()-1));
String from = word.toString();
String to = txtReplacementWord.getText();
String sb = txaInput.getText();
sb = sb.replace(from, to);
txaInput.replaceText(match.start(),match.end(),txtReplacementWord.getText());
txtMessage.setText("");
txtReplacementWord.setText("");
txtWordToReplace.setText("");
cboCorrectSpelling.getItems().clear();
cboMisspelledWord.requestFocus();
// Code above replaces misspelled word with correct spelling in TextArea
// =====================================================================
int SIZE = cboMisspelledWord.getItems().size();
if(SIZE == 0){
onCheckSpelling();
}
}
}
Workable method but changes multiple words
#FXML
private void onReplace(){
if(txtReplacementWord.getText().isEmpty()){
txtMessage.setText("No Replacement Word");
return;
}
cboMisspelledWord.getItems().remove(txtWordToReplace.getText());
// Line Above Removes misspelled word from cboSelect
// ==================================================
String from = txtWordToReplace.getText();
String to = txtReplacementWord.getText();
String sb = txaInput.getText();
sb = sb.replace(from, to);
//sb = sb.replaceAll(from,to);
txaInput.setText("");
txaInput.setText(sb);
txtMessage.setText("");
txtReplacementWord.setText("");
txtWordToReplace.setText("");
cboCorrectSpelling.getItems().clear();
cboMisspelledWord.requestFocus();
// Code above replaces misspelled word with correct spelling in TextArea
// =====================================================================
int SIZE = cboMisspelledWord.getItems().size();
if(SIZE == 0){
onCheckSpelling();
}
}
Well #Grendel I have no idea why this question is voted down. I have been working on a similar project with a TextArea and liked your code and like you found it frustrating that the StringBuilder finds any occurrence of the characters. So here is an answer the code is not real neat you will need to clean it up. I was unhappy that I had to go to a String[] array then to a ArrayList will keep working on this issue
In spite of the down votes enjoy the code
Send the check to 90.83.140.38
#FXML
private void onReplace(){
if(txtReplacementWord.getText().isEmpty()){
txtMessage.setText("No Replacement Word");
return;
}
cboMisspelledWord.getItems().remove(txtWordToReplace.getText());
// Line Above Removes misspelled word from cboMisspelledWord
// ==========================================================
String line = txaInput.getText();
oneA = line.split("\\s");
List<String> list = new ArrayList<>(Arrays.asList(oneA));
int theIndex = list.indexOf(txtWordToReplace.getText());
String gotME = list.get(theIndex);
list.remove(theIndex);
list.add(theIndex,txtReplacementWord.getText());
sb = new StringBuilder();
for (String addWord : list) {
sb.append(addWord);
sb.append(" ");
}
txaInput.setText(sb.toString());
txtMessage.setText("");
txtReplacementWord.setText("");
txtWordToReplace.setText("");
cboCorrectSpelling.getItems().clear();
cboMisspelledWord.requestFocus();
// Code above replaces misspelled word with correct spelling in TextArea
// =====================================================================
if(cboMisspelledWord.getItems().isEmpty()){
onCheckSpelling();
}
}
Im trying to use Grid Component. I need to define the order of a column, I'm using this proyect:
https://github.com/vaadin/tutorial/tree/v8-step4
And I add this code:
Column name = grid.addColumn(customer -> customer.getFirstName() + " " + customer.getLastName())
.setCaption("Name")
.setSortOrderProvider(direction -> Stream.of(
new QuerySortOrder("lastName", direction)
));
grid.setSortOrder(GridSortOrder.asc(name));
But I'm not getting the expected results, I'm getting ordered by firstName and then by lastName but i need the results ordered by lastName.
Have you had the same problem? How have you solved it?
Thank you.
I digged into the code and found out that you need you need to call setComparator instead of the setSortOrderProvider. The former is intended for in-memory data providers. Unfortunately, it's a little bit confusing and not really well documented.
I use this implementation of setComparator and it's working. : )
Column name = grid.addColumn(customer -> customer.getFirstName() + " " + customer.getLastName())
.setCaption("Name")
.setComparator(new SerializableComparator<Customer>() {
#Override
public int compare(Customer arg0, Customer arg1) {
return arg0.getLastName().compareTo(arg1.getLastName());
}
});
With Lambda:
.setComparator((customer0, customer1) -> {
return customer0.getLastName().compareTo(customer1.getLastName());
});
and this other option:
Column name = grid.addColumn(customer -> customer.getFirstName() + " " + customer.getLastName())
.setCaption("Name")
.setComparator(grid.getColumn("lastName").getComparator(SortDirection.ASCENDING));
So here is my problem. I want to loop through every point of a line chart in HighCharts using Selenium. I figured a way to start from path:nth-of-type(1) to path:last-of-type. However, it goes from right to left and I would love to have it going from left to right (I'm peaky I know).
Thus, if I could find a way to start from last-of-type to nth-of-type(1), I would be very pleased. However, I don't know how to get the equivalent nth-of-type(position) of last-of-type in order to decrease it by 1 every time I loop through it.
Here is the code I have so far (the right to left one):
public static boolean isLastPoint(int series,WebDriver driver){
if(series > 1){
WebElement last = driver.findElement(By.cssSelector("g.highcharts-series-group > g:nth-of-type(2) > path:last-of-type"));
WebElement current = driver.findElement(By.cssSelector("g.highcharts-series-group > g:nth-of-type(2) > path:nth-of-type(" + (series) + ")"));
return last.equals(current);
}
else return false;
}
public static void overview(WebDriver driver, boolean active) {
if(active){
wait(driver,By.id("highcharts-0"));
WebElement chart0 = driver.findElement(By.id("highcharts-0"));
LineChart lc0 = new LineChart(driver,chart0);
int series = 1;
while(!isLastPoint(series-1,driver)){
lc0.hoverOverLineChart1(series, "");
series++;
}
}else return;
}
You can use findElements for this:
int count = driver.findElements(By.cssSelector("g.highcharts-series-group > g:nth-of-type(2) > path:last-of-type")).size();
Then use the count to iterate backwards.
public int AuthenticatedUserAge(String User_name)
{
string sql = "SELECT UserName,Age FROM tblDataProg WHERE (UserName ='" + User_name + "')";
ds = GetDataSet(sql);
int help = int.Parse(ds.Tables[0].Rows[0]["Age"].ToString());
return help;
}
I can't figure why this line doesn't convert the age to type int and return a value:
int help = int.Parse(ds.Tables[0].Rows[0]["Age"].ToString());
Completely offtopic to the question, but I think it's worth mentioning. Please don't create your SQL statements by concatenating strings. This creates SQL Injection attack possibility. Instead consider SqlParameter class and compose your WHERE predicates using such parameters.
Here you get nice example (look especially at convenient AddWithValue method).
Thanks!
Test your assumptions more. You are assuming GetDataSet is returning a row but it possibly isn't: -
int help = 0;
if (ds.Tables[0].Rows.Count == 0)
{
throw new ApplicationException("no rows were returned, here is an error to deal with");
}
else if (ds.Tables[0].Rows[0]["Age"] == System.DbNull.Value)
{
throw new ApplicationException("a row was found but Age is null, here is an error to deal with");
}
else
{
help = int.Parse(ds.Tables[0].Rows[0]["Age"].ToString());
}
try
int help;
int.TryParse(Convert.ToString(ds.Tables[0].Rows[0]["Age"]),out help);
and see the code in debug mode
Look please below this codes throw me : FormatException was unhandled by user code
Codes:
satis.KDV = Decimal.Parse((from o in genSatisctx.Urun where o.ID == UrunID select o.Kdv).ToString());
How can i rewrite linq query?
You are calling ToString on the query rather than a single result. Even though you may expect only one value to match your query, it will not return just a single value. You have to instruct it to do so using Single, First, Last or the variations of these that also return a default value (SingleOrDefault, FirstOrDefault, LastOrDefault).
In order to avoid an exception, you could change it to use Decimal.TryParse or you could change your code to use a default value if the LINQ query returns something that won't parse properly. I'd recommend the former or a combination.
Note that in the following example, I have added the call to SingleOrDefault. This ensures that only one value is parsed, even if no value is found, and that if there are multiple results, we get an exception (i.e. it enforces that we get exactly zero or one result to the query).
decimal parsedValue;
if (Decimal.TryParse(
genSatisctx
.Urun
.Where(o => o.ID == UrunID)
.Select(o=>o.Kdv)
.SingleOrDefault()
.ToString(), out parsedValue))
{
satis.KDV = parsedValue;
}
You're calling ToString() on an IQueryable<T> - what did you expect the string to be? It's very unlikely to be anything which can be parsed as a decimal number!
My guess is that you want to call First() or Single(), but we can't really tell without more information. What's the type of o.Kdv?
I suspect you either want:
satis.KDV = (from o in genSatisctx.Urun
where o.ID == UrunID
select o.Kdv).First();
or
string kdvString = (from o in genSatisctx.Urun
where o.ID == UrunID
select o.Kdv).First();
decimal kdv;
if (decimal.TryParse(kdvString, out kdv))
{
satis.KDV = kdv;
}
else
{
// What do you want to do if it's not valid?
}
When I use debug mode I see the data is update when over mouse, after end of this method ( it's show this message [input string was not in a correct format]
/* protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
TextBox name = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditName");
SqlDataSource2.UpdateParameters["Name"].DefaultValue = name.ToString();
TextBox age = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditAge");
SqlDataSource2.UpdateParameters["Age"].DefaultValue = age.ToString();
TextBox birthday = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditBirthday");
SqlDataSource2.UpdateParameters["Birthday"].DefaultValue = birthday.ToString();
DropDownList country = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("DropEditCountry");
SqlDataSource2.UpdateParameters["CountryID"].DefaultValue = country.SelectedValue;
TextBox mobile = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditMobile");
SqlDataSource2.UpdateParameters["Mobile_No"].DefaultValue = mobile.ToString();
SqlDataSource2.Update();
}
catch (Exception j)
{
j.Message.ToString();
}
}
/* }