whats wrong with my code, i want it so if the string you input is 33*10= it outputs the correct answer, but it outputs 0.0 in this case and if the string was 33+10 it would output 44
while (character != '=')
{
for (int i = 0; i < calc.length(); i++)
{
character = calc.charAt(i);
try
{
final String characterString = Character.toString(character);
characterString = characterString +characterString
setOperand(Double.parseDouble(characterString));
if (flag == 0)
{
operand1 = (Double.parseDouble(characterString));
result = operand1;
flag = 1;
}
getResult();
}
}
catch (Exception e)
{
try
{
operator = character;
}
catch (Exception e2)
{
System.out.println("Enter a number");
}
}
}
}
You cannot add char to your String, use StringBuffer:
StringBuffer buffer = new StringBuffer();
buffer.add("3+3=");
buffer.add("6");
System.out.println(buffer.toString());
String mainString="i am ready to add characters";
char c='v';
String toAdd=Character.toString(c);
mainString = mainString.concat(toAdd);
Instead of having character = calc.charAt(i); which is only grabbing 1 character try...
StringBuilder sb = new StringBuilder();
while(calc.charAt(i).isDigit()){
sb.append(calc.charAt(i));
i++;
}
...
final String characterString = sb.toString();
Doing this will attach all consecutive digits to the string builder and then turn that into a string to be parsed.
This may work, but your code has a lot of places that it could fail. For instance, you're using exceptions as a decision method, which is typically frowned upon.
Objects of type String can't be changed after their creation. You have either to build a new String out of the old String an the one you want to append or - way better - use a StringBuilder. If you need synchronization for the String manupilation you would use a StringBuffer instead a StringBuilder. Both are essantially the same but the latter one is threadsafe whereas the first one is not.
final String characterString = Character.toString(character);
characterString = characterString +characterString
I don' really get what you want to do here. Yes you could use the second line, but there is a problem:
characterString +characterString
will create a new object, thus charactrerString will be assigned a new object. This are you preventing by the final statement in the first line.
Moreover characterString +characterString would create a String composed by a String repeated 2 times. Like
characterString = "123456";
characterString = characterString + characterString;
System.out.print(characterString);
Would print 123456123456 in the console. And don't know if this is your intention.
And you are initializing the String characterString inside the loop. So each pass you are creating a new one, discarding the old one. Unnecessary object creation an destruction should be avoided if possible.
Related
I have a String with value
String rest="bac";
I have another String with value
String str="baack";
If i use
str.contains(rest);
it returns false. But i want the output to be true. As "baack" contains all the letters from string rest
Is it possible to do so? With or without this method?
Unfortunately, there is no standard method doing this, as far as I know.
If what you want is to check that the second string contains at least once every character of the first string, then you can check each character one by one with the following test:
boolean result = true;
for (char c : test.toCharArray()) {
result &= str.indexOf(c) > -1;
}
return result;
Or alternatively:
for (char c : test.toCharArray()) {
if (str.indexOf(c) == -1) {
return false;
}
}
return true;
It might not be optimal, but it works and it is simple to read.
Since the order is not important, your question turns to be whether the first set of character contains the second set of character.
// Initial the sets
Set<char> bigSet = new HashSet<char>(Arrays.asList(str));
Set<char> smallSet = new HashSet<char>(Arrays.asList(rest));
for (char c : smallSet) {
if(!bigSet.contains(c)){
return false;
}
}
return true;
Here is another way to make sure all characters from one string are in the second string. It is a lengthy way but it is one of the very basic ways to work with characters from String in java. I know it is not optimal but it serves the purpose.
String rest="bac";
String str="baack";
char[] strChar = str.toCharArray();
char[] restChar = rest.toCharArray();
int count = 0;
for(int i=0;i<restChar.length;i++){
for(int j=0;j<strChar.length; j++){
if(restChar[i] == strChar[j]){
count++;
}
}
}
if(count>=restChar.length){
System.out.println("All the characters from: "+rest+" are in: "+str);
}
May I know how can I remove the leading zero in JAVA code? I tried several methods like regex tools
"s.replaceFirst("^0+(?!$)", "") / replaceAll("^0*", "");`
but it's seem like not support with my current compiler compliance level (1.3), will have a red line stated the method replaceFirst(String,String)is undefined for the type String.
Part of My Java code
public String proc_MODEL(Element recElement)
{
String SEAT = "";
try
{
SEAT = setNullToString(recElement.getChildText("SEAT")); // xml value =0000500
if (SEAT.length()>0)
{
SEAT = SEAT.replaceFirst("^0*", ""); //I need to remove leading zero to only 500
}
catch (Exception e)
{
e.printStackTrace();
return "501 Exception in proc_MODEL";
}
}
}
Appreciate for help.
If you want remove leading zeros, you could parse to an Integer and convert back to a String with one line like
String seat = "001";// setNullToString(recElement.getChildText("SEAT"));
seat = Integer.valueOf(seat).toString();
System.out.println(seat);
Output is
1
Of course if you intend to use the value it's probably better to keep the int
int s = Integer.parseInt(seat);
System.out.println(s);
replaceFirst() was introduced in 1.4 and your compiler pre-dates that.
One possibility is to use something like:
public class testprog {
public static void main(String[] args) {
String s = "0001000";
while ((s.length() > 1) && (s.charAt(0) == '0'))
s = s.substring(1);
System.out.println(s);
}
}
It's not the most efficient code in the world but it'll get the job done.
A more efficient segment without unnecessary string creation could be:
public class testprog {
public static void main(String[] args) {
String s = "0001000";
int pos = 0;
int len = s.length();
while ((pos < len-1) && (s.charAt(pos) == '0'))
pos++;
s = s.substring(pos);
System.out.println(s);
}
}
Both of those also handle the degenerate cases of an empty string and a string containing only 0 characters.
Using a java method str.replaceAll("^0+(?!$)", "") would be simple;
First parameter:regex -- the regular expression to which this string is to be matched.
Second parameter: replacement -- the string which would replace matched expression.
As stated in Java documentation, 'replaceFirst' only started existing since Java 1.4 http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceFirst(java.lang.String,%20java.lang.String)
Use this function instead:
String removeLeadingZeros(String str) {
while (str.indexOf("0")==0)
str = str.substring(1);
return str;
}
I have an assignment where I'm supposed to have a method that formats an array of String objects to be tabulated a certain way with a header, and put all the objects (after being formatted) nicely into a single String for the method to return. This method is inside an object class, so it ultimately will be formatting multiple objects the same way, so I need it to format the same way with various String lengths.
Here's what I need the output to look like:
Hashtags:
#firstHashtag
#secondHashtag
Each hashtag is in a String[] of hashtags,
i.e.
String[] hashtags = ["#firstHashtag", "#secondHashtag"]
So basically I need to use string.format() to create on single string containing a tabbed "Hashtags:" header, and then each String in the "hashtags" array to be on a new line, and double-tabbed. The size of the "hashtag" array changes since it is in an object class.
Could someone help me use String.formatter?
This is what my method looks like so far:
public String getHashtags()
{
String returnString = "Hashtags:";
String add;
int count = 0;
while(count < hashtags.length)
{
//hashtags is an array of String objects with an unknown size
returnString += "\n";
add = String.format("%-25s", hashtags[count]);
//here I'm trying to use .format, but it doesn't tabulate, and I
//don't understand how to make it tabulate!!
count++;
returnString = returnString + add;
}
if(hashtags == null)
{
returnString = null;
}
return returnString;
}
Any helpful advice on what to do here with formatting would be greatly appreciated!!!
If you are trying to use real tabs and not spaces, then just change your program to be like this one:
public String getHashtags()
{
if(hashtags == null)
{
return null;
}
String returnString = "Hashtags:";
int count = 0;
while(count < hashtags.length)
{
//hashtags is an array of String objects with an unknown size
returnString = returnString + "\n\t\t"+hashtags[count];
count++;
}
return returnString;
}
Your String.format() statement will create a String that is left-justified and padded to 25 spaces. For example, this line:
System.out.println("left-justified >" + String.format("%-25s", "hello") + "<");
outputs:
left-justified >hello <
The other thing is that you're not really using tabs (I don't see the tab character in your program). String.format() is creating Strings that are length 25 and left-justified. Keep that in mind as you create the return string. Also, your loop as adding a newline character each time. That's why you're getting multi-line output.
I have a basic method which returns a string based on the input of a user:
public String getString() {
String message = inputGenerator.getMessage(); // Returns user inputted string
String messageStart = message.substring(0, 3); // Get start of message
String concat = ""; // Variable to concatenate messages
if(messageStart.equals("Hi")) {
concat += message; // Append input to concat string.
inputGenerator.getMessage(); // Call for another user prompt
} else {
concat += message; // Append input to concat string.
}
return concat; // Return concatenated string.
}
What I want to do:
As you can hopefully work out, what I want to do is prompt a user for more messages if the start of the message includes the word hi, until it doesn't, and return that concatenated string, e.g.
>> Enter a string ("hiexample")
>> Enter a string ("hianotherexample")
>> Enter a string ("nothi")
>> returns "hiexamplehianotherexamplenothi"
The problem
The problem is that the if statement only works once because inputGenerator.getMessage(); obviously jumps out of the conditional after being called.
If I try to use a while() statement instead, it runs forever and eventually crashes the program.
This seems shorter and more elegant:
public String getString() {
StringBuilder msg = new StringBuilder();
String read;
do {
read = inputGenerator.getMessage();
msg.append(read);
} while (read.toLowerCase().startsWith("hi"));
return msg.toString();
}
I use the StringBuilder because it's more efficient than String concatenation like you do.
Let me explain:
concat += message;
gets inflated by the compiler to
concat = new StringBuilder(concat).append(message).toString();
Now guess which is more efficient. :)
Is this what you're thinking?
public String getString()
{
String result = "";
while (true)
{
String message = inputGenerator.getMessage();
result += message;
if (!message.startsWith("hi"))
{
break;
}
}
return result;
}
I think you want 2 as the second argument to substring since your continuation string is "hi", right?
EDITS: Several tweaks thanks to Floegipoky, clcto and StackOverflowException (see comments/other answers below).
private void doShareEmp(pageBean UTIL, HttpServletRequest request, String page)
throws Exception
{
doAction(request, UTIL, page);
String action = pageBean.getSafeRequestOrNullParameter(request, "DO");
long empRecNum = UTIL.getNumValue("EMPLOYEE", "REC_NUM");
if (action != null)
{
if (action.startsWith("US:"))
unshareEmployee(request, UTIL, action.substring(3));
else if (action.equals("SHARE") && empRecNum != 0)
shareEmployee(request, UTIL, empRecNum);
}
ListBean list = UTIL.getListBean(request, "EMPSHARELIST", true);
if (empRecNum != 0)
{
StringBuffer sql = new StringBuffer();
sql.append("SELECT FLDREC_NUM, FLDCOMPANY, FLDLOCATION, FLDDEPT FROM #SCHEMAEMPLVIEW WHERE FLDEMPLOYEE = ? AND FLDTABLE='SHARED' ORDER BY FLDCOMPANY, FLDLOCATION, FLDDEPT");
ArrayList qryParms = new ArrayList();
qryParms.add(new Long(empRecNum));
list.setQuery(UTIL, sql, qryParms);
}
else
list.init();
}
In this piece of code i am appending an query to a StringBuffer.
Which one will be better?
String
StringBuffer
StringBuilder
StringBuilder is a replacement to StringBuffer in a single threaded environment since 1.5, so go with StringBuilder. If you are not going to do any other manipulation with the data after the fact, go with String.
StringBuffer is only needed in threaded environment and if you need synchronization. Here it doesn't seem to be the case.
Also, your string seems defined one and for all, a simple String would be enough.
A StringBuilder is interesting when you are modifying your "string" by appending content. If you already have all your content, no need for a StringBuilder.
But you can already read all these informations on their javadocs :
The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.
Strings are immutable in Java so any time you modify the String object you're using StringBuilder anyway. If the String is immutable then use String, otherwise create a StringBuilder and convert it to a String when you are done modifying it.
Unless you execute this method (to run the query) thousands of times per second, use a plain String. It's the most readable, fast and compact solution.
You might be too verbose. If your code is
String sql = "SELECT COLUMNA,";
if(foo)
sql += "COLUMNB"
else
sql += "COLUMNC"
Then the compiler is actually going to optimize and use a StringBuffer.
You should not be wasting your time worrying about how to concatenate 2 strings. Thats not the mark of a great programmer, if that's what you thought.
Try this ->
long finalTime1 = 0;
{
long initialTimeTest = System.currentTimeMillis();
for( int index = 0; index < 10000; index++ ){
StringBuilder sb = new StringBuilder("Hello, ").append("World");
System.out.println(sb.toString());
}
finalTime1 = System.currentTimeMillis() - initialTimeTest;
}
long finalTime2 = 0;
{
long initialTimeTest = System.currentTimeMillis();
for( int index = 0; index < 10000; index++ ){
String sb = "Hello, " + "World";
System.out.println( sb );
}
finalTime2 = System.currentTimeMillis() - initialTimeTest;
}
System.out.println( finalTime1 );
System.out.println( finalTime2 );
Results:
...
Hello, World
Hello, World
245
148
Did you think string buffer was faster ??
We are breaking the mother of all rules: Keep it Simple. -
For mundane string handling there is no reason why to use StringBuilder. It just adds unnecessary complexity to a mundane task.
Please, we need to think BIG, think in the overall business impact of the module to the project. Discussing whether we shall assemble two strings with StringBuilder or String is thinking little, - don't do that.