How to set text of multiple codes in one text view - android

Please have a look at this code and at the bottom is the question. Thanks for your help
int i,fact=1;
String value = edtLCM.getText().toString();
for (i = Integer.parseInt(value); i >= 1; i--) {
fact = fact * i;
if (i > 1) {
String one = i + " x ";
System.out.print(i + " x ");
} else {
System.out.print(i);
String two = String.valueOf(i);
}
}
System.out.println(" = " + fact);
LCMResult.setText("");
I want to set the textview of all the 3 "System.out.println()" in one line. The desired result would be like this(if a user input 4 in the edtLCM): 4x3x2x1 = 24

Use a StringBuilder to put the new strings together instead of using system out.
int i,fact=1;
String value = edtLCM.getText().toString();
StringBuilder sb = new StringBuilder(); // find a better name
for (i = Integer.parseInt(value); i >= 1; i--) {
fact = fact * i;
if (i > 1) {
String one = i + " x ";
// System.out.print(i + " x ");
sb.append(i).append(" x ");
} else {
//System.out.print(i);
sb.append(i);
String two = String.valueOf(i);
}
}
//System.out.println(" = " + fact);
sb.append(" = ").append(fact);
String result = sb.toString(); // will be 4 x 3 x 2 x 1 = 24
LCMResult.setText("");

Related

For loop runs twice the result?

I am new to Android. I am creating a native MobilePOS Android application for printng by using Bluetooth. This is my code:
private void showandadd() {
/*String num="";
num=num+String.valueOf(number);*/
String string1="";
String string2="";
String string3="";
if(num==""){
Toast.makeText(this,"Wrong input!! try again", Toast.LENGTH_LONG).show();
}
if(flag==1) {
getItem(directadd);
if(blankflag!=1) {
int updatedPrice = Integer.parseInt(this.price);
int data = Integer.parseInt(this.num);
if(data==0){
Toast.makeText(this,"Wrong input!! insert different quantity number", Toast.LENGTH_LONG).show();
}else {
int d = updatedPrice * data;
this.price = d + "";
// String str = itemName + " \t" + num + " No" + " \t" + "Rs " + price;
printdetailsnew.add(itemName);
quantitynum.add(num);
amount.add(price);
num = "";
directadd = "";
flag = 0;
blankflag = 0;
}
}
num = "";
directadd = "";
flag = 0;
blankflag = 0;
}else {
getItem(directadd);
if(blankflag!=1) {
//String str = itemName + " \t" + num + " No" + " \t" + "Rs " + price;
printdetailsnew.add(itemName);
quantitynum.add("1");
amount.add(price);
num = "";
}
directadd="";
blankflag=0;
}
for(int i=0;i<printdetailsnew.size();i++){
string1=string1+ printdetailsnew.get(i)+"\t"+"\n";
string2=string2 +"No."+ quantitynum.get(i)+"\t"+"\n";
string3= string3 + amount.get(i)+"\n";
result = printdetailsnew.get(i)+"\t" + "No."+ quantitynum.get(i)+"\t"+ amount.get(i)+"\n";
System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"+result);
}
this.selection.setText(string1);
this.selection2.setText(string2);
this.selection3.setText(string3);
num="";
}
There are 3 strings assigned to result.
I am getting result twice when I am press second item.
when I am select first item getting "Itemname Quantity ampount" format like
Tea 1qty 10rs...when I enter second item output will came first item+first item+second item show like this:
Tea 1qty 10rs
Tea 1qty 10rs
Coffee 1qty 12rs
I want to get result
Tea 1qty 10rs
Coffee 1qty 12rs
like this...please any one can help me
A simple example would be to use one label and append to it each time you add a new item.
Instead of this:
for(int i=0;i<printdetailsnew.size();i++){
string1=string1+ printdetailsnew.get(i)+"\t"+"\n";
string2=string2 +"No."+ quantitynum.get(i)+"\t"+"\n";
string3= string3 + amount.get(i)+"\n";
result = printdetailsnew.get(i)+"\t" + "No."+ quantitynum.get(i)+"\t"+ amount.get(i)+"\n";
System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"+result);
}
this.selection.setText(string1);
this.selection2.setText(string2);
this.selection3.setText(string3);
num="";
Change it to this:
str = this.selection.getText().toString();
str += printdetailsnew.get(i)+"\t" + "No."+ quantitynum.get(i)+"\t"+ amount.get(i)+"\n";
this.selection.setText(str);
num="";

display multiplication table in TextView

I am trying to generate a multiplication table,where the 1st EditText takes the actual number while 2nd EditText takes the actual range of multiplication table. When I run the project , the result is only number * range..
can anyone help me in the loop or code below mentioned Or,any alternatives to display the table in GridLayout or TableLayout rather than TextView.
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_multiplication_table);
number = (EditText)findViewById(R.id.numberTable);
range = (EditText)findViewById(R.id.numberRange);
click = (Button)findViewById(R.id.click);
result = (TextView)findViewById(R.id.display);
final String x = range.getText().toString();
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int a = Integer.parseInt(number.getText().toString());
int b = Integer.parseInt(range.getText().toString());
for(int i = 1 ; i <= 10; i++)
{
for(int j = 1 ; j <= 10; j++)
{
int res = a * b;
result. setText(a +" * " + b + " = " + res);
}
}
return;
}
});
}
}
you are calling setText() for every row, but setText() will reset the text of the TextView, you might want to use append() instead
result.setText("");
int a = Integer.parseInt(number.getText().toString());
int b = Integer.parseInt(range.getText().toString());
for(int i = 1 ; i <= b; i++){
int res = a * i;
result.append(a +" * " + i + " = " + res + "\n");
}
or maybe use StringBuilder
int a = Integer.parseInt(number.getText().toString());
int b = Integer.parseInt(range.getText().toString());
StringBuilder builder = new StringBuilder();
for(int i = 1 ; i <= b; i++){
int res = a * i;
builder.append(a +" * " + i + " = " + res + "\n");
}
result.setText(builder.toString())

Android: Check Array for a number Random

I hope you can help me.
I make a game like 4Pics1Word.
I want to load the Level Randomly, I want a loop which generate a Random number from 0 to 10, and then check if the generated number is the first time loaded.
If yes write it in an array and end the loop.
If the number is not the first time loaded, generate a new random number and check it again until it is not used.
For example this is my code (don´t work right):
Boolean usedImageSet = false;
for (int t = 0; t <= usedImages.length; t++) {
if (usedImageSet == false) {
StringBuilder sb = new StringBuilder();
sb.append(currentQuestion);
String used = sb.toString();
if (usedImages[t] != null) {
System.out.println("usedImage" + t
+ " = not Null, it is" + usedImages[t]);
if (usedImages[t].equals(used)) {
System.out.println("String: "
+ used
+ " found it here: [" + t + "]");
currentQuestion = (int) (Math.random() * 10);
}else {
System.out.println("String: "
+ used + " not found");
}
}
if (usedImages[t] == null) {
usedImages[t] = used;
System.out.println("useddImage[" + t + "]: "
+ usedImages[t]);
System.out.println("usedImage" + t + " is Null, change to"
+ usedImages[t]);
usedImageSet = true;
}
}
}
PS:
Thank you all, I think the solution from Oren is the best
// naive implementation
ArrayList<Integer> list = new ArrayList();
for(int i=0; i<10; i++)
{
list.add(i);
}
Collections.shuffle(list);
// output the generated list
for(int i=0; i<10; i++)
{
System.out.print(list.get(i));
}
But how can I save the list if I close the game?
You would probably be much better off creating a List of the numbers you want and then calling Collections.shuffle() on that list.
// naive implementation
ArrayList<Integer> list = new ArrayList();
for(int i=0; i<10; i++)
{
list.add(i);
}
Collections.shuffle(list);
// output the generated list
for(int i=0; i<10; i++)
{
System.out.print(list.get(i));
}
int oldnumber = 5;
int newnumber = new Random().nextInt(10);
while (newnumber == oldnumber){
newnumber = new Random().nextInt(10);
}

String Equation parser issue

I'm coding a method that solve various kind of equation. Now I want that the method receives a String equation that could be in the forms:
ax^2+bx+c=0
or
*ax^2+c=0*
or
bx+c=0
etc. and the order shouldn't matter.
My problem is: How could I parse the equation according the "x" grade?
The eq could contains more values of the same grade for example 2x^2+4x^2+3x+8=2 (max grade x^3).
My method should assign the a value to double a[] if on the left or on the right of a there is x^2, double b[], if on the left or on the right there is x, and double c[] if there isn't any x variable near the value (and should change the value sign if the therms is after the =).
Convert a String number in a double is simple but I don't know how I could disassemble the input String according the x grade as described.
Tested for -2x + 3x^2 - 2 + 3x = 3 - 2x^2
public Double[] parseEquation(String equation)
{
Log.d(TAG, "equation: " + equation);
// Remove all white spaces
equation = equation.replaceAll("[ ]", "");
// Get the left and right sides of =
String[] sides = equation.split("[=]"); // should be of size 2
boolean leftNegative = false;
boolean rightNegative = false;
if (sides.length != 2)
{
// There is no = or more than one = signs.
}
else
{
// if sides i starts with + remove the +
// if - we remove and put it back later
for (int i = 0; i < 2; i++)
{
if (sides[i].charAt(0) == '+')
{
sides[i] = sides[i].substring(1);
}
}
if (sides[0].charAt(0) == '-')
{
leftNegative = true;
sides[0] = sides[0].substring(1);
}
if (sides[1].charAt(0) == '-')
{
rightNegative = true;
sides[1] = sides[1].substring(1);
}
}
Log.d(TAG, "left side:" + sides[0] + " right side: " + sides[1]);
// Terms without signs need to find out later
String[] leftTerms = sides[0].split("[+-]");
String[] rightTerms = sides[1].split("[+-]");
int length = leftTerms[0].length();
if (leftNegative)
{
leftTerms[0] = "-" + leftTerms[0];
}
// put in the minus sign for the rest of the terms
for (int i = 1; i < leftTerms.length; i++)
{
Log.d(TAG, "length = " + length + " " + sides[0].charAt(length));
if (sides[0].charAt(length) == '-')
{
leftTerms[i] = "-" + leftTerms[i];
length += leftTerms[i].length();
}
else
{
length += leftTerms[i].length() + 1;
}
}
length = rightTerms[0].length();
if (rightNegative)
{
rightTerms[0] = "-" + rightTerms[0];
}
for (int i = 1; i < rightTerms.length; i++)
{
Log.d(TAG, "length = " + length + " " + sides[1].charAt(length));
if (sides[1].charAt(length) == '-')
{
rightTerms[i] = "-" + rightTerms[i];
length += rightTerms[i].length();
}
else
{
length += rightTerms[i].length() + 1;
}
}
// Now we put all the factors and powers in a list
List<ContentValues> leftLists = new ArrayList<ContentValues>();
// left side
for (int i = 0; i < leftTerms.length; i++)
{
Log.d(TAG, "leftTerm: " + leftTerms[i]);
ContentValues contentValues = new ContentValues();
int indexOfX = leftTerms[i].indexOf('x');
if (indexOfX == -1)
{
// no x mean a constant term
contentValues.put("factor", leftTerms[i]);
contentValues.put("power", "0");
}
else
{
int indexOfHat = leftTerms[i].indexOf('^');
if (indexOfHat == -1)
{
// no hat mean power = 1
contentValues.put("power", "1");
String factor = leftTerms[i].substring(0, indexOfX).trim();
contentValues.put("factor", factor);
}
else
{
String power = leftTerms[i].substring(indexOfX + 2).trim();
String factor = leftTerms[i].substring(0, indexOfX).trim();
contentValues.put("factor", factor);
contentValues.put("power", power);
}
}
Log.d(TAG, contentValues.toString());
leftLists.add(contentValues);
}
List<ContentValues> rightLists = new ArrayList<ContentValues>();
for (int i = 0; i < rightTerms.length; i++)
{
Log.d(TAG, "rightTerm: " + rightTerms[i]);
ContentValues contentValues = new ContentValues();
int indexOfX = rightTerms[i].indexOf('x');
if (indexOfX == -1)
{
// no hat mean a constant term
contentValues.put("factor", rightTerms[i]);
contentValues.put("power", "0");
}
else
{
int indexOfHat = rightTerms[i].indexOf('^');
if (indexOfHat == -1)
{
// no hat mean power = 1
contentValues.put("power", "1");
String factor = rightTerms[i].substring(0, indexOfX).trim();
contentValues.put("factor", factor);
}
else
{
String power = rightTerms[i].substring(indexOfX + 2).trim();
String factor = rightTerms[i].substring(0, indexOfX).trim();
contentValues.put("factor", factor);
contentValues.put("power", power);
}
}
Log.d(TAG, contentValues.toString());
rightLists.add(contentValues);
}
// Now add the factors with same powers.
// Suppose we solve for cubic here the end result will be
// 4 terms constant, x, x^2 and x^3
// Declare a double array of dim 4 the first will hold constant
// the second the x factor etc...
// You can allow arbitrary power by looping through the lists and get the max power
Double[] result = new Double[]{0.0, 0.0, 0.0, 0.0};
for (ContentValues c : leftLists)
{
switch (c.getAsInteger("power"))
{
case 0:
//Log.d(TAG, "power = 0, factor = " + c.toString());
result[0] += c.getAsDouble("factor");
break;
case 1:
result[1] += c.getAsDouble("factor");
break;
case 2:
result[2] += c.getAsDouble("factor");
break;
case 3:
result[3] += c.getAsDouble("factor");
break;
}
}
for (ContentValues c : rightLists)
{
switch (c.getAsInteger("power"))
{
case 0:
//Log.d(TAG, "power = 0, factor = " + c.toString());
result[0] -= c.getAsDouble("factor");
break;
case 1:
result[1] -= c.getAsDouble("factor");
break;
case 2:
result[2] -= c.getAsDouble("factor");
break;
case 3:
result[3] -= c.getAsDouble("factor");
break;
}
}
Log.d(TAG, "constant term = " + result[0] + ", x^1 = " + result[1]
+ ", x^2 = " + result[2] + ", x^3 = " + result[3]);
return result;
}
If you weren't limited by Android, I'd suggest using a lexer and parser. These are code generators, so they can work anywhere the base language works, but they tend to produce bloated code. Android might not appreciate that.

JSON remove special characters

I want to do the replication between Android sqlite & MS SQL server.That Time i want to take Tables values from Databse.
This is my JSON
{
"Table1":[
{
"BusinessUnit":"MASS",
"ProductCode":"SLD0201",
"Description":"Lou Difan C.Blue 12"3- Commode",
"Description2":"301 0201"
},
{
"BusinessUnit":"MASS",
"ProductCode":"SLN0502",
"Description":"Lou Napoli I"vory- Cistern",
"Description2":"2011 0502"
},
{
"BusinessUnit":"MASS",
"ProductCode":"LDMBL6H",
"Description":"Dortek Taper Bullet Handle 6"5 serr ",
"Description2":"Taper Bullet Ha"
}
],
"Table2":[
{
"chk":6,
"currentchk":1
}
]
}
In Here JSON Description column value contain "(double quotation) .If we check http://jsonformatter.curiousconcept.com/ , it show error.Its a Invalid JSON.
WCF service I have converted DataSet to JSON. Some table column contain special charters.
I converted like this :
public String ConverTableToJson(DataSet dsDownloadJson,int currentSplit)
{
StringBuilder Sb = new StringBuilder();
String result = "";
int start = 0;
int end =500;
int chk = 0;
int currentChk = currentSplit;
if (dsDownloadJson.Tables.Count > 0)
{
Sb.Append("{");
foreach (DataTable dt in dsDownloadJson.Tables)
{
DataTable dtDownloadJson = dt;
string[] StrDc = new string[dtDownloadJson.Columns.Count];
string HeadStr = string.Empty;
double total = dtDownloadJson.Rows.Count;
Console.WriteLine("--1--" + dtDownloadJson.Rows.Count);
if (dtDownloadJson.Rows.Count < 500)
{
end = dtDownloadJson.Rows.Count;
}
if (chk == 0)
{
if (dtDownloadJson.Rows.Count > 500)
{
if ((dtDownloadJson.Rows.Count / 500) == 0)
{
chk = dtDownloadJson.Rows.Count / 500;
}
else
{
chk = dtDownloadJson.Rows.Count / 500 + 1;
}
}
else
{
chk = 1;
}
currentChk = 1;
}
else
{
currentChk = currentChk + 1;
start = currentChk * 500;
end = start + 500;
currentChk = chk;
}
Sb.Append("\"" + dtDownloadJson.TableName + "1\" : [");
if (dtDownloadJson.Rows.Count > 0)
{
for (int i = 0; i < dtDownloadJson.Columns.Count; i++)
{
StrDc[i] = dtDownloadJson.Columns[i].Caption;
HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\",";
}
if (HeadStr.Length > 0)
{
HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);
Console.WriteLine("--2--" + start);
Console.WriteLine("--3--" + end);
for (int i = start; i < end; i++)
{
string TempStr = HeadStr;
Sb.Append("{");
for (int j = 0; j < dtDownloadJson.Columns.Count; j++)
{
TempStr = TempStr.Replace(dtDownloadJson.Columns[j] + j.ToString() + "¾", dtDownloadJson.Rows[i][j].ToString());
TempStr = TempStr.Replace(""", '\"');
}
Sb.Append(TempStr + "},");
}
Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
}
}
else
{
}
Sb.Append("],");
if (chk > 1)
{
Sb.Append("\"Table2\": [{\"chk\": " + chk + ", \"currentchk\": " + currentChk + " }]");
}
else
{
Sb.Append("\"Table2\": [{\"chk\": " + chk + ", \"currentchk\": " + currentChk + " }]");
}
}
// Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
Sb.Append("}");
return Sb.ToString();
}
else
{
return "0";
}
}
My problem is removing special charters OR How to allow special characters.?
Please help me anybody...
You shouldn't use a StringBuilder to convert an object to a JSON string. Use the JsonConverter class in JayRock JSON library and it takes care of Serialising/Deserialising Json for you (including escaping)
try to use inbuilt json serialization
public static string Serialize<T>(T obj)
{
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new
System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, obj);
string retVal = Encoding.Default.GetString(ms.ToArray());
ms.Dispose();
return retVal;
}

Categories

Resources