Possible without String? - java

I can’t solve this task without a string (don’t know yet) :
"My program asks the user if he wants to see a smiley. If he answers with 'Y' he gets a ":)", other input will be a ":(". Use a conditional operator."
My solution (with a string):
System.out.println("Do you want to see a smiley");
answer=scan.findWithinHorizon(".",0).charAt(0);
string=(answer=='Y')?: ":)" : ":("; //works like that but I need it without string
System.out.println(string);
btw: is the conditional operator often used?
Thanks for your help
And if there are any further advices tell me please.

I don't know if i understan you but you can try:
if(answer=='Y'){
System.out.println(":)");
}
else{
System.out.println(":(");
}
And yes conditional operator for example: if/else is one of the basic things in programing.

Do you mean without String variables? Then here is the nasty oneliner:
System.out.println("Do you want to see a smiley");
System.out.println(scan.findWithinHorizon(".",0).charAt(0)=='Y' ? ":)" : ":(" );
If you mean without using any kind of string (not even ""), you cold print each char individually. This would not require a String but is really annoying and unnecessary.
Edit: because requested, here is this version:
System.out.print('D');
System.out.print('o');
....
System.out.print('y');
System.out.print('\n');
if (scan.findWithinHorizon(".",0) == 'Y') {
System.out.print(':');
System.out.print(')');
System.out.print('\n');
} else {
....
}

Related

Is there any Checkstyle/PMD/Findbugs rule to force "else if" to be on the same line?

In our project for chained if/else/if we would like to have following formatting:
if (flag1) {
// Do something 1
} else if (flag2) {
// Do something 2
} else if (flag3) {
// Do something 3
}
And forbid following one:
if (flag1) {
// Do something 1
} else {
if (flag2) {
// Do something 2
} else {
if (flag3) {
// Do something 3
}
}
}
Is there some predefined rule in either of listed above static code analysis tools to force this code style? If no - I know there is an ability to write custom rules in all of those tools, which one would you suggest to implement such a rule (not really familiar with writing custom rules in either of them)?
It can be done with CheckStyle, but you'll have to code a custom check.
Using a custom check allows you to completely ignore comments. The line number that a token is on can be determined by calling getLineNo() on the DetailAST. Here's what the AST looks like, with line number information (red circles):
The custom check's code will likely be quite short. You basically register for LITERAL_ELSE tokens and see if LITERAL_IF is their only child. Also remember to handle SLISTs. In those cases, LITERAL_IF and RCURLY should be the only children. Both cases are illustrated in the above picture.
Alternative using a RegExp check
For the record, I originally thought one could also configure a regex match using else[ \t{]*[\r\n]+[ \t{]*if\b for the format property (based on this post).
Here's the mentioned regex as a railroad diagram:
This turned out not to be feasible, because it produces false negatives when there are comments between between else and if. Worse, it also produces false positives when the nested if is followed by unrelated code (like else { if() {...} <block of code>}. Thanks #Anatoliy for pointing this out! Since comments and matching braces which are mixed with comments cannot be reliably grasped by regexes, these problems obsolete the RegExp approach.
This post says you can't do it in Checkstyle.
In PMD you definitely can. The AST (abstract syntax tree) is different.
For the pattern you don't want
if (true) {
String a;
} else {
if (true) {
String b;
}
}
The tree looks like:
<IfStatement>
<Expression>...</Expression>
<Statement>...</Statement>
<Statement>
<Block>
<BlockStatement>
<IfStatement>...
For the pattern you do want
if (true) {
String a;
} else if (true) {
String b;
}
The tree looks like:
<IfStatement>
<Expression>...</Expression>
<Statement>...</Statement>
<Statement>
<IfStatement>...
In PMD 4 (which I used to make these trees), you write a rule by writing a XPath expression matching the pattern you don't want to occur.

Using || in while loop

This is only sample code.My point is to make: 'If Hello OR foo word is found, do something'.But while loop does not react, even if both strings are in text.If I use only one condition without || while loop does what I expect.How cant I fix this? Thank you!
public void start(){
Document doc=Jsoup.connect("http://www.yahoo.com").get();
String text=doc.text();
while(!text.contains("Hello")||!text.contains("foo"))
System.out.println("Not found.");
}
}
You have some operator precendence issues.
Right now, you're saying if text doesn't contain hello OR it doesn't contain foo do the loop; Use
while(!text.contains("Hello")&&!text.contains("foo"))
instead. This means "if text doesn't contain hello AND doesn't contain foo repeatedly flood System.out with "not found" until the user kills your program or the JVM dies".
You should change your code as follows
while(!text.contains("Hello")&&!text.contains("foo"))
System.out.println("Not found.");
}
}
You can also do:
while(!(text.contains("Hello") || text.contains("foo"))){...}
Maybe it's what you were trying to do above.

'String Index out of Range' Error Message in Java using charAt

Recently, while coding I came upon the following error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 0
at java.lang.String.charAt(String.java:686)
at TestAssign2.main(TestAssign2.java:119)
The error appears when I add the line - firstLetter=userName.charAt(0); to the code and program displays the error message after the user enters all the values asked. Before this line was entered, it all worked fine.
while(uProgStart.equals(PROGSTART))
{
System.out.println("What is your name?");
userName=sc.nextLine();
junk = sc.nextLine();
System.out.println("What is the year of your birth?");
birthYear = sc.nextInt();
junk = sc.nextLine();
System.out.println("What is the date of your birth? (dd.mm)");
birthDDMM = sc.nextDouble();
junk = sc.nextLine();
day=(int)birthDDMM;
month=(int)Math.round(100*birthDDMM)%100;
//Begins calculation of Dss Score
if(birthYear%CYCLE_LENGTH!=SNAKE_YEAR)
{
DssScore=DssScore+1;
}
if(month<SPRING_BEGINNING||month>SPRING_END)
{
DssScore=DssScore+2;
}
firstLetter=userName.charAt(0);
if(firstLetter==(LOWER_S)||firstLetter==(UPPER_S))
{
DssScore=DssScore+4;
}
The idea of the line was to see if the name entered by the user begins with either the letter 's' or 'S'.
All the variables have been declared, I just haven't included them for the sake of keeping this post a little succinct.
I think you are pressing enter key by mistake without giving a chance to enter any input and it forces username variable be empty. I reproduced this error like mentioned above.Sometime when you deal with scanner, it happens like that.
So in your code, check whether the username is null or not before doing any operation.
The call to sc.nextLine() for assigning userName prior to the charAt call likely returns an empty string (eg. if you scan a blank line).
You may want to use if to make sure that the next line really exists.
Something like this:
if(sc.hasNextLine()) {
userName = sc.nextLine()
} else {
System.out.println("OMG... Where is my line?")
}
This most likely not a good fix for your problem, but based on the limited information we have it's difficult to suggest anything better.
The real problem is most likely elsewhere in your logic.

android getInputType in JAVA code

I defined a EditText in XML with attribute android:inputType="numberSigned", so, when I try to get it in Java Code like:
int type = mEditText.getInputType();
switch(type){
case InputType.TYPE_NUMBER_FLAG_SIGNED:
//do when I get EditText defined with 'numberSinged'
//do something
break;
}
But, It doesn't work for me. So I try to check Android source code, TYPE_NUMBER_FLAG_SIGNED=4096. When I try to print println(mEditText.getInputType()),it turns to be 4098. And I can't find any variable equals 4098.
Can anybody tell me the reason?
I'm not good at English, may you can understand me! Thanks!
there can be multiple flags assigned to inputType. To find out if a flag is set or not, use the bitwise AND (&) operator:
int type = mEditText.getInputType();
if((type & InputType.TYPE_NUMBER_FLAG_SIGNED) > 0)
{
// your stuff here
}
I guess, the usage of switch case is not possible here.
TYPE_NUMBER_FLAG_SIGNED Constant Value: 4096 (0x00001000) .
get more information here

Can I strictly evaluate a boolean expression stored as a string in Java?

I would like to be able to evaluate an boolean expression stored as a string, like the following:
"hello" == "goodbye" && 100 < 101
I know that there are tons of questions like this on SO already, but I'm asking this one because I've tried the most common answer to this question, BeanShell, and it allows for the evaluation of statements like this one
"hello" == 100
with no trouble at all. Does anyone know of a FOSS parser that throws errors for things like operand mismatch? Or is there a setting in BeanShell that will help me out? I've already tried Interpreter.setStrictJava(true).
For completeness sake, here's the code that I'm using currently:
Interpreter interpreter = new Interpreter();
interpreter.setStrictJava(true);
String testableCondition = "100 == \"hello\"";
try {
interpreter.eval("boolean result = ("+ testableCondition + ")");
System.out.println("result: "+interpreter.get("result"));
if(interpreter.get("result") == null){
throw new ValidationFailure("Result was null");
}
} catch (EvalError e) {
e.printStackTrace();
throw new ValidationFailure("Eval error while parsing the condition");
}
Edit:
The code I have currently returns this output
result: false
without error. What I would like it to do is throw an EvalError or something letting me know that there were mismatched operands.
In Java 6, you can dynamically invoke the compiler, as explained in this article:
http://www.ibm.com/developerworks/java/library/j-jcomp/index.html
You could use this to dynamically compile your expression into a Java class, which will throw type errors if you try to compare a string to a number.
Try the eval project
Use Janino! http://docs.codehaus.org/display/JANINO/Home
Its like eval for java
MVEL would also be useful
http://mvel.codehaus.org/
one line of code to do the evaluation in most cases:
Object result = MVEL.eval(expression, rootObj);
"rootObj" could be null, but if it's supplied you can refer to properties and methods on it without qualificiation. ie. "id" or "calculateSomething()".
You can try with http://groovy.codehaus.org/api/groovy/util/Eval.html if groovy is an option.

Categories

Resources