Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
System.out.println("Strings to be printed");
In the above line of code, the strings are coated with double inverted commas
and when we want to print the non-string values or variables, we separate by commas.
Does the compiler ask for the commas? or is it required by the println(); to determine the strings separately?
why is inverted commas required by println();?
It is not so much required by println as required by the Java language.
The println method takes a String argument, and the way to write a String literal in Java is you put double-quote characters around it.
If you didn't put the double-quotes around 'String to be printed' then the Java Language Specification says that you have a sequence of 4 identifiers: String to be printed. That is not a valid Java expression ... and you will get a compilation error.
Why is it that way? Well, it is also consistent with the vast majority of other programming languages ... including Java's direct antecedents ... and that is as good an explanation as you are likely to get.
I suppose you could also be asking why they need to have rules like this: why couldn't the compiler just figure out what the programmer means. And the answer to that is that it is beyond the state of the art ... and probably beyond the realms of possibility. (How does a compiler figure out what the programmer means, when a lot of the time the programmer doesn't know himself!?)
Java: Creating Strings
The most direct way to create a string is to write:
String greeting = "Hello world!";
In this case, "Hello world!" is a string literal—a series of
characters in your code that is enclosed in double quotes.
Whenever it encounters a string literal in your code, the compiler
creates a String object with its value—in this case, Hello world!.
So it's not the requirement of println() but it is a way to create a string literal in Java.
"Strings to be printed"
This is called a String Literal. The compiler understands it as a string. If you want to add a " in the middle of it you use a \ before it to escape the character.
"Strings \"to\" be printed"
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
Improve this question
I want to understand the use of semicolons in Java expressions, statements, or in for loops. and I want to know what is the memory consumption for the semicolon and comments we write in the source code?.
int a = 1; //coments written in java
for(int a=0; a <1;a++);
etc
If I remove the semicolon gives below errors
java: ';' expected
The semicolon is the statement delimiter. It's not part of the instructions, it separates them. It's just a hint to the compiler, it doesn't generate any code in itself.
Generally speaking, there's no relation between the length of the source code and the size of the binary file, particularly because the length of the visible source code is typically much smaller than that of all the libraries used.
The reason for semicolon in all c-family languages is, that the code parser (part of compiler) must know somehow, when is the expression complete. Programmer is free to type another statement(s) in that same line, each delimited by a semicolon.
In some other languages, end of line character denotes end of expression.
As to the memory consumption, with ASCII coding (or variable length coding), it would be 8 bits = 1 byte each colon. But careful, this will only consume memory while you edit the code in editor.
When you compile/execute your code - those semantic characters like colons, commas, brackets, etc are not held in memory anymore. As stated before, this is only needed for compiler (and editor of course).
Does this explain ?
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am creating a project "test" Which takes questions set by teacher and student has to answer them.What if teacher has to set boolean expression questions The question appear in label in swing.That is why I have told swing That is why I want to know how to represent A bar(complement of A) in label in frame.is there a way to do it?
You can use Unicode, the numbering of all kind of characters in the World. Under Windows or Linux there is a char map utility which which to look after characters:
You will find U+XXXX codes show, where XXXX is a hexadecimal number (base 16: 0-9A-F).
You can use this number in Java as \uXXXX.
Ā = "\u0100" U+0100
ā = "\u0101" U+0101
The bar, also called macron, also exists separately as "combining diacritical mark", a zero-width accent:
̄ = "\u0304"
In Char Map you can find other combining diacritical marks by selecting the thus named "Unicode subrange."
Hence
Ā == "\u0100" == "A\u304"
However is some fonts that may not look to good. But it would mean little work, to replace any letter with its bar-variant. The teacher types in "X-bar" and you replace it.
String s = ".... a-bar ... z-bar ...";
s = s.replaceAll("-bar\\b", "\u304");
The regex "\\b" is a word boundary marker, so you won't translate "milk-bars."
Maybe best would be to edit in Unicode, say UTF-8. As ≤ ≠ ≈ ∞ probably are also desired. This means setting the editor and java compiler to use UTF-8. For separate text editing, there exist free NotePad++ and JEdit.
Labels in Swing support HTML, and the overline character entity can be used in the HTML:
label.setText("<html>A̅");
See a HtmlDemo screenshot
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am reading from a file that contains the following two lines: "hello hi" and "hii hey".
The first string of each line is the regex and the second is the replacement, i.e. String.replaceAll("hello", "hi"). I am supposed to go through each line in the file to replace the regex in a String with the replacement. However there is a catch. The processed characters should never be replaced again.
For example I have this String: "helloi".
After the first line, I have "hii".
After the second line, the naive approach would result in "hey".
I want to make sure "hii" still stays as "hii", because it already contains processed characters.
Note that the String I'm using as an example ("helloi") is just a simple one, the actual String will be large and contains multiple lines.
How do you implement that?
Edit: Let me use an example to explain my situation more clearly. I have a String "helloi hii". After the first line in the file, I have "hii hii". But after the second line, I will have "hii hey". The first "hii" contains processed characters, hence it will not be replaced
I guess every time you call String.replaceAll you should insert search and replacement strings into a HashSet. Check presence of search and replacement strings in this HashSet, before your call String.replaceAll.
Only when both search and replacement strings are not present in HashSet you call String.replaceAll.
// at start
Set<String> processed = new HashSet<String>();
// read file line by line and have this inside your file processing loop
if (!processed.contains(search) && !processed.contains(replacement)) {
String repl = line.replaceAll(search, replacement);
processed.add(search);
processed.add(replacement);
}
Not entirely sure I understand, but can you make your own class with a string property and a boolean property to indicate if it's been modified? Split your string into an array of that class and process each one.
String.replaceAll() probably won't do the job for you.
I would suggest something similar to this psuedo-code
replacements -> HashMap<String, String>
StringBuffer result
regexStr = "("
for each key in replacements
regexStr += key + "|" //key MUST not have any regex syntax or must be properly escaped
regexStr remove last '|' append ")"
Matcher m = Pattern.compile(regexStr).matcher()
while(matches) {
get next match
result.append(match group 1)
result.append(replacements.get(match group 2))
}
Essentially:
Keep a map of all of your replacements:
hi->woah
hello->hi
hey->what's up
what\'s up->fun
You search for strings matching the regex (.*?)(hi|hello|hey|what\'s up), which is all of the map keys (i.e. the things you want to search for). The \ would end up in a Java literal as "what\\s up", because the regex string needs to know to escape the '
Each iteration, look at what was captured. The first group is everything since the last match. The second group is the word/phrase to replace. If the word it "hi", you want to replace it with "woah", so look up the replacement for "hi" in your map.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
A friend had an interview question asking the following:
Given a string comprising of the characters (,),{,},[,], determine if is well formed or not.
In my mind I would have answered no as it is a string and so "/" character would be required to print said characters. Is this correct or am I way off base?
if well-formed means each brace is closed with a matching brace and there are no incidents like ({)}, then I would suggest you to use stack
go through each character in the string
if it is opening brace, push it on the stack
if it is closing brace, pop from stack and look, if it is a match
-> if you go through all chars in string and stack is empty, your string is well formed
You seem to be asking what the interview question means.
The answer is that is means what the interviewer meant it to mean. You (or your friend) should ask the interviewer for clarification if you need it. (Indeed, if you didn't ask the interviewer for clarification, you might "lose points" ... for not asking.)
However, a reasonable interpretation would be that the question is asking the interviewee to write a method to check that a String consisting of those characters has balanced bracketing; e.g.
[]{[]} OK
[ BAD
[(]) BAD
FWIW - there is no general definition for a "well-formed string". Rather a string is considered to be well-formed with respect to some grammar, if a valid parse tree can be constructed for the string using the productions of the grammar.
The problem in this case is that no such grammar has been provided (at least, not here). Hence the interview question (as stated) is incomplete / ambiguous / only answerable if you are prepared to guess what grammar the interviewer means.
The correct answer is "exactly what do you mean by well formed?" Vague requirements should be made more specific, and that's a signal that you are looking for correct functionality, not a quick fix.
We can guess as to what it means. It might mean correct nesting of elements, such that opening and closing parenthesis follow an xml-style tag syntax, where
{([)]}
would not be well formed
It might mean properly escaped so that it can be printed in an environment where the characters are interpreted as commands. In such a case, well formed might mean
\{\(\[
It might even mean that once an opening character is found, the only following legal character is its closing character. In such a case, the following would not be well formed.
{()}
If well formed just means one closing item for each opening item, then (due to the definition) the following even might be ok
)(
In short, when you have doubt, ask. Asking is the key to so many things, and it shows that you are paying attention and thinking. These skills are far more important than "knowing the answer" because knowing the answer without understanding the request results in answering the wrong question.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am writing a simplified Java compiler. I wrote a regex for variable name:
"(_?[a-zA-Z]+[\w]*)"
and I want to add that the name can not be certain words, like int, double, true, false...
I tryed using ^ , but it is not working.
It can be done with a RE, but it's not easy for a human to write it. Treat keywords as identifiers in the scanner and distinguish the identifiers vs keywords in the tokenizer afterwards. That should be substantially easier.
I don't believe that this should do that via regular expressions but rather can be better done using a HashSet<String> and exclude identifier names that are contained in the set.
^ is used for something else :
^ may appear at the beginning of a pattern to require the match to
occur at the very beginning of a line. For example, ^abc matches
abc123 but not 123abc.
consider using "(?!...)" :
(?!...) is a negative look-ahead because it requires that the
specified pattern not exist.
i suggest that if it's impossible or too hard , go to real coding instead . sometimes , regular expressions can be much slower than real , optimized code , and they can be very confusing and you might have problems finding what's wrong with what you've written.
for trying out your regular expressions , check this one:
http://gskinner.com/RegExr/
for quick referencing , check this one:
http://www.autohotkey.com/docs/misc/RegEx-QuickRef.htm