Is there any goto statement in Java? [duplicate] - java

This question already has answers here:
Is there a goto statement in Java?
(23 answers)
Closed 9 years ago.
I wrote a program in C++ with some goto statements. Now, I need to write the same program in Java. Is there any goto option in Java? If so, how it can be implemented? Is it same as the C++?
My program is:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,k,w,l,q,d;
clrscr();
printf("\nEnter the limit:");
scanf("%d",&k);
for(i = 13; i <= k ; i++)
{
repeat:
j = i%10;
if (j != 0)
{
if(i < 99)
{
for(w = 1; w <= 9; w++)
{
l = 11*w;
if (l == i){
i++;
goto repeat;
}
}
}
if(i > 99)
{
for(q = 1; q<=9 ; q++)
{
d = 111*q;
if (d == i){
i++;
goto repeat;
}
}
}
printf("%d,",i);
}
}
getch();
}

No, Java does not have a goto operator, by design. It's considered harmful.
Your code could be rewritten with continue repeat in place of the goto repeat, if the repeat: label was placed just before the for loop.
E.g.
repeat: for(i=13;i<=k;i++)
and then
continue repeat;
instead of goto repeat

No Java doesn't have goto in active state (but in reserved state). You cannot use it in your program for now (it's a reserved keyword).
And avoid using it in C++ either. You can write your program using smartly placed continue and/or break for both the languages.

Short answer, No.
You can also refer this question

Although goto is a reserved word in Java it is not used in the Java language. But there is a label, an identifier that can be used in conjunction with the break or continue. The purpose of the label it to let an iteration to jump outside of the iteration, it is a bit like goto statement.
Code:
labelA:
// some loop {
continue labelA;
}

I wrote a program in C++ with some goto statements.
No, you didn't. C++ requires that main() returns int, and <stdio.h> is a C library (and conio.h a platform-specific C library). In C++, we spell it <cstdio>, and we don't normally use it anyway (because <iostream> is much more powerful and type-safe). However, your program is valid C.
Now,i need it to write the same program in java.
Good heavens, why? To the extent that I can figure out what your program is actually intended to do, it isn't anything useful at all. If this is for homework, your teacher is doing an incredibly bad job of explaining good coding style, from what I can see.
Is there any goto option in java ?
No, goto is not implemented in Java. They did this because you don't have a reason to use it. No, really. The fact that it's all over the Linux kernel doesn't mean you have a reason. (It doesn't mean they have a real reason, either.)
Your program can be written more simply, for example:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,k,w,l,q,d;
clrscr();
printf("\nEnter the limit:");
scanf("%d",&k);
for(i=13;i<=k;i++)
{
j=i%10;
if (j == 0) continue;
if (i<99)
{
for(w=1;w<=9;w++)
{
l=11*w;
if (l==i) continue;
}
}
else
{
for(q=1;q<=9;q++)
{
d=111*q;
if(d==i) continue;
}
}
printf("%d,",i);
}
getch();
}
And the same basic approach will work in Java, too.
Although you really need to work on several other style issues. Please try to use real variable names, and restrict variable scope.

I do condone the use of goto on occasion. This is not one of those occasions. This particular problem can be solved without any kind of goto (break and continue are a goto, just a restricted form).
#include <iostream>
int main()
{
unsigned int lim;
std::cout << "Enter the limit: ";
std::cin >> lim;
std::cout << "\n";
if (lim > 999) {
std::cout << lim << " is too large. Truncating to 999.\n";
lim = 999;
}
// Why start at 13? Oh well.
for (unsigned int ii=13; ii <= lim; ii++) {
if (((ii % 10) != 0) &&
((ii < 100) ? (ii % 11) != 0 : (ii % 111 != 0))) {
std::cout << ii << ",";
}
}
std::cout << "\n";
return 0;
}
There are times where the clearest way to write a chunk of code involves break or continue. There are times where the clearest way to write a chunk of code involves a multi-level break or continue. While Java does provide such a mechanism, neither C nor C++ does.
As I said at the onset, I do condone the use of goto on occasion. The occasions are very, very rare:
To emulate a multi-level break or continue when that truly is the clearest way to write the code.
To deal with errors in a stupid programming environment that mandates single point of entry, single point of return.
To deal with errors in a programming environment that makes try, catch, and throw forbidden keywords.
To implement a finite state machine (but a loop around a switch usually quite nicely in this case).

You can do anything with label that you could do with goto. Labels as an Anti-Pattern This doesn't make it a good idea.
What you are trying to do here doesn't need nested loops which avoids the need to use labels at all.
Scanner in = new Scanner(System.in);
System.out.print("\nEnter the limit:");
int limit = in.nextInt();
for (int i = 12; i <= limit; i++) {
if (i % 10 == 0) continue;
if (i <= 99) {
// two digits the same.
if (i % 10 == i / 10 % 10) continue;
} else if (i <= 999) {
// three digits the same.
if (i % 10 == i / 10 % 10 && i % 10 == i / 100) continue;
} else {
System.err.println("Value " + i + " too large to check");
break;
}
System.out.printf("%d,", i);
}

Related

The code showing Time Limit Exceed erroe, could some one explain, where is problem in this code [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last year.
Improve this question
LeetCode 485
Given a binary array nums, return the maximum number of consecutive 1's in the array.
Example 1:
Input: nums = [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
---------Solution:-------
public int findMaxConsecutiveOnes(int[] nums) {
int maxConsSize = Integer.MIN_VALUE;
int i = -1, j=-1, k=0;
while(k<nums.length){
while(k<nums.length && nums[k] == 1){
k++;
i++;
}
if(nums[k] == 0){
maxConsSize = Math.max(maxConsSize,i-j);
j = i;
}
}
maxConsSize = Math.max(maxConsSize,i-j);
return maxConsSize;
}
Warning: This is not direct answer (for this "do my homework" question)
You should use (or learn to use) debugger in your IDE (trust me, IDE, e.g. Eclipse will help you a lot in your beginnings).
The easiest (I'm not saying smartest) way, how to know what the program is doing (when you need to know, like in this case) is to add some print statements, e.g. add System.out.println("k=" + k) into your program (in a while loop).
You might want to watch this youtube video.
You have an infinity loop. Try run this:
public class Test {
public static void main(String[] args) {
int maxConsSize = Integer.MIN_VALUE;
int[] nums = {1,1,0,1,1,1};
int i = -1, j=-1, k=0;
System.out.println(nums.length);
while(k<nums.length){
while(k<nums.length && nums[k] == 1){
k++;
i++;
System.out.println("k = " + k);
}
if(nums[k] == 0){
maxConsSize = Math.max(maxConsSize,i-j);
j = i;
}
}
maxConsSize = Math.max(maxConsSize,i-j);
System.out.println(maxConsSize);
}
}
Output:
6
k = 1
k = 2
After reading the first 0 you are in infinite loop. You have made this task very complicated :)
It's probably not the best solution, but it should be faster
public int findMaxConsecutiveOnes(int[] nums) {
int maxCons = 0;
int currentCons = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
if (currentCons > maxCons) {
maxCons = currentCons;
}
currentCons = 0;
} else {
currentCons++;
}
}
if (currentCons > maxCons) {
maxCons = currentCons;
}
return maxCons;
}
}
There are two basic forms of loops:
for-each, for-i or sometimes called ranged for
Use that for a countable number of iterations.
For example having an array or collection to loop through.
while and do-while (like until-loops in other programming languages)
Use that for something that has a dynamic exit-condition. Bears the risk for infinite-loops!
Your issue: infinite loop
You used the second form of a while for a typical use-case of the first. When iterating over an array, you would be better to use any kind of for loop.
The second bears always the risk of infinite-loops, without having a proper exit-condition, or when the exit-condition is not fulfilled (logical bug). The first is risk-free in that regard.
Recommendation to solve
Would recommend to start with a for-i here:
// called for-i because the first iterator-variable is usually i
for(int i=0; i < nums.length, i++) {
// do something with num[i]
System.out.println(num[i]):
}
because:
it is safer, no risk of infinite-loop
the iterations can be recognized from the first line (better readability)
no counting, etc. inside the loop-body
Even simpler and idiomatic pattern is actually to use a for each:
for(int n : nums) {
// do something with n
System.out.println(n):
}
because:
it is safer, no risk of infinite-loop
the iterations can be recognized from the first line (better readability)
no index required, suitable for arrays or lists
no counting at all
See also:
Java For Loop, For-Each Loop, While, Do-While Loop (ULTIMATE GUIDE), an in-depth tutorial covering all about loops in Java, including concepts, terminology, examples, risks

Beginner Boolean compiling error

I am very new to Java (doing a beginners university module) so sorry for the probably silly question. I am trying to verify whether a ragged array is a 'tridiagonal matrix'.
It is valid if it is of length 3 at the first level and of length n − 1, n, and n − 1 at the second level. I intended to come up with a code to firstly verify the length is 3, then find the longest length array within it for n, then finally verify each length.
For whatever reason my code won't compile but I'm not seeing an error message, just a red exclamation mark on the class. I assume this means there are multiple errors. If anyone could point them out it would be a massive help.
static boolean isValidTridiagonal ( double [][] m)
{
if (double [][]=new double [3][])
{
int n = 0;
for(int i = 0; i < m.length; i++)
{
if(m[i].length > n)
{
n = m[i].length;
if( (m[0].length = n-1) && (m[1].length = n) &&(m[2].length=n-1))
{
return true
}
else
{
return false
}
}
else
{
return false
}
}
Thanks very much!
I agree with Foolish in the comments that it's helpful to use an IDE that can highlight syntax errors and other problems with the code, it really makes a huge difference. Apart from that, another general strategy is to always code in "baby steps": do only the minimal thing to test if the code works, compile and test often. And if you still have troubles, you can always comment out chunks of your code when searching for the offending bits.
Having said that, the errors that I see in your code are:
if (double [][]=new double[3][])
If you want to test the length of the input, you can do if (m.length == 3)
In
if( (m[0].length = n-1) && (m[1].length = n) &&(m[2].length=n-1))
you're not testing for equality, but rather trying to put the values n-1 etc into m[0].length, which is not going to work. What you probably meant was
if( (m[0].length == n-1) && (m[1].length == n) &&(m[2].length==n-1))
In
return true
you're missing a semicolon. The compiler is whiny about things like that and unless you use an IDE or learn to interpret the compiler error messages, it can be really painful to find such errors.
Finally, of course, the answer by vasste provides a much simpler solution to your actual task, so it's worth looking into that :).
Why do you need all that loops? If all arrays cannot be null, than
static boolean isValidTridiagonal(double[][] m) {
return m.length == 3 && m[0].length == m[1].length - 1 && m[2].length == m[0].length;
}
You're missing a few braces at the end but, judging from your indentation, you just forgot to copy them.
You're missing semicolons from the end of the return lines.
The condition within this if statement if (double [][] = new double [3][]) is not a valid expression. You simply want to evaluate the length, which you can do like if (m.length == 3). You did the same thing later on.
The line including (m[0].length = n-1) && (m[1].length = n) && (m[2].length=n-1) is not valid because you are performing assignment (=) in all three cases. An equality check is the double equals operator ==.
You do not return a value in every case. You can fix this by adding return false; after the closing brace of your first if statement, i.e. the last line of the function.
This is enough to get your code to compile. As mentioned in another answer though, your logic is confusing and without actually tracing it through I would speculate that it will not work as you would expect.
If I have understood your requirements correctly, you can rewrite the entire function as:
static boolean isValidTridiagonal ( double [][] m)
{
return m.length == 3 &&
m[0].length + 1 == m[1].length &&
m[2].length + 1 == m[1].length;
}
A proper IDE - Netbeans, Eclipse, etc. - will give you fairly descriptive error messages to show you where you've gone wrong.
This is basically completely stylistic but I wish someone had pointed this out to me earlier. If you ever find yourself writing code in this form:
if( (m[0].length == n-1) && (m[1].length == n) && (m[2].length == n-1))
{
return true;
}
else
{
return false;
}
know that you can save yourself so many lines without losing any readability by instead writing:
return (m[0].length == n-1) && (m[1].length == n) && (m[2].length == n-1);

dex2jar and JD-GUI label statements

I used dex2jar to get jar from an apk and to view it used JD-GUI .
But I notice there are label symbols such as following,
if (this.data.length != 7)
break label279;
// more code here
label279: short[] aos = { 0, 0 };
is it something added by compiler(or Obfuscate) ? is there any other tool that could use to avoid these labels?
If found this
https://code.google.com/p/dex2jar/source/browse/dex-ir/src/main/java/com/googlecode/dex2jar/ir/ts/CleanLabel.java?r=e8b872fdfce8a5a39aa7df083c46ec724fa8d3f4
is it something relate for this cleaning ?
Further research:
if (Math.abs(k) > this.mMaxRotationAngle)
if (k >= 0)
break label100;
label100: for (k = -this.mMaxRotationAngle; ; k = this.mMaxRotationAngle)
{
transformImageBitmap((ImageView)paramView, paramTransformation, k);
break;
}
From the above code by natural observation I changed the code to :
if (Math.abs(k) > this.mMaxRotationAngle)
// label100:
for (k = -this.mMaxRotationAngle; ; k = this.mMaxRotationAngle)
{
if (k >= 0)
break;// label100;
transformImageBitmap((ImageView)paramView, paramTransformation, k);
// break;
}
Still the label100 remains as a mystery... Wondering how does dex2jar handles the situations when it is unaware of the code.
the existence of : operator also suggests that there might be a for each loop
If at some point in future this mystery is resolved then please notify me too.
thanks.

Greater than and less than in one statement

I was wondering, do you have a neat way of doing this ?
if(orderBean.getFiles().size() > 0 && orderBean.getFiles().size() < 5)
without declaring a variable that is not needed anywhere else ?
int filesCount = orderBean.getFiles().size();
if(filesCount > 0 && filesCount < 5) {
I mean, in for loop we are "declaring conditions" for the actual iteration, one can declare a variable and then specify the conditions. Here one can't do it, and neither can do something like
if(5 > orderBean.getFiles().size() > 0)
Simple utility method:
public static boolean isBetween(int value, int min, int max)
{
return((value > min) && (value < max));
}
Several third-party libraries have classes encapsulating the concept of a range, such as Apache commons-lang's Range (and subclasses).
Using classes such as this you could express your constraint similar to:
if (new IntRange(0, 5).contains(orderBean.getFiles().size())
// (though actually Apache's Range is INclusive, so it'd be new Range(1, 4) - meh
with the added bonus that the range object could be defined as a constant value elsewhere in the class.
However, without pulling in other libraries and using their classes, Java's strong syntax means you can't massage the language itself to provide this feature nicely. And (in my own opinion), pulling in a third party library just for this small amount of syntactic sugar isn't worth it.
If getFiles() returns a java.util.Collection, !getFiles().isEmpty() && size<5 can be OK.
On the other hand, unless you encapsulate the container which provides method such as boolean sizeBetween(int min, int max).
This is one ugly way to do this. I would just use a local variable.
EDIT: If size() > 0 as well.
if (orderBean.getFiles().size() + Integer.MIN_VALUE-1 < Integer.MIN_VALUE + 5-1)
java is not python.
you can't do anything like this
if(0 < i < 5) or if(i in range(0,6))
you mentioned the easiest way :
int i = getFilesSize();
if(0 < i && i < 5){
//operations
}
of
if(0 < i){
if(i < 5){
//operations
}
}
If this is really bothering you, why not write your own method isBetween(orderBean.getFiles().size(),0,5)?
Another option is to use isEmpty as it is a tad clearer:
if(!orderBean.getFiles().isEmpty() && orderBean.getFiles().size() < 5)
Please just write a static method somewhere and write:
if( isSizeBetween(orderBean.getFiles(), 0, 5) ){
// do your stuff
}
Nowadays you can use lodash:
var x = 1;
var y = 5;
var z = 3;
_.inRange(z,x,y);
//results true

Python Program converted into Java

Sooo I started taking my second computer science class ever! For my first class we used python and for this class we're using Java. Our first assignment (pretty much just practice) is to convert this craps program from Python to Java and I'm just having a hell of a time.
Could someone please help with what I've done and umm give me some advice? Maybe a good site for a beginner.... Someone that kinda knows Python (only from a first CS course perspective).
1) In python
def winCraps():
roll = rollDice()
if roll == 7 or roll == 11:
return True
elif roll == 2 or roll == 3 or roll == 12:
return False
else:
return rollForPoint(roll)
This is my attempt at the conversion of it over to java
public int winCraps{
roll = rollDice();
if (roll = 7 && 11){
return (true);
}
else (roll =2 && 3 && 12){
return(false);
}
else{
return rollforPoint(roll);
}
}
2) Python
def rollDice():
raw_input("Press <Enter> to roll...")
die1 = randrange(1,7)
die2 = randrange(1,7)
sum = die1 + die2
print "You rolled", die1, "+", die2, "=", sum
return sum
This one confused the hell out of me. What would randrange be in Java??
Java
static int rollDice(){
System.out.print("Press <Enter> to roll...");
double die1 = Math.random();
double die2 = Math.random();
die1 = (int) die1*6+1;
die2 = (int) die2*6+1;
int sum = (int)die1 + (int)die2;
System.out.println("You rolled "+die1+ " + "+die2+ " = "+sum+".");
return sum;
}
*please bear in mind that I'm just learning this stuff lol
You need to fix your if statements the "==" operator checks for equality, and you must put the variable you are checking against in each section of the statement.
public int winCraps{
roll = rollDice();
if (roll == 7 || roll == 11) {
return true;
}
else if(roll == 2 || roll == 3 || roll == 12) {
return false;
}
else{
return rollforPoint(roll);
}
}
In you rollDice() method, the way you assign values to each die is incorrect. I recommend reading up on random numbers (since this is homework, I'll leave that to you).
Also, remember in java you must always end each statement with a semicolon
What would randrange be in Java?
You can get a random integer in a specific range from Java's Random class by calling the nextInt(int n) method. For example,
Random rand = new Random();
int a = rand.nextInt(7);
will give you a random integer >= 0 and < 7. This isn't exactly the same as randrange in Python, but you could use it as the index to an array of objects, or as the value of a roll of a single die.
Randrange can be replaced by methods in java.util.Random. Like Python, Java has an extensive standard library which you should reference.
1) In Java "OR" operator is "||" not "&&" and comparison operator is "==" as in Python
So
if roll == 7 or roll == 11:
Should be
if( roll == 7 || roll == 11 ) {
and not
if( roll = 7 && 11 ){
2) randrange is : random generator from there you can search: Random in Java
Which will lead you to something like: Random.nextInt()
Use this algorithm ( a) search Internet for Python function, b) understand what it does c) search it in java ) for the next assignment you have and you're done.
You can always ask here again, that's what this site is all about after all
I'd recommend that you look up the docs on randrange(). Once you know exactly what it does, google for the those keywords, plus the word Java.
One thing you'll quickly discover in working with languages is that the APIs can be very different. There might not be an equivalent of randrange in Java, but you might be able to find two or three functions that you can combine to do the same thing.
System.out.print isn't going to cause the system to wait for someone to hit the enter key. For that, you need to do something with System.in, most likely System.in.read(), as it blocks while waiting for input.
Also, in Java, a program starts executing with the main method. To be exact, an executable class starts something like this:
// You'll need the Random class, as per other answers
import java.util.Random;
// assuming WinCraps is the class name
public class WinCraps {
// args in this example is a string array of command-line arguments
public static void main(String[] args) {
// This is where your main method (that calls winCraps?) would be
}
// Other methods
}
Also, any method in this class called directly from main must also be static.
Write out in English what the Python program does. Go through it line by line and explain to yourself what computations are evoked, in other words...what is happening?
Afterwards, write the Java program from that description.
Never ever try to convert the text of a program from one language to another. You'll run into a LOT of problems that way because every language is different, no matter how similar they look.
One major error in your first program that you have in the Java conversion is the conditionals.
Something like (roll =2 && 3 && 12) assigns 2 to roll and then applies AND operators. You also forgot the if. You have elseif in Python.
You want something like:
else if(roll==2 || roll==3 || roll==12)
As for random numbers, there is a function for that in Java.

Categories