const order = ['margherita', 'pepperoni'];
var total = 0.0;
for (var item in order) {
final price = pizzaPrices[item];
if (price != null) {
total += price;
} else {
print('$item pizza is not on the menu');
}
}
print('Total: \$$total');
Here final variable is accessed twice, one is final price = 'margherita' and another one is price = 'pepperoni'....why it is not showing an error as the final price variable is accessed twice.....but the below code is showing the error...
var item = 'margherita';
final price = pizzaPrices[item];
item = 'pepperoni';
price = pizzaPrices[item];
print(price);
here it is showing error cause final variable price is accessed twice by dartpad
in the first example, you are defining a final variable once in the block. in every iteration, it removes and reinitializes the variables. so you are changing it only once. but in the second example, you are changing a variable twice in a block. so you will get an error.
Related
I wanted to delete the last occurrence of a function name in a calculator edittext with one click.
I already have a delete button, which looks like this:
private void onDelete() {
final Editable formulaText = mFormulaEditText.getEditableText();
final int formulaLength = formulaText.length();
if (formulaLength > 0) {
formulaText.delete(formulaLength - 1, formulaLength);
}
}
I tried to get the last 3 character than if it equals with the function name, delete 3 letters, but the problem is that there are some longer (e.g.: atanh) or shorter function names (e.g.: ln).
P. S. Sorry for my English.
You could use a regular expression:
private static String removeLastMathFunction(String input) {
final String mathFnRegex = "(ln|log|a?(sin|cos|tan)h?)";
final String lastMathFnRegex = mathFnRegex + "(?!.*" + mathFnRegex + ")";
return input.replaceAll(lastMathFnRegex, "");
}
private void onDelete() {
String oldInputValue = mFormulaEditText.getText().toString();
String newInputValue = removeLastMathFunction(oldInputValue);
mFormulaEditText.setText(newInputValue);
}
To make it simple, I have this model:
#Table(name = "Items")
class TItem extends Model {
#Column(name = "title")
private String mTitle;
public String getTitle() { return mTitle; }
public void setTitle(String title) { mTitle = title; }
}
And I'm failing in my testings doing that:
//Create new object and save it to DDBB
TItem r = new TItem();
r.save();
TItem saved = new Select().from(TItem.class).where("id=?", r.getId()).executeSingle();
//Value for saved.getTitle() = null --> OK
r.setTitle("Hello");
r.save();
saved = new Select().from(TItem.class).where("id=?", r.getId()).executeSingle();
//Value for saved.getTitle() = "Hello" --> OK
r.setTitle(null);
r.save();
saved = new Select().from(TItem.class).where("id=?", r.getId()).executeSingle();
//Value for saved.getTitle() = "Hello" --> FAIL
It seems I cannot change a column value from anything to null in ActiveAndroid. Very strange. Is it a bug? I didn't find anything about it, but looks pretty basic this functionallity.
If I debug the app and follow the saving method, the last command it reaches is in SQLLiteConnection.java:
private void bindArguments(PreparedStatement statement, Object[] bindArgs) {
....
// It seems ok, as it is really inserting a null value in the DDBB
case Cursor.FIELD_TYPE_NULL:
nativeBindNull(mConnectionPtr, statementPtr, i + 1);
....
}
I cannot see further, as "nativeBindNull" is not available
Finally I found what happened, and the problem is in ActiveAndroid library.
The null value is saved propertly to DDBB, but is not retrieved correctly. As ActiveAndroid uses cached items, when getting an element, it gets an "old version" and updates it with the new values. Here is where the library fails, because is checking that if not null replace the value, otherwise, nothing.
To solve this, we'll have to change it from the library, in the class Model.java:
public final void loadFromCursor(Cursor cursor) {
List<String> columnsOrdered = new ArrayList<String>(Arrays.asList(cursor.getColumnNames()));
for (Field field : mTableInfo.getFields()) {
final String fieldName = mTableInfo.getColumnName(field);
Class<?> fieldType = field.getType();
final int columnIndex = columnsOrdered.indexOf(fieldName);
....
if (columnIsNull) {
<strike>field = null;</strike> //Don't put the field to null, otherwise we won't be able to change its content
value = null;
}
....
<strike>if (value != null)</strike> { //Remove this check, to always set the value
field.set(this, value);
}
....
}
....
}
I am getting an unusual result when attempting to place a value in an array.
I have an array table[] of a simple class result{ int score, long time, string ID}
Intention is to have a sort of leader board.
My code happily finds the correct place to insert a new score if it is in the top 10.
int ix = 0;
int jx = 10; //
while ( ix < jx )
{
if (points > sTable[ix].points)
{
// score is higher move records down
for (jx = mNumRecords - 1; jx >ix ; jx--)
{
sTable[jx] = sTable[jx -1];
}
//now add new score
sTable[ix].score = score; // all good until here
sTable[ix].time = time;
}
ix++;
}
Problem is that when I try to insert the score using sTable[ix].score = score;
The value gets written to sTable[ix].score and also sTable[ix +1].score.
It is repeatable, it occurs at any value of ix, I have single stepped through the code and as far as I can tell the command only executes once.
Has anyone seen this before?
That because you copied the object reference to the next element in the array. You should copy the values, or create a new object:
Option A:
// score is higher move records down
for (jx = mNumRecords - 1; jx >ix ; jx--)
{
sTable[jx].time = sTable[jx -1].time;
sTable[jx].score = sTable[jx -1].score;
}
//now add new score
sTable[ix].score = score; // all good until here
sTable[ix].time = time;
Option B:
for (jx = mNumRecords - 1; jx >ix ; jx--)
{
sTable[jx] = sTable[jx -1];
}
sTable[ix] = new Result(score, time, ""); // Or however you construct the object
I'm working on code that takes two arrays with strings (the strings are just sentences) and allocates them to classes which are held in another array (The Sentence class array shown below in the code).
So here's my problem. When popList() is called, the for loop runs through twice and works fine, putting the first index of addStrings and addTranslation into the first class in the array. However, when the loop indexes up and runs temp.sentence = addStrings[1] again, it OVERRIDES the first class's .sentence also. Then when temp.translations = addTranslations[1] runs again it OVERRIDES the first class's .translation.
So by the end of the loop, all of the arrays are filled with the same thing: the last index of addStrings and addTranslation. Every time it loops it overwrites all the indices before it with the index it's supposed to be putting in.
Anyone know what the problem is here? Thanks!
public class Sentence {
public String sentence;
public String translation;
Sentence() {
sentence = " ";
translation = " ";
}
}
private void popStrings() {
addStrings[0] = "我是你的朋友。"; addTranslations[0] = "I am your friend.";
addStrings[1] = "你可以帮助我吗?"; addTranslations[1] = "Could you help me?";
addStrings[2] = "我不想吃啊!"; addTranslations[2] = "I don't want to eat!";
}
//Fill Sentence array with string and translation arrays
private void popList() {
int i = 0;
Sentence temp = new Sentence();
for(i = 0; i < addStrings.length && i < addTranslations.length ; i++) {
temp.sentence = addStrings[i];
temp.translation = addTranslations[i];
sentences[i] = temp;
}
}
You need to create new Sentence() inside the loop:
for(i = 0; i < addStrings.length && i < addTranslations.length ; i++) {
Sentence temp = new Sentence();
temp.sentence = addStrings[i];
temp.translation = addTranslations[i];
sentences[i] = temp;
}
Otherwise you set sentence and translation continuously in the same object.
I am having trouble with understanding how to compare strings in Java for Android. I have written code to do this in JavaScript and Palm but am new to Java and am a little confused. Case in point, I am trying to modify the example on the Android Developers site for SpinnerActivity (http://developer.android.com/resources/samples/Spinner/src/com/android/example/spinner/SpinnerActivity.html). In my application I am looking at pipe sizes in the spinner not planets. When the user picks a pipe size I want to reference an array of pipe sizes and be able to pick other parameters associated with that pipe size like the outside diameter (OD) of the pipe. I have modified the above sample code and added and array for the pipe sizes and the OD sizes. I then try to compare what the user picked in the pipe sizes spinner with my pipe sizes array and use the number of the array that matches to pick the associated OD. There is something wrong with the way I am trying to make this comparision. I set both of these values as stings but they never seem to find one another.
HelloSpinner1.java section I have changed is:
public void onItemSelected(AdapterView<?> parent, View v, int pos, long row) {
HelloSpinner1.this.mPos = pos;
HelloSpinner1.this.mSelection = parent.getItemAtPosition(pos).toString();
/*
* Set the value of the text field in the UI
*/
TextView resultText = (TextView)findViewById(R.id.SpinnerResult);
resultText.setText(HelloSpinner1.this.mSelection);
String[] OD; // array of pipe ODs
OD = new String[30]; // allocates memory for 30 floating point numbers
OD[0] = "0.405";
OD[1] = "0.540";
OD[2] = "0.675";
OD[3] = "0.840";
OD[4] = "1.050";
OD[5] = "1.315";
OD[6] = "1.660";
OD[7] = "1.9";
OD[8] = "2.375";
OD[9] = "2.875";
OD[10] = "3.5";
OD[11] = "4";
OD[12] = "4.5";
OD[13] = "5.563";
OD[14] = "6.625";
OD[15] = "8.625";
OD[16] = "10.750";
OD[17] = "12.75";
OD[18] = "14";
OD[19] = "16";
OD[20] = "18";
OD[21] = "20";
OD[22] = "22";
OD[23] = "24";
OD[24] = "26";
OD[25] = "28";
OD[26] = "30";
OD[27] = "32";
OD[28] = "34";
OD[29] = "36";
String [] Size;
Size = new String [30];
Size[0] = "1/8";
Size[1] = "1/4";
Size[2] = "3/8";
Size[3] = "1/2";
Size[4] = "3/4";
Size[5] = "1";
Size[6] = "1-1/4";
Size[7] = "1-1/2";
Size[8] = "2";
Size[9] = "2-1/2";
Size[10] = "3";
Size[11] = "3-1/2";
Size[12] = "4";
Size[13] = "5";
Size[14] = "6";
Size[15] = "8";
Size[16] = "10";
Size[17] = "12";
Size[18] = "14";
Size[19] = "16";
Size[20] = "18";
Size[21] = "20";
Size[22] = "22";
Size[23] = "24";
Size[24] = "26";
Size[25] = "28";
Size[26] = "30";
Size[27] = "32";
Size[28] = "34";
Size[29] = "36";
String ODSize;
for (int i = 0; i <= 29; i++){
if (Size.equals("HelloSpinner1.this.mSelection")) {
ODSize = OD[i];
break;
}
}
}
The associated strings.xml rorm the android site with slight modifications is:
Pipe and Tube
1/8
1/4
3/8
3/4
1
1-1/4
1-1/2
2
2-1/2
3
3-1/2
4
5
6
8
10
12
14
16
18
20
22
24
26
28
30
32
34
36
Select a Pipe Size
Just a quick note, but I see two things here:
1) You have "HelloSpinner1.this.mSelection" in quotes. Inside .equals, that is comparing your variable Size directly to that string ... not the value stored in that object. For example, you're asking: "1/8" ?= "HelloSpinner1.this.mSelection" ... not, "1/8" ?= "1/4" in this case. That might be most of your problem here.
2) You could just use the position of the spinner inside your Listener method. That gives you the position of the selection on the spinner. If you aren't modifying those values, you would already know the index into your array. If you were modifying them, /then/ you could do a string comparison (or concurrently modify your array to keep them up to date).
You might also want to check what you're comparing against once you eliminate the quotes problem. A very simple way to do that would be to declare a String for each value, then run it in the debugger or log the output.
Lastly, as personal preference, I don't like to store long arrays which aren't going to change in the xml file. Just code that up as an array which doesn't have to be interpreted later. That'll give you the array access directly, and speed up execution some.