Okay, I'm just getting curious. But I was wondering if there was such thing as a substring for numbers (math.substring ?), and then it would get the character(s) in the position specified.
Example (really poorly thought out one)
int number = 5839;
int example = number.substring(0,1)
println = example;
and then it displays 5?
Why don't you just convert it to a string, and then call substring(0,1)?...
int number = 5839;
int example = Integer.parseInt((number+"").substring(0,1));
Where calling number+"" causes the JVM to convert it into a String, and then it calls substring() on it. You then finally parse it back into an int
int number = 5839;
String numString = Integer.toString(number);
String example = numString.substring(0,1)
int subNum = Integer.parseInt(example);
System.out.println(subNum);
Change it to a String first.
Here's a little function I wrote:
public static int intSubstring(int number, int beginIndex, int endIndex) {
String numString = Integer.toString(number);
String example = numString.substring(beginIndex,endIndex)
int subNum = Integer.parseInt(example);
return subNum;
}
Or compressed:
public static int intSubstring(int number, int beginIndex, int endIndex) {
return Integer.parseInt((number+"").substring(beginIndex,endIndex));
}
No there is not. But you could possibly convert the integer to string and get the substring and again parse back to integer
No there no such thing, but you can do the following:
String s = ""+number; //You can now use the Substring method on s;
Or if you just want to remove the last y digits:
number = (int)(number/y);
of if you want to keep only the last z digits:
number = number%(Math.pow(10,z)); // % means modulo
No, there is none. int is a primitive data type. You can however, accomplish your need with one statement.
Integer.parseInt(String.valueOf(12345).substring(1, 2))
Related
This is just a little bit of my code, but I am trying to loop through two strings, get the value of the first number in one string, and then use that number as the position to find in the other string, then add that word into a new string. But it comes up with the error "String cannot be converted to int" can anyone help?
String result = "";
for (int i = 0; i < wordPositions.length; i++){
result += singleWords[wordPositions[i]];
}
if your wordPositions is a String array when you do this:
result += singleWords[wordPositions[i]];
it like if you does this
result += singleWords["value of the wordPositions array at index i"];
but is need to be an int in [] not a string that why you have the exception String can not be cast to Int
If wordPositions is an array of numbers inside a string for example
String[] wordPositions = new String[]{"1","2","3"};
Then you nees to use
Integer.parseInt(NUMBER_IN_STRING);
To change the string value to an int value.
You are getting this error because wordPositions[i] returns a string and you need to convert it to int before trying to acess singlewords[].
result += singleWords[Integer.parseInt(wordPositions[i])];
Use this to convert String into int
Integer.parseInt(integerString);
The completed line of code:
result += singleWords[Integer.parseInt(wordPositions[i])];
I've searched for this on the internet but was unable to find a precise solution, one possible solution I found was to read the integer as a String, and use charAt method and then cast the character to int to print the ascii value.
But is there any other possible way to do it other than the above stated method?
int a=sc.nextInt();
//code to convert it into its equivalent ASCII value.
For example, consider the read integer as 1, and now I want the ASCII value of 1 to be printed on the screen,which is 49
I assume you're looking for this:
System.out.print((char)a);
The easy way to do that is:
For the Whole String
public class ConvertToAscii{
public static void main(String args[]){
String number = "1234";
int []arr = new int[number.length()];
System.out.println("THe asscii value of each character is: ");
for(int i=0;i<arr.length;i++){
arr[i] = number.charAt(i); // assign the integer value of character i.e ascii
System.out.print(" "+arr[i]);
}
}
}
For the single Character:
String number="123";
asciiValue = (int) number.charAt(0)//it coverts the character at 0 position to ascii value
I'm trying to select the positions of some value and print the parts of that value by position in java when I'm working on android app.
for example if I have some number four-digit, 4375 if I select the 3rd one system will print 7, 4th one system will print 5..
You can easily select the portion of a string with String.substring() methods.
See https://docs.oracle.com/javase/7/docs/api/java/lang/String.html for more help.
Hence, you could simply convert the digit to String and then use the substring() method get the part you want.
I will just provide my solution as a suggestion:
private String getSubDigit(int value, int postion){
// you probably should check if the value is correct and ready to be processed.
if(Check(value)) {
String temp = "" + value;
return temp.substring(position,position+1);
}else{
return "";
}
}
You can acheive it like this
int values = 4375;
String mValue = String.valuOf(values);
Char mChar = mValue.chatAt(int index);
int selectedValue = Character.getNumericValue(mChar);
i try to split String array and show rundom values in this array.i wrote function witch can split String
public int Cal(String ab) {
String[] arr=ab.split(":");
int av=(Integer.parseInt(arr[0])*60 + Integer.parseInt(arr[1]))*1000;
return av;
}
and i call this function like this
String[] st = {"00:49 ","00:49","02:17","03:26","03:55", "04:26", "05:25" };
Random random = new Random();
String index = st[random.nextInt(st.length)];
Log.e("randommmmmmmmmmmm", String.valueOf(Cal(index)));
i have numberformatexception exception. i have not idea what i am doing wrong
Use Trim() method like below,
public int Cal(String ab)
{
String[] arr=ab.split(":");
int av = ( Integer.parseInt(arr[0].trim())*60 + Integer.parseInt(arr[1].trim()))*1000;
return av;
}
trim() will remove spaces. Whenever you are trying to convert numeric string to number ( i.e. "11 " ), you should always remember to use trim() to avoid NumberFormatException
It means you are passing invalid number to parseInt method. The parseInt method of Integer class expects a valid string representation of a number
Your String array first element is having the space at the last --->> "00:49 "
String[] arr=ab.split(":");
Integer.parseInt(arr[1]) --------->>> This Leads to NumberFormatException
So Try Trimming the data before use..
int av=(Integer.parseInt(arr[0].trim())*60 + Integer.parseInt(arr[1]).trim())*1000;
Use the code as below.
public int Cal(String ab) {
String[] arr=ab.split(":");
int av=(Integer.parseInt(Integer.parseInt(arr[0]))*60 + Integer.parseInt(arr[1]))*1000;
return av;
}
I've tried the code below, but I'm getting an error. How would I go about adding two large values represented as strings together?
public class LargeAddition {
static String testcase1 = "987659876598765";
static String testcase2 = "9999999999999999999999999988888888888";//can we add this kind of large num
public static void main(String args[]){
LargeAddition testInstance = new LargeAddition();
String result = testInstance.add(testcase1,testcase2);
System.out.println("Result : "+result);
}
//write your code here
public String add(String str1, String str2){
Long num=000000000000000L;
//String str="";
num=Long.parseLong(str1)+Long.parseLong(str2);
//String str=num.toString();
return num.toString();
}
}
Use BigInteger, Long is short for these values.
public static String add(String str1, String str2) {
BigInteger big1 = new BigInteger(str1);
BigInteger big2 = new BigInteger(str2);
final BigInteger num = big1.add(big2);
return num.toString();
}
Since this is an a homework assignment and you don't/can't use classes such as BigInteger, I'll go through a more tedious and manual way to do it (although a good introduction assignment).
You can loop through the two String-integers from size-1 to 0.
String integer1 = "1230"
String integer2 = "9999999"
for(int i = integer1.size; i >= 0; i--){
//addition
}
However, this is may be an issue since the two String-integers have different sizes. I would create a method that will add additional zeroes to the front of the smaller String-integer so both String-integers match in size. Ex. "1230" -> "0001230"
Before looping, create an output String-inter which equals to an empty-String.
String outputInt = "";
Convert each char to an int, then do the addition.
int tempResult = Integer.parseInteger(integer1.indexOf(i)) + Integer.parseInteger(integer2.indexOf(i))
If you get a single digit, convert it to a String and append to output String-integer. If you get a double digit, then only put append the second digit and carry over the first digit to the next calculation.
String tempResultStr = //convert tempResult into a String
if(tempResultStr .size == 1){
//handle single digit case
}else{
//handle double digit case
//use a variable to declare carry over
}
Remember to handle the case if you have to carry over and there is nothing to carry over to.
NOTE: This is pseudo code for most part
If you run
System.out.println(Long.MAX_VALUE);
you'll get
9223372036854775807
your values are far greater
9999999999999999999999999988888888888
so the way is to use BigDecimal
BigDecimal bd = new BigDecimal("9999999999999999999999999988888888888");
System.out.println(bd.multiply(bd));
gives you
99999999999999999999999999777777777760000000000000000123456790143209876544