I want to count the characters in a string and if the counter reach a limit puts a line break. But I don't know how to solve.
I found that word counter, but how to add a break to specific places?e.g after each 4th word.
public static int countWords(String s){
int wordCount = 0;
boolean word = false;
int endOfLine = s.length() - 1;
for (int i = 0; i < s.length(); i++) {
// if the char is a letter, word = true.
if (Character.isLetter(s.charAt(i)) && i != endOfLine) {
word = true;
// if char isn't a letter and there have been letters before,
// counter goes up.
} else if (!Character.isLetter(s.charAt(i)) && word) {
wordCount++;
word = false;
// last word of String; if it doesn't end with a non letter, it
// wouldn't count without this.
} else if (Character.isLetter(s.charAt(i)) && i == endOfLine) {
wordCount++;
}
}
return wordCount;
}
Related
I can pause and resume in text to speech by using below code but onRangeStart() values are discarded, i am highlighting text also while tts is speaking however when i resume, then onRangeStart() values fall back to 0th index.
HOW can i save onRangeStart() values?
int index;
int start;
int end;
String text;
String alltext;
public void getReady() {
alltext = main_input.getText().toString() ;
alltextlen = alltext.length();
list.clear();
int i;
int i2 = 0;
while(true) {
i = alltextlen;
if(i2 >= i - 1) {
break;
}
String s = Character.toString().alltext.charAt(i2);
if(s.equals(".") {
list.add(i2);
i2++;
}
list.add(i - 1);
start = maininput.getSelectionStart();
while(i3 < list.size()) {
if(list.get(i3) >= start) {
index = i3;
break;
}
speak();
}
private void speak() {
if(index < list.size()) {
end = list.get(index) + 1;
text = allText.substring(start, end);
start = end;
texttospeech.speak(text, 0, null, "tts");
}
}
I want to show the number in this xx-xxx-xxx-xxx-x format on EditText.
Eg (01-140-176-515-4)
I tried modifying the below code which displays the number in credit card number format
(xxxx-xxxx-xxxx-xxxx)
et_cardnumber.addTextChangedListener(new TextWatcher() {
private static final int TOTAL_SYMBOLS = 19; // size of pattern 0000-0000-0000-0000
private static final int TOTAL_DIGITS = 16; // max numbers of digits in pattern: 0000 x 4
private static final int DIVIDER_MODULO = 5; // means divider position is every 5th symbol beginning with 1
private static final int DIVIDER_POSITION = DIVIDER_MODULO - 1; // means divider position is every 4th symbol beginning with 0
private static final char DIVIDER = '-';
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// noop
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
iv_cardtype.setImageResource(getCreditCardTypeForImageView(et_cardnumber.getText().toString()));
}
#Override
public void afterTextChanged(Editable s) {
if (!isInputCorrect(s, TOTAL_SYMBOLS, DIVIDER_MODULO, DIVIDER)) {
s.replace(0, s.length(), buildCorrecntString(getDigitArray(s, TOTAL_DIGITS), DIVIDER_POSITION, DIVIDER));
}
}
private boolean isInputCorrect(Editable s, int totalSymbols, int dividerModulo, char divider) {
boolean isCorrect = s.length() <= totalSymbols; // check size of entered string
for (int i = 0; i < s.length(); i++) { // chech that every element is right
if (i > 0 && (i + 1) % dividerModulo == 0) {
isCorrect &= divider == s.charAt(i);
} else {
isCorrect &= Character.isDigit(s.charAt(i));
}
}
return isCorrect;
}
private String buildCorrecntString(char[] digits, int dividerPosition, char divider) {
final StringBuilder formatted = new StringBuilder();
for (int i = 0; i < digits.length; i++) {
if (digits[i] != 0) {
formatted.append(digits[i]);
if ((i > 0) && (i < (digits.length - 1)) && (((i + 1) % dividerPosition) == 0)) {
formatted.append(divider);
}
}
}
return formatted.toString();
}
private char[] getDigitArray(final Editable s, final int size) {
char[] digits = new char[size];
int index = 0;
for (int i = 0; i < s.length() && index < size; i++) {
char current = s.charAt(i);
if (Character.isDigit(current)) {
digits[index] = current;
index++;
}
}
return digits;
}
});
I couldn't get it right when i make changes to get the format which i want.
Can anyone help me to get the number in xx-xxx-xxx-xxx-x format?
i dont know much in Android , but try to build something like this .
str Yourstring = "";
for (int i = 0; i < digits.length; i++) {
if (i == 2 || i == 5 || i == 8 || i == 11) {
Yourstring = Yourstring + "-" +digits[i];
}
else
{
Yourstring = Yourstring +digits[i];
}
}
I answered this already in this link , please change the logic according to your format
Use this library.
it will allow according yo your formate
EditText Pattern lib
I am making an android dictionary Vietnam - English (over 20,000 entries).
In my application contain edittext and Listview.
To search item in my listview, i use Binary Search.
But the problem is with the search method and Vietnamese, it doesn't search well
some words it can find, some it can't.
Following is my search code to find word by prefix when edittext change.
public void searchWords(String[] words, String prefix)
{
int first = 0, last = words.length - 1;
int mid = 0;
while (first <= last)
{
mid = (first + last) / 2;
int c = prefix.compareTo(words[mid]);
if (c == 0)
{
first = mid; // first indicates the beginning
break;
}
if (c > 0)
first = mid + 1;
else
last = mid - 1;
}
int i;
for (i = first; i < words.length; i++)
{
if (words[i].startsWith(prefix))
{
pos=i;
break;
}
}
lv.setSelection(pos);
// Toast.makeText(getApplicationContext(), ""+pos,Toast.LENGTH_SHORT).show();
}
and onTextchange code i call my method like this:
public void onTextChanged(CharSequence s, int start, int before, int count){
// TODO Auto-generated method stub
searchWords(w,s.toString());
}
and this is how i load my entries from database to array:
d=handle.retrieve();
if(d.moveToFirst())
{
do
{
w[ii++]=d.getString(1);
}while(d.moveToNext());
}
So, what should i do to make my search working correctly?
Binary Search with "compareTo()" works only with SORTED words (or sorted Strings, i.e. sorted in alphabetic sequence -regardless of language). Meaning: Array starts with A, AA, AAA,... and ends with z, zz, zzz...Btw, UPPER case before lower case. Example:
String[] seq = {"Ape", "Bird", "Donkey", "Eagle", "Fish", "Gnu", "Horse", "Koala"};
String[] ran = {"Gnu", "Koala", "Horse", "Fish", "Bird", "Donkey", "Eagle", "Ape"};
String[] queries = {"Eagle", "Bird", "Donkey", "Fish", "Ape", "Horse", "Eagle", "Gnu"};
// binarySearch with random[] will produce unpredictable results when prefix starts with
// a word that is either after "Bird" or "Ape" or "Gnu"
for (String s : queries) {
System.out.println("Random: BS for " + s + " = " + binarySearch(ran, s));
}
//
// binarySearch with sequence[] will produce correct results whatever prefix is.
for (String s : queries) {
System.out.println("Sequence: BS for " + s + " = " + binarySearch(seq, s));
}
//-------------------------------------------------------------------------
public static int binarySearch(String[] words, String value) {
return binarySearch(words, value, 0, words.length - 1);
}
//
public static int binarySearch(String[] words, String value, int min, int max) {
if (min > max) {
return -1;
}
int mid = (max + min) / 2;
if (words[mid].equals(value)) return mid;
if(words[mid].compareTo(value) > 0)
return binarySearch(words, value, min, mid - 1);
return binarySearch(words, value, mid + 1, max);
}
In my application i want to check whether the user have entered valid card number for that i have used LUHN algorithm.I have created it as method and called in the mainactivity. But even if i give valid card number it shows invalid.While entering card number i have given spaces in between i didn't know because of that its not validating properly. Please help me in finding the mistake.
CreditcardValidation.java
public class CreditcardValidation {
String creditcard_validation,msg;
//String mobilepattern;
public static boolean isValid(long number) {
int total = sumOfDoubleEvenPlace(number) + sumOfOddPlace(number);
if ((total % 10 == 0) && (prefixMatched(number, 1) == true) && (getSize(number)>=16 ) && (getSize(number)<=19 )) {
return true;
} else {
return false;
}
}
public static int getDigit(int number) {
if (number <= 9) {
return number;
} else {
int firstDigit = number % 10;
int secondDigit = (int) (number / 10);
return firstDigit + secondDigit;
}
}
public static int sumOfOddPlace(long number) {
int result = 0;
while (number > 0) {
result += (int) (number % 10);
number = number / 100;
}
return result;
}
public static int sumOfDoubleEvenPlace(long number) {
int result = 0;
long temp = 0;
while (number > 0) {
temp = number % 100;
result += getDigit((int) (temp / 10) * 2);
number = number / 100;
}
return result;
}
public static boolean prefixMatched(long number, int d) {
if ((getPrefix(number, d) == 5)
|| (getPrefix(number, d) == 4)
|| (getPrefix(number, d) == 3)) {
if (getPrefix(number, d) == 4) {
System.out.println("\nVisa Card ");
} else if (getPrefix(number, d) == 5) {
System.out.println("\nMaster Card ");
} else if (getPrefix(number, d) == 3) {
System.out.println("\nAmerican Express Card ");
}
return true;
} else {
return false;
}
}
public static int getSize(long d) {
int count = 0;
while (d > 0) {
d = d / 10;
count++;
}
return count;
}
public static long getPrefix(long number, int k) {
if (getSize(number) < k) {
return number;
} else {
int size = (int) getSize(number);
for (int i = 0; i < (size - k); i++) {
number = number / 10;
}
return number;
}
}
public String creditcardvalidation(String creditcard)
{
Scanner sc = new Scanner(System.in);
this.creditcard_validation= creditcard;
long input = 0;
input = sc.nextLong();
//long input = sc.nextLong();
if (isValid(input) == true) {
Log.d("Please fill all the column","valid");
msg="Valid card number";
}
else{
Log.d("Please fill all the column","invalid");
msg="Please enter the valid card number";
}
return msg;
}
}
MainActivity.java
addcard.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
if(v.getId()==R.id.btn_add)
{
creditcard= card_number.getText().toString();
cv = new CreditcardValidation();
String mob = cv.creditcardvalidation(creditcard);
Toast.makeText(getActivity(), mob, 1000).show();``
refer code below
EditText cardNumber=(EditText)findViewById(R.id.cardNumber);
String CreditCardType = "Unknown";
/// Remove all spaces and dashes from the passed string
String CardNo ="9292304336";///////cardNumber.getText().toString();
CardNo = CardNo.replace(" ", "");//removing empty space
CardNo = CardNo.replace("-", "");//removing '-'
twoDigit=Integer.parseInt(CardNo.substring(0, 2));
System.out.println("----------twoDigit--"+twoDigit);
fourDigit=Integer.parseInt(CardNo.substring(0, 4));
System.out.println("----------fourDigit--"+fourDigit);
oneDigit=Integer.parseInt(Character.toString(CardNo.charAt(0)));
System.out.println("----------oneDigit--"+oneDigit);
boolean cardValidation=false;
// 'Check that the minimum length of the string isn't <14 characters and -is- numeric
if(CardNo.length()>=14)
{
cardValidation=cardValidationMethod(CardNo);
}
boolean cardValidationMethod(String CardNo)
{
//'Check the first two digits first,for AmericanExpress
if(CardNo.length()==15 && (twoDigit==34 || twoDigit==37))
return true;
else
//'Check the first two digits first,for MasterCard
if(CardNo.length()==16 && twoDigit>=51 && twoDigit<=55)
return true;
else
//'None of the above - so check the 'first four digits collectively
if(CardNo.length()==16 && fourDigit==6011)//for DiscoverCard
return true;
else
if(CardNo.length()==16 || CardNo.length()==13 && oneDigit==4)//for VISA
return true;
else
return false;
}
also u can refer this demo project
Scanner.nextLong() will stop reading as spaces (or other non-digit characters) are encountered.
For instance, if the input is 1234 567 .. then nextLong() will only read 1234.
However, while spaces in the credit-card will [likely] cause it to fail LUHN validation with the above code, I make no guarantee that removing the spaces would make it pass - I'd use a more robust (and well-tested) implementation from the start. There is no need to rewrite such code.
Android 2.3.3
I have written a program for calculating the LCM for more than 2 numbers, and it worked for me. I thought of sharing it, so that it might come in handy for those who are looking for it. This may not be the best solution, but, i did it according to my requirement. You can modify it to your need.
I have hard coded the input, and also my program uses ArrayLists to do the operations. You might want to change these.
Pre-Requisites ::: 1. Calculation of PrimeNumbers for the range of inputs.
public class PlusMinusActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
EditText edtxtExpression;
Button btnLCM, btnGCD;
ArrayList<String> alPrimes = new ArrayList<String>(); // Contains List of Prime Numbers
ArrayList<String> alNumbers = new ArrayList<String>(); // Contains the input => Numbers for which LCM is to be determined
ArrayList<String> alResult = new ArrayList<String>(); // Contains the numbers that make up the LCM
String strExp = ""; // Temporary String to display the result
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edtxtExpression = (EditText)findViewById(R.id.edtxtExpression);
btnLCM = (Button)findViewById(R.id.btnLCM);
btnGCD = (Button) findViewById(R.id.btnGCD);
btnLCM.setOnClickListener(this);
btnGCD.setOnClickListener(this);
addData();
strExp = alNumbers.toString();
System.out.println("strExp Value is ::: "+strExp);
}
private void addData() {
// TODO Auto-generated method stub
//alPrimes.add(String.valueOf(1));
alPrimes.add(String.valueOf(2));
alPrimes.add(String.valueOf(3));
alPrimes.add(String.valueOf(5));
alPrimes.add(String.valueOf(7));
alPrimes.add(String.valueOf(9));
alPrimes.add(String.valueOf(11));
alPrimes.add(String.valueOf(13));
alPrimes.add(String.valueOf(17));
alPrimes.add(String.valueOf(19));
alPrimes.add(String.valueOf(23));
alPrimes.add(String.valueOf(29));
alNumbers.add(String.valueOf(1));
alNumbers.add(String.valueOf(5));
alNumbers.add(String.valueOf(7));
alNumbers.add(String.valueOf(9));
System.out.println("alPrimes ::: "+alPrimes.toString());
System.out.println("alNumbers ::: "+alNumbers.toString());
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btnLCM:
calculateLCM();
break;
case R.id.btnGCD:
calculateGCD();
break;
default:
break;
}
}
// Calculates LCM
private void calculateLCM() {
// TODO Auto-generated method stub
int i=0, count=0;
while(i < alPrimes.size())
{
count = 0;
int p = Integer.parseInt(alPrimes.get(i)); // Getting the element from PrimeNumbers List
System.out.println("Prime Number ::: "+p);
int j=0;
while(j < alNumbers.size())
{
int n = Integer.parseInt(alNumbers.get(j)); // Getting the number from Input List
System.out.println("Number ::: "+n);
if(n % p == 0 && n != 1)
{
count++; // Counts the number of integers that gets divided (% = 0) by that particular prime number
System.out.println("Count :::"+count);
}
j++;
}
if(count >= 2) // If two or more numbers, gets divided, then we do the division
{
alResult.add(String.valueOf(p)); // adding the prime number to Result list
System.out.println("Result ::: "+alResult.toString());
j=0;
while(j < alNumbers.size())
{
int n = Integer.parseInt(alNumbers.get(j));
System.out.println("Number ::: "+n);
if(n % p == 0)
{
int result = n/p;
System.out.println("Temp Result ::: "+result);
alNumbers.remove(j); // Replace the element by the result
System.out.println("After Removing ::: "+alNumbers.toString());
alNumbers.add(j, String.valueOf(result));
System.out.println("After Adding ::: "+alNumbers.toString());
}
j++;
}
i = -1; // iterate the Input list from the start
}
else if(count == 0 || count == 1)
{
boolean allPrimes = checkAllPrimes();
if(allPrimes)
{
break;
}
}
i++;
}
calculateResult();
}
// Calculates the result
private void calculateResult() {
// TODO Auto-generated method stub
int i=0;
while(i < alNumbers.size())
{
alResult.add(alNumbers.get(i));
i++;
}
int result = 1;
i=0;
while(i < alResult.size())
{
result *= Integer.parseInt(alResult.get(i));
i++;
}
edtxtExpression.setText("LCM of "+strExp+" is ::: "+result);
}
// Checks whether the elements in the ArrayList are all prime numbers
// returns true if all are prime
//
private boolean checkAllPrimes() {
// TODO Auto-generated method stub
int i=0;
boolean areAllPrimes = true;
while(i < alNumbers.size())
{
int n = Integer.parseInt(alNumbers.get(i));
if(! (alPrimes.contains(n) || n == 1))
{
areAllPrimes = false;
break;
}
i++;
}
return areAllPrimes;
}
private void calculateGCD() {
// TODO Auto-generated method stub
}
}
For the following input :::
alNumbers.add(String.valueOf(10));
alNumbers.add(String.valueOf(15));
alNumbers.add(String.valueOf(20));
alNumbers.add(String.valueOf(25));
For the following input :::
alNumbers.add(String.valueOf(10));
alNumbers.add(String.valueOf(15));
alNumbers.add(String.valueOf(20));
alNumbers.add(String.valueOf(25));
alNumbers.add(String.valueOf(110));
alNumbers.add(String.valueOf(130));
I am very new to Android and Java as well. So, if this is not a good solution, please don't mind.
Hope it helps...
You could probaly simplify your code using this idea:
static int ggt(int a, int b)
{
if (b == 0)
return a;
return ggt(b, a % b);
}
static void Main(string[] args)
{
int lcm = 1;
foreach(int x in new int[] { 1,5,7,9 })
lcm = x * lcm / ggt(x, lcm);
Console.WriteLine("{0}", lcm);
}
Syntax is c#, but hopefully readable enough. 'ggt' ist the german abbrevation for 'gcd' (greatest common divisor)
//LCM of range of numbers using JAVA
n=s.nextInt();//Reading range value
for(i=0;i<n;i++)
{
a[i]=s.nextInt(); //reading list of numbers
}
Arrays.sort(a,0,n); //Sorting the numbers
k=a[n-1]; //Assigning biggest value in the sorted array to k
j=1;
l=k;
for(i=0;i<n;i++)
{
if(k%a[i]==0)
{
continue; //checking whether all the elements are divisible by k
}
else
{
j=j+1;
k=l*j;//multiples of highest element i.e k in the sorted array
i=-1;//Assigning -1 to i, so as to check whether all the elements
//in the array are divisible by k or not from the beginning
}
}
System.out.println("LCM of range of numbers:"+k);
Input:
6
2 4 6 8 9 3
Output:
LCM of range of numbers:72