New to java. Trying to familiarize myself with syntax and overall language structure.
I am trying to mimic this php function in java which just converts all instances of a number to a particular character
for($x=10;$x<=20;$x++){
$string = str_replace($x, chr($x+55), $string);
}
so in php if a string was 1090412 it would be converted to something like A904C.
I am trying to do this in java by using string.replace but I cant for the life of me figure out how to cast the variables properly. I know that I can convert an integer to a character by casting it as (char), but not sure where to go from there. this gives me a compile error expecting a character set.
string=1090412;
for (x = 10; x <= 35; x++) {
string.replace( x, (char) (x + 55));
}
Well, although not the best way to do this, here is a method that works
import java.lang.*;
public class T {
public static void main(String[] args) {
String s = "1090412";
for (int i = 10; i <= 20; i++) {
s = s.replace(Integer.toString(i), "" + (char)(i + 55));
}
System.out.println(s);
}
}
The java.lang.String object has a replace method on it. It is overloaded to take either two char parameters or two CharSequence objects. The "" + (char)(i + 55) is just a quick way to create a CharSequence.
Related
I have been given a code and need to "fill in the blanks", for one part of the problem I need to write a method that will check that a string has only letters from the alphabet ( no commas or periods or numbers) and then if there are upper case letters, convert them to lower case.
I think I understand how to write this, however this is part of the code that is given
public Message (String m){
message = m;
lengthOfMessage = m.length();
this.makeValid();
The method I have to write is the makeValid one, but I'm not sure how to use the this.makeValid and how to write the code if the method doesn't take a string as the argument?
Note: I understand now that I can use message and lengthOfmessage but i am still trying to wrap my head around it.
would this code make sense and make proper use of the this
public void makeValid(){
for (int i = 0; i < lengthOfMessage ; i++ ) {
char mchar = message.charAt(i);
if (64 <= mchar && mchar<= 90) {
mchar = (char)((mchar + 32));
builder.append(mChar);
}
}
}
I am trying to fix this code because it's not running due to a java.lang.NumberFormatException. It's confusing me because I've never encountered this error before.
The code has to solve expressions such as 3 + 4 * 5, while following PEMDAS rules, such as multiplying comes before adding, etc. I would also prefer it to use keyboard input, which I tried to do myself which made matters worse, so I decided to just remove it.
import java.util.*;
import static java.lang.Integer.*;
import static java.lang.System.*;
import java.lang.*;
class ExpressionSolver_Rumenov
{
private ArrayList<String> list;
private String expression;
private String trimmedExp;
private String evaluated;
private int eval;
public ExpressionSolver_Rumenov(String s)
{
list=new ArrayList<String>();
expression=s;
trimmedExp=s.trim();
for (int x=0; x<trimmedExp.length(); x++)
{
list.add(""+trimmedExp.charAt(x));
}
}
public void setExpression(String s)
{
expression=s;
trimmedExp=s.trim();
list.clear();
for (int x=0; x<trimmedExp.length(); x++)
{
list.add(""+trimmedExp.charAt(x));
}
}
public void solveExpression()
{
eval=0;
for (int x=0; x<list.size(); x++)
{
if (list.get(x).equals("*")||list.get(x).equals("/"))
{
if (list.get(x).equals("*"))
{
list.set(x-1, String.valueOf(Integer.parseInt(list.get(x-1))*Integer.parseInt(list.get(x+1))));
list.remove(x+1);
list.remove(x);
}
else if(list.get(x).equals("/"))
{
list.set(x-1, String.valueOf(Integer.parseInt(list.get(x-1))/Integer.parseInt(list.get(x+1))));
list.remove(x+1);
list.remove(x);
}
}
}
for (int x=0; x<list.size(); x++)
{
if (list.get(x).equals("-"))
{
list.set(x-1, String.valueOf(Integer.parseInt(list.get(x-1))-Integer.parseInt(list.get(x+1))));
list.remove(x);
list.remove(x+1);
}
else if (list.get(x).equals("+"))
{
list.remove(x);
}
}
for (int x=0; x<list.size(); x++)
{
if (list.get(x).equals(" "))
{
list.remove(x);
}
list.set(x, list.get(x).trim());
}
for (int x=0; x<list.size(); x++)
{
eval+=Integer.parseInt(list.get(x));
}
evaluated=String.valueOf(eval);
}
public String toString( )
{
return evaluated;
}
}
public class Lab04
{
public static void main( String args[] )
{
ExpressionSolver_Rumenov test = new ExpressionSolver_Rumenov("3 + 5");
test.solveExpression();
out.println(test.toString());
test.setExpression("3 * 5");
test.solveExpression();
out.println(test);
test.setExpression("3 - 5");
test.solveExpression();
out.println(test);
test.setExpression("3 / 5");
test.solveExpression();
out.println(test);
test.setExpression("5 * 5 + 2 / 2 - 8 + 5 * 5 - 2");
test.solveExpression();
out.println(test);
}
}
You are trying to parse a " " character into an Integer at line eval+=Integer.parseInt(list.get(x));. This is happening because you are not properly removing the spaces from the list.
Here, you are running a loop on the x<list.size() condition and when loop runs, you are also removing elements from it. You can not dynamically change the list size when you are comparing the loop termination with list.size(). This is not how you loop through the list.
// not a correct way
for (int x=0; x<list.size(); x++)
{
if (list.get(x).equals(" "))
{
list.remove(x);
}
list.set(x, list.get(x).trim());
}
Instead, you should use list Iterator. Like this,
// correct way
Iterator iter = list.iterator();
while (iter.hasNext()) {
if(iter.next().equals(" "))
iter.remove();
}
You should update your code wherever you are iterating through list and removing the elements from it at the same time.
The bottom line is that you're trying to feed a non-Integer character to Integer.parseInt(). If you fix the expressions in your Lab04 driver class, you'll see that everything works properly.
For example, instead of this:
ExpressionSolver_Rumenov test = new ExpressionSolver_Rumenov("3 + 5");
Try this, with the space characters removed:
ExpressionSolver_Rumenov test = new ExpressionSolver_Rumenov("3+5");
You probably want a more fault tolerant program, however, so you have some work to do, especially if you want users to be able to input their own data.
I think you might be misunderstanding what String.trim() does. The trim() method removes leading and trailing whitespace from a String, so if you have a tab character at the beginning of your String and a newline at the end, trim() will get rid of those.
What trim() will not do, however, is get rid of whitespace interspersed throughout a String. For that, you need to prune out the whitespace yourself, or just ignore whitespace characters.
To remove space characters from within the String, in your setExpression method, replace:
expression=s;
with
expression = s.replaceAll("\\s+","");
Of course, you can still just ignore whitespace. Instead of:
char c = trimmedExp.charAt(x);
list.add("" + c);
Try:
char c = trimmedExp.charAt(x);
if(c != " ")
{
list.add("" + c);
}
Remember that you're comparing Character in this case, so == should be used, rather than .equals().
the scope of (.trim() ) is removing the spaces before and after the String expression like in the link blow
https://www.w3schools.com/jsref/jsref_trim_string.asp
ex : String name = " my name is Muhamad " ;
we have two spaces before the expression and one after
so if we applied the .trim() like blow
String newName = name.trim();
we will receive "my name is Muhamad" not "mynameisMuhamad" as a value of newName
Acording to the JavaDocs from the Oracle, the NumberFormatException:
Thrown to indicate that the application has attempted to convert a
string to one of the numeric types, but that the string does not have
the appropriate format.
Your problem is that you are trying to convert someting that is not a number into a number. The problem is probably from the parsing, like reading spaces and trying to convert them into numbers.
EDIT:
For the parsing I advise you to look at the "Shunting Yard" Algorithm in the Wikipedia:
https://en.wikipedia.org/wiki/Shunting-yard_algorithm
The following code should be pretty self-evident. What I have made up so far to compute Y with variable x and some constants:
public static void main(String[] args) {
int x=50;
String str="100-x+200";
str=str.replaceAll("x", Integer.toString(x));
String [] arrComputeNumber = str.split("[-|+]");
String [] arrComputeOperator = str.split("[\\d]");
int y=Integer.parseInt(arrComputeNumber[0]);
for (int i = 0; i < arrComputeOperator.length; i++) {
if (arrComputeOperator[i].equals("-")) {
y-=Integer.parseInt(arrComputeNumber[i+1]);
} else if (arrComputeOperator[i].equals("+")) {
y+=Integer.parseInt(arrComputeNumber[i+1]);
}
}
System.out.println("y="+y);
}
Unfortunately it doesn't work since str.split("[\\d]") extracts wrongly.
It it extracts correctly I assume that above code would function correctly. Anyway this implementation is merely trivial and doesn't take parenthesis or +- combination (which becomes minus), etc. into consideration. I haven't found any better ways. Do you know any better ways to evaluate string as mathematical expression in Java?
You can use BeanShell. It is a Java interpreter.
Here is some code:
Interpreter interpreter = new Interpreter();
interpreter.eval("x = 50");
interpreter.eval("result = 100 - x + 200");
System.out.println(interpreter.get("result"));
I am trying to translate a String that contains a binary value (e.g. 000010001010011) to it's Hex value.(453)
I've been trying several options, but mostly I get a converted value of each individual character. (0=30 1=31)
I have a function that translates my input to binary code through a non-mathematical way, but through a series of "if, else if" statements. (the values are not calculated, because they are not standard.) The binary code is contained in a variable String "binOutput"
I currently have something like this:
String bin = Integer.toHexString(Integer.parseInt(binOutput));
But this does not work at all.
Try using Integer.parseInt(binOutput, 2) instead of Integer.parseInt(binOutput)
Ted Hopp beat me to it, but here goes anyway:
jcomeau#intrepid:/tmp$ cat test.java; java test 000010001010011
public class test {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
System.out.println("The value of " + args[i] + " is " +
Integer.toHexString(Integer.parseInt(args[i], 2)));
}
}
}
The value of 000010001010011 is 453
Is there a method or way to read and keep reading chars from a string, putting them in a new string until there is a certain char.
Keep reading from < to > but no further.
Thankx
Of course. You will need:
the method String.charAt(int)
the + operator (or the method String.concat, or, if performance matters, the class StringBuilder)
the for statement
and perhaps an if-statement with a break statement
The statements and operators are explained in the Java Tutorial, and the method in the api javadoc.
(And no, I will not provide an implementation, since you would learn little by copying it)
You can actually write a utility that does that
public class StringUtil {
public static String copy(String str, char startChar, char endChar) {
int startPos = str.indexOf(startChar);
int endPos = str.lastIndexOf(endChar);
if (endPos < startPos) {
throw new RuntimeException("endPos < startPos");
}
char[] dest = new char[endPos - startPos + 1];
str.getChars(startPos, endPos, dest, 0);
return new String(dest);
}
};
PS Untested....
Alternatively, you can
String result = str.substring(startPos, endPos + 1); //If you want to include the ">" tag.
This may not be what you want but it will give you the desired string.
String desiredString="<Hello>".split("[<>]")[1];