this is my code :
String addchar = "";
String tempchar;
int len = strline.length();
char[] chars = strline.toCharArray();
int amount = 0;
for (int i = 0; i < len; i++) {
tempchar = String.valueOf(chars[i]);
if (tempchar == "0" || tempchar == "1" || tempchar == "2" || tempchar == "3" || tempchar == "4" || tempchar == "5" || tempchar == "6" || tempchar == "7" || tempchar == "8" || tempchar == "9") {
addchar=tempchar+addchar;
}
}
amount=Integer.parseInt(addchar);
but when run this code , I see that amount is empty!
I want to extract , the number that there is in strline
Slightly less elegant than Nilesh's answer, but as an alternative:
StringBuilder sb = new StringBuilder();
for (char c : strline.toCharArray()) {
if ((sb.length() == 0 && "-".equals(c)) || Character.isDigit(c)) sb.append(c);
}
int amount = Integer.parseInt(sb.toString());
Edit Amended to allow for initial negative sign
try this use Matcher
Matcher matcher = Pattern.compile("\\d+").matcher("a22dsdddd212");
while(matcher.find()) {
Log.e("number :-> ",matcher.group()+"");
}
If you want all numeric char, you can use replaceALL in this way:
String numericString = strline.replaceAll("[^0-9]", "");
then use ParseInt.
Hope it helps.
Related
I made a code to show the amount of times a vowel is used. A, E, I, O, U. The code is counting but it is not conunting correctly.
#Override
public void onClick(View v) {
int letter1 = 0;
int letter2 = 0;
String enter1 = str1.getText().toString();
String enter2 = str2.getText().toString();
for (int i = 0; i < str1.length(); i++) {
if (enter1.charAt(i) == 'a' || enter1.charAt(i) == 'e' || enter1.charAt(i) == 'i' || enter1.charAt(i) == 'o' ||
enter1.charAt(i) == 'u')
{
letter1++;
}
for(int j = 0; j < str2.length(); j ++){
if(enter2.charAt(j) == 'a' || enter2.charAt(j) == 'e' || enter2.charAt(j) == 'i' || enter2.charAt(j) == 'o' ||
enter2.charAt(j) == 'u')
{
letter2++;
}
}
display3.setText("The amount of vowels are :"+ letter1 + " & " + letter2);
}
}
});
My output for Hello World is 2 and 5. 2 for Hello is correct but 5 for World is not. What am I missing?
If we reformat the code slightly, the problem is more apparent:
for (int i = 0; i < str1.length(); i++) {
if (enter1.charAt(i) == 'a' || enter1.charAt(i) == 'e' || enter1.charAt(i) == 'i' || enter1.charAt(i) == 'o' ||
enter1.charAt(i) == 'u') {
letter1++;
}
for (int j = 0; j < str2.length(); j++) {
if (enter2.charAt(j) == 'a' || enter2.charAt(j) == 'e' || enter2.charAt(j) == 'i' || enter2.charAt(j) == 'o' ||
enter2.charAt(j) == 'u') {
letter2++;
}
}
display3.setText("The amount of vowels are :" + letter1 + " & " + letter2);
}
As you can see, the second for loop is inside the first one. That means the second number will be N times larger than it should be, where N is the length of the first word. This matches what's happening: there is only 1 vowel in "world" but there are 5 letters in "hello".
The display3.setText(...) part will also be executed N times, but since it overwrites the previous value you won't be able to notice that, and you'll just see the final value.
To fix, just close the first for loop earlier:
for (int i = 0; i < str1.length(); i++) {
if (enter1.charAt(i) == 'a' || enter1.charAt(i) == 'e' || enter1.charAt(i) == 'i' || enter1.charAt(i) == 'o' ||
enter1.charAt(i) == 'u') {
letter1++;
}
}
for (int j = 0; j < str2.length(); j++) {
if (enter2.charAt(j) == 'a' || enter2.charAt(j) == 'e' || enter2.charAt(j) == 'i' || enter2.charAt(j) == 'o' ||
enter2.charAt(j) == 'u') {
letter2++;
}
}
display3.setText("The amount of vowels are :" + letter1 + " & " + letter2);
Something problem with the brackets
#Override
public void onClick(View v) {
for(Loop){
if(condition){
}
}//first loop
for(Loop){
if(condition){
}
}//second loop
//display here
});//end for onClick
Is there any pdf text extractor api that extract arabic text from pdf.
I am using itextpdf api it works fine in extract English but it doesn't extract arabic text.
This is my code for extract text in pdf:
private String extractPDF(String path) throws IOException {
String parsedText = "";
PdfReader reader = new PdfReader(path);
int n = reader.getNumberOfPages();
for (int page = 0; page < n; page++) {
parsedText = parsedText + PdfTextExtractor.getTextFromPage(reader, page + 1).trim() + "\n"; //Extracting the content from the different pages
}
reader.close();
return parsedText;
}
and this is the input pdf :arabic.pdf
Update :
i able to extract arabic text but it doesn't preserves the order of the lines , and this is my code:
private String extractPDF(String name) throws IOException {
PdfReader reader = new PdfReader(name);
StringBuilder text = new StringBuilder();
for (int i=1;i<=reader.getNumberOfPages();i++){
String data = PdfTextExtractor.getTextFromPage(reader,i,new SimpleTextExtractionStrategy());
text.append(Bidi.BidiText(data,1).getText());
}
return text.toString();
}
pdf text is :
بسم الله الرحمن الرحيم
السلام عليكم ورحمة الله وبركاته
سبحان الله
the output is :
سبحان الله
السلام عليكم ورحمة الله وبركاته
بسم الله الرحمن الرحيم
this is my code for method BidiText:
public static BidiResult BidiText(String str, int startLevel)
{
boolean isLtr = true;
int strLength = str.length();
if (strLength == 0)
{
return new BidiResult(str, false);
}
// get types, fill arrays
char[] chars = new char[strLength];
String[] types = new String[strLength];
String[] oldtypes = new String[strLength];
int numBidi = 0;
for (int i = 0; i < strLength; ++i)
{
chars[i] = str.charAt(i);
char charCode = str.charAt(i);
String charType = "L";
if (charCode <= 0x00ff)
{
charType = BaseTypes[charCode];
}
else if (0x0590 <= charCode && charCode <= 0x05f4)
{
charType = "R";
}
else if (0x0600 <= charCode && charCode <= 0x06ff)
{
charType = ArabicTypes[charCode & 0xff];
}
else if (0x0700 <= charCode && charCode <= 0x08AC)
{
charType = "AL";
}
if (charType.equals("R") || charType.equals("AL") || charType.equals("AN"))
{
numBidi++;
}
oldtypes[i] = types[i] = charType;
}
if (numBidi == 0)
{
return new BidiResult(str, true);
}
if (startLevel == -1)
{
if ((strLength / numBidi) < 0.3)
{
startLevel = 0;
}
else
{
isLtr = false;
startLevel = 1;
}
}
int[] levels = new int[strLength];
for (int i = 0; i < strLength; ++i)
{
levels[i] = startLevel;
}
String e = IsOdd(startLevel) ? "R" : "L";
String sor = e;
String eor = sor;
String lastType = sor;
for (int i = 0; i < strLength; ++i)
{
if (types[i].equals("NSM"))
{
types[i] = lastType;
}
else
{
lastType = types[i];
}
}
lastType = sor;
for (int i = 0; i < strLength; ++i)
{
String t = types[i];
if (t.equals("EN"))
{
types[i] = (lastType.equals("AL")) ? "AN" : "EN";
}
else if (t.equals("R") || t.equals("L") || t.equals("AL"))
{
lastType = t;
}
}
for (int i = 0; i < strLength; ++i)
{
String t = types[i];
if (t.equals("AL"))
{
types[i] = "R";
}
}
for (int i = 1; i < strLength - 1; ++i)
{
if (types[i].equals("ES") && types[i - 1].equals("EN") && types[i + 1].equals("EN"))
{
types[i] = "EN";
}
if (types[i].equals("CS") && (types[i - 1].equals("EN") || types[i - 1].equals("AN")) && types[i + 1] == types[i - 1])
{
types[i] = types[i - 1];
}
}
for (int i = 0; i < strLength; ++i)
{
if (types[i].equals("EN"))
{
// do before
for (int j = i - 1; j >= 0; --j)
{
if (!types[j].equals("ET"))
{
break;
}
types[j] = "EN";
}
// do after
for (int j = i + 1; j < strLength; --j)
{
if (!types[j].equals("ET"))
{
break;
}
types[j] = "EN";
}
}
}
for (int i = 0; i < strLength; ++i)
{
String t = types[i];
if (t.equals("WS") || t.equals("ES") || t.equals("ET") || t.equals("CS"))
{
types[i] = "ON";
}
}
lastType = sor;
for (int i = 0; i < strLength; ++i)
{
String t = types[i];
if (t.equals("EN"))
{
types[i] = (lastType.equals("L")) ? "L" : "EN";
}
else if (t.equals("R") || t.equals("L"))
{
lastType = t;
}
}
for (int i = 0; i < strLength; ++i)
{
if (types[i].equals("ON"))
{
int end = FindUnequal(types, i + 1, "ON");
String before = sor;
if (i > 0)
{
before = types[i - 1];
}
String after = eor;
if (end + 1 < strLength)
{
after = types[end + 1];
}
if (!before.equals("L"))
{
before = "R";
}
if (!after.equals("L"))
{
after = "R";
}
if (before == after)
{
SetValues(types, i, end, before);
}
i = end - 1; // reset to end (-1 so next iteration is ok)
}
}
for (int i = 0; i < strLength; ++i)
{
if (types[i].equals("ON"))
{
types[i] = e;
}
}
for (int i = 0; i < strLength; ++i)
{
String t = types[i];
if (IsEven(levels[i]))
{
if (t.equals("R"))
{
levels[i] += 1;
}
else if (t.equals("AN") || t.equals("EN"))
{
levels[i] += 2;
}
}
else
{
if (t.equals("L") || t.equals("AN") || t.equals("EN"))
{
levels[i] += 1;
}
}
}
int highestLevel = -1;
int lowestOddLevel = 99;
int ii = levels.length;
for (int i = 0; i < ii; ++i)
{
int level = levels[i];
if (highestLevel < level)
{
highestLevel = level;
}
if (lowestOddLevel > level && IsOdd(level))
{
lowestOddLevel = level;
}
}
for (int level = highestLevel; level >= lowestOddLevel; --level)
{
int start = -1;
ii = levels.length;
for (int i = 0; i < ii; ++i)
{
if (levels[i] < level)
{
if (start >= 0)
{
chars = ReverseValues(chars, start, i);
start = -1;
}
}
else if (start < 0)
{
start = i;
}
}
if (start >= 0)
{
chars = ReverseValues(chars, start, levels.length);
}
}
String result = "";
ii = chars.length;
for (int i = 0; i < ii; ++i)
{
char ch = chars[i];
if (ch != '<' && ch != '>')
{
result += ch;
}
}
return new BidiResult(result, isLtr);
}
Your example PDF does not contain any text at all, it merely contains an embedded bitmap image of text.
When talking about "text extraction from PDFs" (and "text extractor APIs" and PdfTextExtractor classes etc.), one usually means finding text drawing instructions in the PDF (for which a PDF viewer uses a font program either embedded in the PDF or available on the system at hand to display the text) and determining their text content from their string arguments and font encoding definitions.
As in your case there are no such text drawing instructions, merely a bitmap drawing instruction and the bitmap itself, text extraction from your document will return an empty string.
To retrieve the text displayed in your document, you have to look for OCR (optical character recognition) solutions. PDF libraries (like iText) can help you to extract the embedded bitmap image to forward to the OCR solution if the OCR solution does not directly support PDF but only bitmap formats.
If you also have PDF documents which display Arabic text using text drawing instructions with sufficient encoding information instead of bitmaps, you may need to post-process the text extraction output of iText with a method like Convert as proposed in this answer as pointed out by Amedee in a comment to your question. (Yes, it is written in C# but it is pretty easy to port to Java.)
I am writing a code in android for rpn calculations and it crashes when i have operators inside brackets. Eg(89+7) crashes but (8)+7 outputs 15.
This is the method i use for infix to postfix conversion:
private static List<String> convert(String input) {
int p = 0;
String pfb = "";
Stack<Character> chara = new Stack<>();
List<String> pfa = new ArrayList<>();
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {
if (pfb.length() > 0) {
pfa.add(pfb);
}
pfb = "";
if (chara.empty()) {
chara.push(ch);
} else {
Character chTop = (Character) chara.peek();
if (chTop == '*' || chTop == '/')
p = 1;
else if (chTop == '+' || chTop == '-')
p = 0;
if (p == 1) {
if (ch == '+' || ch == '-') {
pfa.add(String.valueOf(chara.pop()));
i--;
Log.d("pfa", "" + input.length() + "" + i);
} else { // Same
pfa.add(String.valueOf(chara.pop()));
i--;
}
} else {
if (ch == '+' || ch == '-' && chara.peek() != '(') {
pfa.add(String.valueOf(chara.pop()));
chara.push(ch);
} else
chara.push(ch);
}
}
} else if (ch == '(') {
chara.push(ch);
// Log.d("St",""+chara.peek());
} else if (ch == ')') {
`//Code crashes here` while (chara.peek() != '(' && !chara.empty()) {
pfa.add(String.valueOf(chara.pop()));
}
if (!chara.empty() && chara.peek() != '(')
return null; // invalid expression
else
chara.pop();
} else {
pfb += ch;
}
// Log.d("pfa",""+pfa+"");
}
return pfa;
}
You code crashes because first you peek the stack element and then checking the empty condition.
it should be like
while ( !chara.empty() && chara.peek() != '(' )
There are 3 EditText, 1st Price input,2nd Percentage, 3rd Result. I am trying to calculate EditText inputs using onFocusChangeListener.
The Code:
etPercen.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
OnFocusChangedPercenCalculator();
}
}
});
etresult.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
OnFocusChangedResultCalculator();
}
}
});
and
public void OnFocusChangedPercenCalculator() {
String text1 = String.valueOf(etPrice.getNumericValue()).toString();
String text2 = etPercen.getText().toString();
String text3 = String.valueOf(etresult.getNumericValue()).toString();
double input1 = 0;
double input2 = 0;
int i = 0;
if (text1.length() > 0 || text2.length() > 0 || text3.length() > 0)
input1 = Double.parseDouble(text1);
input2 = Double.parseDouble(text2);
if (text1.length() != 0 ){
if(text2.length() != 0) {
double output = (input1 * input2) / 100;
e = String.valueOf(output);
etresult.setText("" + e);
} else if (text2.length() ==0 || text2.matches("")){
etresult.setText(i+"");
}
}else if(text1.length() == 0){
if(text2.length() != 0) {
etresult.setText(i+"");
} else if (text2.length() ==0 || text2.matches("")){
etresult.setText(i+"");
}
}
}
public void OnFocusChangedResultCalculator() {
String text1 = String.valueOf(etPrice.getNumericValue()).toString();
String text2 = etPercen.getText().toString();
String text3 = String.valueOf(etresult.getNumericValue()).toString();
double input1 = 0;
double input3 = 0;
int i = 0;
if (text1.length() > 0 || text2.length() > 0 || text3.length() > 0)
input1 = Double.parseDouble(text1);
input3 = Double.parseDouble(text3);
if (text1.length() != 0 ){
if(text3.length() != 0) {
double output = (input3 / input1) * 100;
e = String.valueOf(output);
etPercen.setText("" + e);
} else if (text3.length() ==0 || text3.matches("")){
etPercen.setText(i);
}
}else if(text1.length() == 0){
if(text3.length() != 0) {
etPercen.setText(i);
} else if (text3.length() ==0 || text3.matches("")){
etPercen.setText(i);
}
}else if (input3 > input1){
etPercen.setText(100);
}
}
What i want to do is 2nd and 3rd EditTexts looking each other. I mean when the user change focus from 2nd/3rd editText then the calculation will begin in an instant. The idea is to make the 2nd one calculate and put the result on the 3rd and make the 3rd one calculate and put the result on 2nd. It depends on the user if he/she wants to change fill/change the value (lets say the price is 10000, the user want to know whats the 20% of it, or the user want the other way around, whats the % of 20000 from 10000). Thats my expectation, but when we emptied the 1st and 3rd edittext the output of the 2nd one will be NaN. How to handle this? i mean avoid the result become NaN?
Ok, I refactored the second method to illustrate what I was talking about. Should be working.
public void OnFocusChangedResultCalculator() {
String text1 = etPrice.getText().toString().trim();
String text2 = etPercen.getText().toString().trim();
String text3 = etresult.getText().toString().trim();
double input1 = text1.length()>0 ? Double.parseDouble(text1) : 0;
double input3 = text3.length()>0 ? Double.parseDouble(text3) : 0;
if (input3 > input1){
etPercen.setText(100);
return;
}
double output = (input3 / input1) * 100;
etPercen.setText(output);
}
UPDATE
public void OnFocusChangedResultCalculator() {
String text1 = String.valueOf(etPrice.getNumericValue()).toString().trim();
String text2 = etPercen.getText().toString().trim();
String text3 = String.valueOf(etresult.getNumericValue()).toString().trim();
double input1 = text1.length()>0 ? Double.parseDouble(text1) : 0;
double input3 = text3.length()>0 ? Double.parseDouble(text3) : 0;
if (input3 > input1){
etPercen.setText(Integer.toString(100));
etresult.setText(Double.toString(input1));
return;
}
double output = (input3 / input1) * 100;
etPercen.setText(Double.toString(output));
}
The NaN error is just Not-a-Number.
I think you need to change your condition
From
if (text1.length() != 0 )
To
if (text1.length() > 0 )
If length is -1 or 1 your if condition will still be satisfied.
By using the operator > instead of != you will be assured that
text1 is not empty.
You are getting NaN because "" and " " are not a number
Instead of using
if (text1.length() != 0 )
use
if(!TextUtils.isEmpty(text1.toString().trim()))
This is an android String utility to perform null and empty check on any String.
Also you probably should to mention in your layout xml that your inputType is number
I'm trying to use the intent anchor to launch my app as described here. I'm able to get it to launch my app using this syntax,
Launch my app
but I have no idea what many of the various elements mean.
The basic syntax for an intent-based URI is as follows:
intent:
HOST/URI-path // Optional host
#Intent;
package=[string];
action=[string];
category=[string];
component=[string];
scheme=[string];
end;
what do each of the segments mean (so I know how I may best use take advantage of them)
how/where can I include any extra data (ie, my own parameters)
Here is the method toUri() from the Intent class:
public String toUri(int flags) {
StringBuilder uri = new StringBuilder(128);
String scheme = null;
if (mData != null) {
String data = mData.toString();
if ((flags&URI_INTENT_SCHEME) != 0) {
final int N = data.length();
for (int i=0; i<N; i++) {
char c = data.charAt(i);
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
|| c == '.' || c == '-') {
continue;
}
if (c == ':' && i > 0) {
// Valid scheme.
scheme = data.substring(0, i);
uri.append("intent:");
data = data.substring(i+1);
break;
}
// No scheme.
break;
}
}
uri.append(data);
} else if ((flags&URI_INTENT_SCHEME) != 0) {
uri.append("intent:");
}
uri.append("#Intent;");
if (scheme != null) {
uri.append("scheme=").append(scheme).append(';');
}
if (mAction != null) {
uri.append("action=").append(Uri.encode(mAction)).append(';');
}
if (mCategories != null) {
for (String category : mCategories) {
uri.append("category=").append(Uri.encode(category)).append(';');
}
}
if (mType != null) {
uri.append("type=").append(Uri.encode(mType, "/")).append(';');
}
if (mFlags != 0) {
uri.append("launchFlags=0x").append(Integer.toHexString(mFlags)).append(';');
}
if (mPackage != null) {
uri.append("package=").append(Uri.encode(mPackage)).append(';');
}
if (mComponent != null) {
uri.append("component=").append(Uri.encode(
mComponent.flattenToShortString(), "/")).append(';');
}
if (mSourceBounds != null) {
uri.append("sourceBounds=")
.append(Uri.encode(mSourceBounds.flattenToString()))
.append(';');
}
if (mExtras != null) {
for (String key : mExtras.keySet()) {
final Object value = mExtras.get(key);
char entryType =
value instanceof String ? 'S' :
value instanceof Boolean ? 'B' :
value instanceof Byte ? 'b' :
value instanceof Character ? 'c' :
value instanceof Double ? 'd' :
value instanceof Float ? 'f' :
value instanceof Integer ? 'i' :
value instanceof Long ? 'l' :
value instanceof Short ? 's' :
'\0';
if (entryType != '\0') {
uri.append(entryType);
uri.append('.');
uri.append(Uri.encode(key));
uri.append('=');
uri.append(Uri.encode(value.toString()));
uri.append(';');
}
}
}
uri.append("end");
return uri.toString();
}
If you can read Java code then it should be pretty clear what is going on here. In any case, extras can be put in the URL and they look something like this:
<type>.<key>=<value>;
where <type> is one of the following:
S = String
B = Boolean
b = Byte
c = Character
d = Double
f = Float
i = Integer
l = Long
s = Short
Here are a few examples:
Launch app:
<a href="intent://#Intent;scheme=http;package=com.example.myapp;end">
Launch app with one String extra called "foo" containing the value "bar123":
<a href="intent://#Intent;scheme=http;package=com.example.myapp;S.foo=bar123;end">
Launch app with a String extra called "foo" containing the value "bar123" and an Integer extra called "number" containing the value "-567":
<a href="intent://#Intent;scheme=http;package=com.example.myapp;S.foo=bar123;i.number=-567;end">
As at android 28, the API has changed. Here is what the toUri code has been changed to:
public String toUri(#UriFlags int flags) {
StringBuilder uri = new StringBuilder(128);
if ((flags&URI_ANDROID_APP_SCHEME) != 0) {
if (mPackage == null) {
throw new IllegalArgumentException(
"Intent must include an explicit package name to build an android-app: "
+ this);
}
uri.append("android-app://");
uri.append(mPackage);
String scheme = null;
if (mData != null) {
scheme = mData.getScheme();
if (scheme != null) {
uri.append('/');
uri.append(scheme);
String authority = mData.getEncodedAuthority();
if (authority != null) {
uri.append('/');
uri.append(authority);
String path = mData.getEncodedPath();
if (path != null) {
uri.append(path);
}
String queryParams = mData.getEncodedQuery();
if (queryParams != null) {
uri.append('?');
uri.append(queryParams);
}
String fragment = mData.getEncodedFragment();
if (fragment != null) {
uri.append('#');
uri.append(fragment);
}
}
}
}
toUriFragment(uri, null, scheme == null ? Intent.ACTION_MAIN : Intent.ACTION_VIEW,
mPackage, flags);
return uri.toString();
}
String scheme = null;
if (mData != null) {
String data = mData.toString();
if ((flags&URI_INTENT_SCHEME) != 0) {
final int N = data.length();
for (int i=0; i<N; i++) {
char c = data.charAt(i);
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
|| (c >= '0' && c <= '9') || c == '.' || c == '-' || c == '+') {
continue;
}
if (c == ':' && i > 0) {
// Valid scheme.
scheme = data.substring(0, i);
uri.append("intent:");
data = data.substring(i+1);
break;
}
// No scheme.
break;
}
}
uri.append(data);
} else if ((flags&URI_INTENT_SCHEME) != 0) {
uri.append("intent:");
}
toUriFragment(uri, scheme, Intent.ACTION_VIEW, null, flags);
return uri.toString();
}
This shows that the chosen answer will no longer work.
Check this answer by David Wasser for a working solution.