How to compare & replace x10 variable with a String containing x10 inside - java

I've been trying to do:
double x10 = 2.4;
String str = "The value of a variable is x10";
int c = 0;
while(c<str.length) #Here digit means a valid Number
if(str.charAt[c]==digit && str.charAt[c+1]==digit){
str.charAt[c] = Double.toString(x10);
}
Desired Output:
The value of a variable is 2.4
Problem:
The problem is that it doesn't seems to be comparing 10 in a String,
so that it can replace the x10 in the string with the value of variable x10.
Is there any other way to achieve the desired goal???
it works fine with variable x(1-9) but when it exceeds x10 & greater it stucks.
Didn't found anything relevant to my problem.
Any help would be highly encouraged!

I assume you are in C#. You can use the Regex.Replace variant that takes a MatchEvaluator delegate. Assuming your values are in double[] values and that they substitutions are one off in value (e.g. "x1" corresponds to values[0]), you do:
var ans = Regex.Replace(str, #"x(\d+)", m => values[Convert.ToInt32(m.Groups[1].Value)-1].ToString());

After so many tries, in order to achieve the desired output. I finally figured it out the way to solve it.
String str = "x12",str2 = "x1";
if(str2.matches("x[0-9]{1}")==true){
int var = Integer.parseInt(str.substring(1,2));
System.out.println(var);
}else{
System.out.println("Not Found!");
}if(str.matches("x[0-9]{2}")==true){
int var = Integer.parseInt(str.substring(1,2));
int var2 = Integer.parseInt(str.substring(2,3));
var = var * 10 + var2;
System.out.println(var);
}else{
System.out.println("Not Found!");
}

Related

Taking multiple user entries Without using arrays java

I've just started a intro to programming class and I'm having serious trouble with this. I basically have to take a int, double, boolean, char and string from a user the amount of times they specify and compare them. I'm having trouble actually taking the inputs.
The Problem is:
Modify the program so that, instead of comparing only two sets (records) of values (e.g. first integer vs. second integer, first boolean vs.
second boolean, etc.), the program compares an arbitrary number of records. Your code must not use arrays at this stage and it should still
achieve this behavior using only two variables for each data type.
To get the user data I have tried this :
int numberUsers = Integer.parseInt(gt.getInputString("How many people are we comparing?"));
int dataPoints = 0;
while (dataPoints <= numberUsers) {
String rawInput = gt.getInputString("For person" + dataPoints
+ ", enter in the following format: Height,Hourly Rate,Satisfied with course,Last exam grade,name.");
String[] enteredData = rawInput.split(",");
int userHeight = Integer.parseInt(enteredData[0]);
double hourRate = Double.parseDouble(enteredData[1]);
boolean satisfiedCourse = Boolean.parseBoolean(enteredData[2]);
char userGrade = enteredData[3].charAt(0);
String userName = enteredData[4];
dataPoints++;
the problem I'm having is to start a new string input for users after the first is taken. Any help would be greatly appreciated.
In case the output of the program is supposed to be the max or min value for each data type, it is possible to do that with 2 variables for each type.
For instance, here's what I would do to find the max height and the max hour rate:
int maxUserHeight = Integer.MIN_VALUE;
double maxHourRate = Double.MIN_VALUE;
int dataPoints = 0;
while (dataPoints <= numberUsers) {
String rawInput = gt.getInputString("For person" + dataPoints
+ ", enter in the following format: Height,Hourly Rate,Satisfied with course,Last exam grade,name.");
String[] enteredData = rawInput.split(",");
int userHeight = Integer.parseInt(enteredData[0]);
if (userHeight > maxUserHeight)
maxUserHeight = userHeight;
double hourRate = Double.parseDouble(enteredData[1]);
if (hourRate > maxHourRate)
maxHourRate = hourRate;
boolean satisfiedCourse = Boolean.parseBoolean(enteredData[2]);
char userGrade = enteredData[3].charAt(0);
String userName = enteredData[4];
dataPoints++;
}

Unexpected Type errors

I'm getting two small unexpected type errors which I'm having trouble trying to solve.
The errors occur at:
swapped.charAt(temp1) = str.charAt(temp2);
swapped.charAt(temp2) = temp1;
Any advice?
public class SwapLetters
{
public static void main(String[] args)
{
System.out.println("Enter a string: ");
String str = new String(args[0]);
String swapped = str;
char[] charArray = str.toCharArray();
System.out.println("Enter a position to swap: ");
int Swap1 = Integer.parseInt(args[1]);
System.out.println("Enter a second position to swap: ");
int Swap2 = Integer.parseInt(args[2]);
char temp1 = str.charAt(Swap1);
char temp2 = str.charAt(Swap2);
swapped.charAt(temp1) = str.charAt(temp2);
swapped.charAt(temp2) = temp1;
System.out.println("Original String = " + str);
System.out.println("Swapped String = " + swapped);
}
}
You can assign values to variables, not other values. Statements like 5 = 2 or 'a' = 'z' don't work in Java, and that's why you're getting an error. swapped.charAt(temp1) returns some char value you're trying to overwrite, it's not a reference to a particular position inside the String or a variable you can alter (also, mind that Java Strings are immutable so you can't really change them in any way after creation).
Refer to http://docs.oracle.com/javase/7/docs/api/java/lang/String.html for information on using String, it should have a solution for what you're trying to do.
Your code may even throw IndexOutOfBoundsException - if the index argument is negative or not
less than the length of this string. Check the length of each string.
The left side of your assignment cannot receive that value.
Description of String#charAt(int):
Returns the char value at the specified index
It returns the value of the character; assigning values to that returned value in the following lines is the problem:
swapped.charAt(temp1) = str.charAt(temp2);
swapped.charAt(temp2) = temp1;
Also, String#charAt(int) expects an index of a character within the String, not the character itself (i.e. chatAt(temp1) is incorrect), so your method will not work as expected even if you fix the former problem.
Try the following:
String swapped;
if(swap1 > swap2) {
swap1+=swap2;
swap2=swap1-swap2;
swap1-=swap2;
}
if(swap1!=swap2)
swapped = str.substring(0,swap1) + str.charAt(swap2) + str.substring(swap1, swap2) + str.charAt(swap1) + str.substring(swap2);

Remove trailing zero in Java

I have Strings (from DB), which may contain numeric values. If it contains numeric values, I'd like to remove trailing zeros such as:
10.0000
10.234000
str.replaceAll("\\.0*$", ""), works on the first one, but not the second one.
A lot of the answers point to use BigDecimal, but the String I get may not be numeric. So I think a better solution probably is through the Regex.
there are possibilities:
1000 -> 1000
10.000 -> 10 (without point in result)
10.0100 -> 10.01
10.1234 -> 10.1234
I am lazy and stupid, just
s = s.indexOf(".") < 0 ? s : s.replaceAll("0*$", "").replaceAll("\\.$", "");
Same solution using contains instead of indexOf as mentioned in some of the comments for easy understanding
s = s.contains(".") ? s.replaceAll("0*$","").replaceAll("\\.$","") : s
Use DecimalFormat, its cleanest way
String s = "10.1200";
DecimalFormat decimalFormat = new DecimalFormat("0.#####");
String result = decimalFormat.format(Double.valueOf(s));
System.out.println(result);
Kent's string manipulation answer magically works and also caters for precision loss, But here's a cleaner solution using BigDecimal
String value = "10.234000";
BigDecimal stripedVal = new BigDecimal(value).stripTrailingZeros();
You can then convert to other types
String stringValue = stripedVal.toPlainString();
double doubleValue = stripedVal.doubleValue();
long longValue = stripedVal.longValue();
If precision loss is an ultimate concern for you, then obtain the exact primitive value. This would throw ArithmeticException if there'll be any precision loss for the primitive. See below
int intValue = stripedVal.intValueExact();
String value = "10.010"
String s = new DecimalFormat("0.####").format(Double.parseDouble(value));
System.out.println(s);
Output:
10.01
I find all the other solution too complicated. Simply
s.replaceFirst("\\.0*$|(\\.\\d*?)0+$", "$1");
does the job. It tries the first alternative first, so that dot followed by all zeros gets replaced by nothing (as the group doesn't get set). Otherwise, if it finds a dot followed by some digits (as few as possible due to the lazy quantifier *?) followed by some zeros, the zeros get discarded as they're not included in the group. It works.
Warning
My code relies on my assumption that appending a unmatched group does nothing. This is true for the Oracle implementation, but not for others, including Android, which seem to append the string "null". I'd call the such implementations broken as it just may no sense, but they're correct according to the Javadoc.
The following works for all the following examples:
"1" -> "1"
"1.0" -> "1"
"1.01500" -> "1.015"
"1.103" -> "1.103"
s = s.replaceAll("()\\.0+$|(\\..+?)0+$", "$2");
What about replacing
(\d*\.\d*)0*$
by
\1
?
You could replace with:
String result = (str.indexOf(".")>=0?str.replaceAll("\\.?0+$",""):str);
To keep the Regex as simple as possible. (And account for inputs like 1000 as pointed out in comments)
My implementation with possibility to select numbers of digits after divider:
public static String removeTrailingZero(String number, int minPrecise, char divider) {
int dividerIndex = number.indexOf(divider);
if (dividerIndex == -1) {
return number;
}
int removeCount = 0;
for (int i = dividerIndex + 1; i < number.length(); i++) {
if (number.charAt(i) == '0') {
removeCount++;
} else {
removeCount = 0;
}
}
int fracLen = number.length() - dividerIndex - 1;
if (fracLen - removeCount < minPrecise) {
removeCount = fracLen - minPrecise;
}
if (removeCount < 0) {
return number;
}
String result = number.substring(0, number.length() - removeCount);
if (result.endsWith(String.valueOf(divider))) {
return result.substring(0, result.length() - 1);
}
return result;
}
In addition to Kent's answer.
Be careful with regex in Kotlin. You have to manually write Regex() constructor instead of a simple string!
s = if (s.contains("."))
s.replace(Regex("0*\$"),"").replace(Regex("\\.\$"),"")
else s
Try to use this code:
DecimalFormat df = new DecimalFormat("#0.#####");
String value1 = df.format(101.00000);
String value2 = df.format(102.02000);
String value3 = df.format(103.20000);
String value4 = df.format(104.30020);
Output:
101
102.02
103.2
104.3002
Separate out the fraction part first. Then you can use the below logic.
BigDecimal value = BigDecimal.valueOf(345000);
BigDecimal div = new BigDecimal(10).pow(Integer.numberOfTrailingZeros(value.intValue()));
System.out.println(value.divide(div).intValue());

Regex expression w/ set length

I have several thousands of rows that I'm loading into a database utilizing Pentaho. I must keep the string value length at 4 characters. The source file may only have a single character but it is still needed to keep the length at 4 characters to maintain consistency in the database.
Example:
Source: 10
Database expected results: 0010
I'm using a replace in string transformation or could use a java expression, which ever one works. Please help and provide a resolution utilizing either method (Regex or Javascript expression).
Thanks,
In Java you can use String.format(...) with a format specifier to pad your number with zeroes to 4 digits:
String.format("%04d", yournumber);
In Javascript you can use sprintf(...) for the same task:
var s = sprintf("%04d", yournumber);
So apparently sprintf() isn't standard Javascript but is a library you can download if you like. You can always to do this to get your 4 digits though:
// take the last 4 digits from the right
var s = String("0000" + yournumber).slice(-4);
And you could actually turn this into a simple left-padding function:
String.prototype.leftPad = function(paddingValue, paddingLength) {
return (new Array(paddingLength + 1).join(paddingValue) + this).slice(-paddingLength);
};
var s = String(yournumber).leftPad("0", 4)
(If you mean Javascript):
var str = "10";
function padIt(s) {
s = ""+s;
while (s.length < 4) {
s = "0" + s;
}
return s;
}
console.log(padIt(str));
http://jsfiddle.net/EzqRM/1/
For arbitrary padding of numbers, in javascript:
// padLeft(
// number to pad
// length to pad to
// character to pad with[optional, uses 0's if not specified]
// )
function padLeft(num, pad, padchr) {
num = "" + num;
pad = (pad || num.length) + 1;
return (num.length < pad ? new Array(pad - num.length).join(padchr || "0") : "") + num;
}
// returns "0010"
var input = 10
padded = padLeft(input, 4)

Converting a string to an integer on Android

How do I convert a string into an integer?
I have a textbox I have the user enter a number into:
EditText et = (EditText) findViewById(R.id.entry1);
String hello = et.getText().toString();
And the value is assigned to the string hello.
I want to convert it to a integer so I can get the number they typed; it will be used later on in code.
Is there a way to get the EditText to a integer? That would skip the middle man. If not, string to integer will be just fine.
See the Integer class and the static parseInt() method:
http://developer.android.com/reference/java/lang/Integer.html
Integer.parseInt(et.getText().toString());
You will need to catch NumberFormatException though in case of problems whilst parsing, so:
int myNum = 0;
try {
myNum = Integer.parseInt(et.getText().toString());
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
int in = Integer.valueOf(et.getText().toString());
//or
int in2 = new Integer(et.getText().toString());
Use regular expression:
String s="your1string2contain3with4number";
int i=Integer.parseInt(s.replaceAll("[\\D]", ""));
output:
i=1234;
If you need first number combination then you should try below code:
String s="abc123xyz456";
int i=NumberFormat.getInstance().parse(s).intValue();
output:
i=123;
Use regular expression:
int i=Integer.parseInt("hello123".replaceAll("[\\D]",""));
int j=Integer.parseInt("123hello".replaceAll("[\\D]",""));
int k=Integer.parseInt("1h2el3lo".replaceAll("[\\D]",""));
output:
i=123;
j=123;
k=123;
Use regular expression is best way to doing this as already mentioned by ashish sahu
public int getInt(String s){
return Integer.parseInt(s.replaceAll("[\\D]", ""));
}
Try this code it's really working.
int number = 0;
try {
number = Integer.parseInt(YourEditTextName.getText().toString());
} catch(NumberFormatException e) {
System.out.println("parse value is not valid : " + e);
}
Best way to convert your string into int is :
EditText et = (EditText) findViewById(R.id.entry1);
String hello = et.getText().toString();
int converted=Integer.parseInt(hello);
You should covert String to float. It is working.
float result = 0;
if (TextUtils.isEmpty(et.getText().toString()) {
return;
}
result = Float.parseFloat(et.getText().toString());
tv.setText(result);
You can use the following to parse a string to an integer:
int value=Integer.parseInt(textView.getText().toString());
(1) input: 12 then it will work.. because textview has taken this 12 number as "12" string.
(2) input: "abdul" then it will throw an exception that is NumberFormatException.
So to solve this we need to use try catch as I have mention below:
int tax_amount=20;
EditText edit=(EditText)findViewById(R.id.editText1);
try
{
int value=Integer.parseInt(edit.getText().toString());
value=value+tax_amount;
edit.setText(String.valueOf(value));// to convert integer to string
}catch(NumberFormatException ee){
Log.e(ee.toString());
}
You may also want to refer to the following link for more information:
http://developer.android.com/reference/java/lang/Integer.html
There are five ways to convert
The First Way :
String str = " 123" ;
int i = Integer.parse(str);
output : 123
The second way :
String str = "hello123world";
int i = Integer.parse(str.replaceAll("[\\D]" , "" ) );
output : 123
The Third Way :
String str"123";
int i = new Integer(str);
output "123
The Fourth Way :
String str"123";
int i = Integer.valueOf(Str);
output "123
The Fifth Way :
String str"123";
int i = Integer.decode(str);
output "123
There could be other ways
But that's what I remember now
You can also do it one line:
int hello = Integer.parseInt(((Button)findViewById(R.id.button1)).getText().toString().replaceAll("[\\D]", ""));
Reading from order of execution
grab the view using findViewById(R.id.button1)
use ((Button)______) to cast the View as a Button
Call .GetText() to get the text entry from Button
Call .toString() to convert the Character Varying to a String
Call .ReplaceAll() with "[\\D]" to replace all Non Digit Characters with "" (nothing)
Call Integer.parseInt() grab and return an integer out of the Digit-only string.
The much simpler method is to use the decode method of Integer so for example:
int helloInt = Integer.decode(hello);
Kotlin
There are available Extension methods to parse them into other primitive types.
"10".toInt()
"10".toLong()
"true".toBoolean()
"10.0".toFloat()
"10.0".toDouble()
"10".toByte()
"10".toShort()
Java
String num = "10";
Integer.parseInt(num );
I have simply change this
int j = Integer.parseInt(user.replaceAll("[\\D]", ""));
into
int j = 1;
AND IT SOLVE MY PROBLEM

Categories