String[] tokens = s.split(' ');
for(int i = 0; i < (tokens.length) - 1; ++i)
{
if(isDigit(tokens[i]))
{
// Two numbers cannot be together without an operator.
if(isDigit(tokens[i + 1]))
{
check = 1;
break;
}
if((tokens[i + 1] == '(') )
{
check = 1;
break;
}
}
}
s is the string i'm splitting. after splitting i want to check whether each split part is a digit. i m not able to use isDigit because it can only be used on characters and here the split part is String.
NOTE: i m writing a program for a calculator. if i use toCharArray() the more than one digit numbers will be split. eg. 23 will become 2 and 3 seperately.
int isDigit = false;
try
{
Integer.parseInt(tokens[i])
isDigit = true;
}
catch(NumberFormatException e)
{
}
YOu might use Integer.parseInt(...) if your number should be Integer (same for other types). It throws NumberFormatException on invalid number I believe.
try{
if(isDigit(Integer.parseInt(tokens[i]))
{
//Will come here if it is an integer
}
} catch(NumberFormatException nfe) {
//Will come here if it is not an integer
}
Do you want to know if every token is a number?
try{
Integer.parseInt(token)
return true;
} catch (numberFormatException){
return false;
}
or use apache commons lang http://commons.apache.org/lang/api-release/index.html
StringUtils.isNumeric()
You may want to use string.toCharArray() method instead of string.split(), it produces an array of chars that can then be checked using Character.isDigit(char) method. Hope this helps.
One way: use Integer.parse(token) and catch NumberFormatException for the ones that aren't numbers:
Or use token.toCharArray() and test the characters individually.
Related
package Assignments;
import java.util.Scanner;
public class Assignment1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.next();
int i=0,j=str.length()-1,count=0;
while(i!=j) {
if(str.charAt(i)!=str.charAt(j)) {
count++;
break;
}
i++;
j--;
}
if(count!=0) {
System.out.println("Not a Palindrome");
}
else {
System.out.println("Palindrome");
}
}
}
Upon entering Uppercase letter in input it is showing error. "assa" as input is working fine but "Assa" is showing error.
I know it is a minor fault somewhere but I am new to java. Can anyone help?
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48)
at java.base/java.lang.String.charAt(String.java:709)
at Assignments.Assignment1.main(Assignment1.java:12)
a and A are not the same character. If you don't care about the case, you could convert all the character to lowercase (or to upper case) explicitly when comparing them:
while (i != j) {
if (Character.toLowerCase(str.charAt(i)) != Character.toLowerCase(str.charAt(j))) {
count++;
break;
}
i++;
j--;
}
EDIT:
The updated exception in the question clarifies the problem - it is unrelated to upper/lower case discrepancies, but to a wrong handling of strings with an even number of characters. To handle this you could use the < operator instead of !=:
while (i < j) {
A and a are not the same character, so it is normal that the string doesn't match.
What you could do is, before processing the string to see if it's a palindrome, you convert it to lowercase:
str = str.toLowerCase();
Replace
if(str.charAt(i)!=str.charAt(j))
with
if(Character.toUpperCase(str.charAt(i))!=Character.toUpperCase(str.charAt(j)))
Alternatively,
Replace
if(str.charAt(i)!=str.charAt(j))
with
if(Character.toLowerCase(str.charAt(i))!=Character.toLowerCase(str.charAt(j)))
The key is to compare the characters in the same case.
Apart from this, you also need to
replace
while(i!=j)
with
while(i < j)
in order to avoid StringIndexOutOfBoundsException.
I wanna trim this string.
"0000819780"
How i can get just the "819780" part.
I can do it with my way, just curious is there any "elegant" or "right" way to do this.
I hope this works:
try {
int i = Integer.parseInt(yourString);
System.out.println(i);
} catch(NumberFormatException e) {
// the string is not a number
}
There are many ways you might remove leading zeros from your String; one approach, iterate the String from left to right stopping at the next to the last character (so you don't erase the final digit) stop if you encounter a non-zero and invoke String.substring(int) like
String str = "0000819780";
for (int i = 0, length = str.length() - 1; i < length; i++) {
if (str.charAt(i) != '0') {
str = str.substring(i);
break;
}
}
System.out.println(str);
Alternatively, parse the String like
int v = Integer.parseInt(str);
System.out.println(v);
Alternative:
Using Apache Commons StringUtils class:
StringUtils.stripStart(String str, String stripChars);
For your example:
StringUtils.stripStart("0000819780", "0"); //should return "819780"
An elegant pure java way is just "0000819780".replaceFirst("^0+(?!$)", "")
If the input is always a number and you want to remove only the beginning zeroes, just parse it into an integer. If you want it in string format, parse it back.
String a = "0000819780";
System.out.println(Long.parseLong(a));
Check https://ideone.com/7NMxbE for a running code.
If it can have values other than numbers, you would need to catch NumberFormatException
while(str.length() >= 1 && str.charAt(0) == '0')
str = str.substring(1);
Double abc = Double.parseDouble("00346632");
String xyz = String.format("%.0f", abc);
I enter a list into a JTextArea, and when I push a button, it runs the method below. I need to check to see if str[i+1], str[i+2] is a String and not an int.
public void readData(JTextArea input) {
String[] str = input.getText().split("\n");
for(int i =1; i< str.length; i= i+3) {
try {
Integer.parseInt(str[i]);
simulator.add(new Process(Integer.parseInt(str[i]), str[i+1],str[i+2]));
} catch(NumberFormatException e) {
System.out.println("Please enter an integer only " +
str[i] + " is not an integer");
}
}
}
You could have a function that tries to parse the string into an Integer or a Double and return true if it succeeded, or return false is an exception was thrown during parsing. Parsing into a Double should be enough since all integer values are decimal values without the .0
public static boolean isNumber(String s) {
try {
Double.parseDouble(s);
/* Use Integer.parseInt(s) instead, if
you want to check if the String s
is an Integer */
} catch(NumberFormatException e) { // string is not a number
return false;
}
return true;
}
Then you can say if(!isNumber(str)) to check if the String str is not a number.
Alternatively, you could make the isNumber() be a isNotNumber() by swapping the return false and return true statements.
If you don't want to use exceptions, a different approach would be the following. Since we know a valid number can only contain digits and at most 1 dot for decimal point, we can iterate through the string and check for each character:
if it is not a digit and not a dot, return false
if it is a dot but a dot was already found, return false
otherwise it is valid number character and we do nothing
Here is a sample function:
public static boolean isNumber(String s) {
int dotCount = 0;
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) != '.' && !Character.isDigit(s.charAt(i))) {
return false;
} else if(s.charAt(i) == '.') {
if(dotCount == 1) {
return false;
}
dotCount = 1;
}
}
return true;
}
EDIT: based on #MadProgrammer's suggestions:
A more general approach that will accept values separated with commas such as 1,35 or any amount of spaces within the number string like with 123 456 . 333.
Approach:
Iterate through the string and check for each character:
if it is not a digit, dot, comma, or a space, return false
if it is a dot or a comma but one of them was already found, return false
otherwise it is valid number character and we do nothing
So the code would look something like:
public static boolean isNumber(String s) {
int separatorCount = 0; // count dots and commas
char currChar;
s.trim(); // remove trailing and leading whitespace
for (int i = 0; i < s.length(); i++) {
currChar = s.charAt(i);
if (currChar != '.' && currChar != ',' && currChar != ' '
&& !Character.isDigit(currChar)) {
return false;
} else if (currChar == '.' || currChar == ',') {
if (separatorCount == 1) {
return false;
}
separatorCount = 1;
}
}
return true;
}
Another solution could use the NumberFormat's parse() method. However, this method only checks the beginning of the string (for example, for 12.3.3 it will return 12.3) so we have to return false if the returned string doesn't equal the input string as well as if the ParseException is thrown.
public static boolean isNumber(String s) {
try {
String newVal = NumberFormat.getInstance().parse(s).toString();
if (!newVal.equals(s)) {
return false;
}
} catch (ParseException e) {
return false;
}
return true;
}
NOTE: All of the methods should probably have a check if(s == null) { return false; } for the input String s to prevent a NullPointerException
Your rules are sparse, you don't specify if things like , or . are considered part of a number or not (1, 000.01 for example), also, you don't define if the value is allowed to contain numerical values or not, but...
You Could...
Try parsing each value (or the concatenation of the two) using Integer.parseInt, if they pass, then they are not String (or text) based values...
You Could...
Verify each character within the String to see if it contains more than just digits, using something like Character#isLetter
You Could...
Use a regular expression to determine if the value contain other content other than numbers.
You can try this simple regular expression to check if a string represents a number or not:-
String str = "12345";
System.out.println(str.matches("\\d+"));
Regex seems the best option. Here's a regex that will parse float and integers and currency values with comma as well.
String numberRex = "^([\\d]*\\.*\\d*|[\\d,]*\\.*\\d*)$";
"1234,455.43".matches(numberRex); // true
This is a simple test that asserts there is at least one non numeric char:
if (str.matches(".*[^\\d.].*"))
the regex translates as "somewhere in the input there's a character that's not a digit or a dot"
Alright, I want to make a method for my Chemistry game/project where it would:
take a String
then it would take the String, check for numbers, and if there are numbers, turn it into a subscript of that same number.
return the updated String
My original thoughts was to turn the string into a char array, then make a for loop where I try Integer.parseInt(Character.toString(char array element)), and if it threw a NumberFormatException it would continue the for loop. If it didn't throw an error, then I retain that number, add it to 2080 (because \u2080 -> \u2089 are the subscript unicodes) and then somehow smush that number back into a char.
I tried to write the code for it, but wasn't sure how to proceed.
private String processName(String original)
{
char[] or = original.toCharArray();
int returned = 0;
for(char character : or)
{
try
{
returned = Integer.parseInt(Character.toString(character));
}
catch (Exception e)
{
continue;
}
if(returned != 0)
{
returned += 2080;
String temp = "\\u" + returned;
//gave up here
}
}
}
You're almost there. Remember that chars are two bytes, so they can hold the values you want:
for(int i = 0; i < or.length; i++)
{
try
{
returned = Integer.parseInt(Character.toString(or[i]));
}
catch (Exception e)
{
continue;
}
if(returned != 0)
{
or[i] = (char) (returned + 2080);
}
}
You could get rid of some of the cost of converting to an int by simply checking if the char is a digit and, if it is, adding the appropriate amount, but since this code already works I'll leave that up to you.
This was asked in an interview:
Given in any string, get me the first occurence of an integer.
For example
Str98 then it should return 98
Str87uyuy232 -- it should return 87
I gave the answer as loop through the string and compared it with numeric characters, as in
if ((c >= '0') && (c <= '9'))
Then I got the index of the number, parsed it and returned it. Somehow he was not convinced.
Can any one share the best possible solution?
With a regex, it's pretty simple:
String s = new String("Str87uyuy232");
Matcher matcher = Pattern.compile("\\d+").matcher(s);
matcher.find();
int i = Integer.valueOf(matcher.group());
(Thanks to Eric Mariacher)
Using java.util.Scanner :
int res = new Scanner("Str87uyuy232").useDelimiter("\\D+").nextInt();
The purpose of a Scanner is to extract tokens from an input (here, a String). Tokens are sequences of characters separated by delimiters. By default, the delimiter of a Scanner is the whitespace, and the tokens are thus whitespace-delimited words.
Here, I use the delimiter \D+, which means "anything that is not a digit". The tokens that our Scanner can read in our string are "87" and "232". The nextInt() method will read the first one.
nextInt() throws java.util.NoSuchElementException if there is no token to read. Call the method hasNextInt() before calling nextInt(), to check that there is something to read.
There are two issues with this solution.
Consider the test cases - there are 2 characters '8' and '7', and they both form the integer 87 that you should be returning. (This is the main issue)
This is somewhat pedantic, but the integer value of the character '0' isn't necessarily less than the value of '1', '2', etc. It probably almost always is, but I imagine interviewers like to see this sort of care. A better solution would be
if (Character.isDigit(c)) { ... }
There are plenty of different ways to do this. My first thought would be:
int i = 0;
while (i < string.length() && !Character.isDigit(string.charAt(i))) i++;
int j = i;
while (j < string.length() && Character.isDigit(string.charAt(j))) j++;
return Integer.parseInt(string.substring(i, j)); // might be an off-by-1 here
Of course, as mentioned in the comments, using the regex functionality in Java is likely the best way to do this. But of course many interviewers ask you to do things like this without libraries, etc...
String input = "Str87uyuy232";
Matcher m = Pattern.compile("[^0-9]*([0-9]+).*").matcher(input);
if (m.matches()) {
System.out.println(m.group(1));
}
Just in case you wanted non-regex and not using other utilities.
here you go
public static Integer returnInteger(String s)
{
if(s== null)
return null;
else
{
char[] characters = s.toCharArray();
Integer value = null;
boolean isPrevDigit = false;
for(int i =0;i<characters.length;i++)
{
if(isPrevDigit == false)
{
if(Character.isDigit(characters[i]))
{
isPrevDigit = true;
value = Character.getNumericValue(characters[i]);
}
}
else
{
if(Character.isDigit(characters[i]))
{
value = (value*10)+ Character.getNumericValue(characters[i]);
}
else
{
break;
}
}
}
return value;
}
}
You could go to a lower level too. A quick look at ASCII values reveals that alphabetical characters start at 65. Digits go from 48 - 57. With that being the case, you can simply 'and' n character against 127 and see if that value meets a threshold, 48 - 57.
char[] s = "Str87uyuy232".toCharArray();
String fint = "";
Boolean foundNum = false;
for (int i = 0; i < s.length; i++)
{
int test = s[i] & 127;
if (test < 58 && test > 47)
{
fint += s[i];
foundNum = true;
}
else if (foundNum)
break;
}
System.out.println(fint);
Doing this wouldn't be good for the real world (different character sets), but as a puzzle solution is fun.