This may sound silly but I couldn't find an answer by googling it.
When using a for loop in it's simplest form I can add conditions to break the loop in the for statement. example:
for(int i=0; i<100 && condition2 && condition3; i++){
//do stuff
}
When using an object for loop like this:
for(String s:string_table){
//do stuff
}
how can i add a condition to break the loop? I'm talking about adding conditions in the for statement. I know I can add the condition inside //do stuff part and break from there.
You cannot do that you have to go by putting the if statements in the for loop.
You cannot add anything else to the () part of the "enhanced for" statement. JLS ยง 14.14.2:
The enhanced for statement has the form:
for ( FormalParameter : Expression ) Statement
The type of the Expression must be Iterable or an array type.
(The "FormalParameter" means a variable declaration.)
The break; statement is the only way:
for (String s : string_table) {
if (condition) break;
// ...
}
Related
I'm trying to create a programme like this previous one I've made;
It simply gives a boolean true/false on if a string backwards is still spelt the same way.
I've created this using if statements, but would like too know if it is possible too create using only methods and loops, and if so how? I have looked for duplicates, and there are similar posts that achieve what I have below, but everything I find uses if else statements
Any help appreciated as always; thanks.
import java.util.*;
public class testingthingsv24 {
private static Scanner in;
public static void main(String args[])
{
in = new Scanner(System.in);
System.out.println("Please Enter Your String: ");
String n=in.nextLine();
System.out.println("Your String Was: "+n);
StringBuffer str=new StringBuffer(n);
StringBuffer str2=new StringBuffer(str.reverse());
String s2=new String(str2);
System.out.println("Reversed Is: "+str2);
if(n.equals(s2))
System.out.println("ITS A PALINDROME");
else
System.out.println("ITS NOT A PALINDROME");
}
}
Output:
Please Enter Your String:
dad
Your String Was: dad
Reversed Is: dad
ITS A PALINDROME
To test a result, generally a conditional statement (if, ternary or switch) appears useful.
You have to avoid using conditional statements as these conditions are annoying by making your code not readable, brittle, error prone, etc..
To do that, you have to favor abstraction over sequential logic.
In your simple case, you could for example introduce a structure (key-value) that associate each boolean value to the String message.
Map<Boolean, String> messageByBoolean = new HashMap<>();
messageByBoolean.put(true, "ITS A PALINDROME");
messageByBoolean.put(false, "ITS NOT A PALINDROME");
...
System.out.println(messageByBoolean.get(n.equals(s2));
But does it make really sense ? It looks like an overhead as you have just two possibilities.
With 5 or 10 of them, it would make much sense.
would like too know if it is possible too create using only methods and loops, and if so how?
Sure. The if statement is redundant in Java. There are plenty of other conditionals in the language, and there are multiple ways that you could implement the semantics of an if statement (including an else clause, if desired) without actually using an if statement.
For example, you can always replace
if (condition) {
// statements when true ...
} else {
// statements when false ...
}
with
if_replacement: do {
while (condition) {
// statements when true ...
break if_replacement;
}
// statements when false ...
} while (false);
Note that that has no association whatever with any particular problem, and that it uses only looping constructs. A somewhat simpler form is possible if you don't need the analog of an else block. In principle you could replace every if in any program with a construct of this form.
This can't really be achieved any more efficiently (as in using a method or function). The reason is that the if-statement:
if (n.equals(s2))
System.out.println("ITS A PALINDROME");
else
System.out.println("ITS NOT A PALINDROME");
at the processor level would simply evaluate the statement: n.equals(s2) and then switch to the first println if true else go to the second println. If you think about this, there isn't really any optimisation that you can do as this condition will always have to be evaluated and always have to carry out the necessary task (printing).
However, having said that this is the most optimised solution for this part of your code, you can make the code slightly shorted and less bulky without a big if-else.
And to do that, the best solution IMO would be #shmosel's with a ternary expression. This would replace this if-else block with a simple line:
System.out.println(n.equals(s2) ? "ITS A PALINDROME" : "ITS NOT A PALINDROME");
This works due to the general format of a ternary statement:
condition ? task if true : task if false
Can be done with recursion too
boolean isPalindrome (String s) {
return s.length() < 2 ? true : s.charAt(0) == s.charAt(s.length() - 1) && isPalindrome(s.substring(1,s.length() - 1));
}
First of all, I apologize for this unclear title!
So I am making an app, and I have an if statement :
if(num.contains(input) )
{
...
}
So, say num is 213, and input is 1, it will still execute the the block inside the statement.
But I want to make an if statement that only executes when num starts with input, and the other characters after 1 don't matter.
Note:
All variables are Strings
you can use startsWith()
num.startsWith(input)
Here is something for your reference :-
https://www.tutorialspoint.com/java/java_string_startswith.htm
maybe convert it to a string and see if the index of input is in the string at the very front.
if(String.valueOf(num).indexOf(String.valueOf(input))==0){
//do stuff
}
edit:
If the variables are strings you can just check the index of input in num
if(num.indexOf(input)==0){
//do stuff
}
I have a question associated with curly braces in switch-case block
switch( conditon ) {
case val1: {
// something
}
break;
case val2: {
// something
}
break;
default:
break;
}
or something like this:
switch( conditon ) {
case val1: {
// something
break;
}
case val2: {
// something
break;
}
default:
break;
}
A I know both codes should work the same way but I think there is some irrationalities here. As the break should cause jumping out from curly braces block so theoretically second code should do smoothen like this:
1. break course jumping out of block
2. switch continues execution case val2 or default cause outside the braces there isn't any break statement.
Which version you recommend to use and Are they really working the same way?
Try this:
{
System.out.println("A");
break;
System.out.println("B");
}
You'll see
$ javac Y.java
Y.java:35: error: break outside switch or loop
break;
^
1 error
This means: you can't use it in a block, it has no effect in combination with a block.
I would not put the break outside the block, but I've never seen coding rules demanding either way (and you could put up arguments for both sides). Maybe this is because blocks aren't used very frequently to separate visibility per switch branches.
Curly braces limit the scope of variables. And have no effect on flow control other than if, for, while, switch.. blocks, except for the cases where they're optional
The following code:
boolean continue = false;
Returns the following error:
error: not a statement
boolean continue = false;
^
Why is this happening? I am pretty familiar with booleans.
Try this instead:
boolean cont = false;
Or use another name. The point is that in Java, continue is a keyword and it can't be used as a variable name - it's right here in the language specification. For future reference this is what continue is used for:
The continue statement skips the current iteration of a for, while, or do-while loop. The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop.
You can't use continue as a name of a variable. It's one of java reserved words.
You cannot use continue as a variable name because it is a reserved word.
From the docs:
The continue statement skips the current iteration of a for, while, or do-while loop. The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop.
You can tell that it is a keyword because, when you look at your question, continue has syntax highlighting applied, like boolean and false.
boolean continue = false;
That would be like writing
boolean boolean = false;
or
boolean false = false;
Both of those obviously won't work, so try something else like continuing:
boolean continuing = false;
I want to break a while loop of the format below which has an if statement. If that if statement is true, the while loop also must break. Any help would be appreciated.
while(something.hasnext()) {
do something...
if(contains something to process){
do something
break if condition and while loop
}
}
The break keyword does exactly that. Here is a contrived example:
public static void main(String[] args) {
int i = 0;
while (i++ < 10) {
if (i == 5) break;
}
System.out.println(i); //prints 5
}
If you were actually using nested loops, you would be able to use labels.
An "if" is not a loop. Just use the break inside the "if" and it will break out of the "while".
If you ever need to use genuine nested loops, Java has the concept of a labeled break. You can put a label before a loop, and then use the name of the label is the argument to break. It will break outside of the labeled loop.
while(something.hasnext())
do something...
if(contains something to process){
do something...
break;
}
}
Just use the break statement;
For eg:this just prints "Breaking..."
while (true) {
if (true) {
System.out.println("Breaking...");
break;
}
System.out.println("Did this print?");
}