0

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();
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pari Sairam Mohan
  • 421
  • 1
  • 4
  • 11
  • 3
    I don't think you needed to include a code example in this question; everyone knows what a goto is. – David Grayson Jul 08 '11 at 06:47
  • 1
    Take a note that using `goto` is considered very bad practice. Also, `main()` should return int, not void. – BЈовић Jul 08 '11 at 06:47
  • If you use Java and want to add a `goto`, use multiple inheritance or a few other things, it only means one thing: you're thinking wrong and taking the problem the wrong way. And anyway, whatever the language might be, `goto` is a bad way to do things, it might cause terrible bugs that could allow half-loops and other very unpleasant surprises. – SteeveDroz Jul 08 '11 at 06:50
  • You could do with some refactoring. I have no idea what this program does. – Thorbjørn Ravn Andersen Jul 08 '11 at 06:56
  • @VJo: Although there is a significance of the return value of `main()`, its not compulsory for `main()` to return `int`. When the program is standalone and the return type is not relevant, a return type of `void` can be used... Please correct me if I am wrong! – Mahendra Liya Jul 08 '11 at 07:11
  • @mahi: It is compulsory for main() to return an int. One particular compiler than comes from Redmond, WA allows this non-standard `void main()` nonsense. It is nonsense. – David Hammen Jul 08 '11 at 07:56
  • 1
    This is, in many ways, not a C++ program. – Karl Knechtel Jul 08 '11 at 08:17
  • @mahl You would be surprised if you had the access to the c++ standard. Read for example this question : http://stackoverflow.com/questions/204476/what-should-main-return-in-c-c – BЈовић Jul 08 '11 at 08:34
  • @Pari, You start at 13. When the limit is also match, it will print the number after the limit. e.g. if the limit is 22 it will print 23. This will accept every value over 999 which is not a multiple of ten. Is this behaviour intended? – Peter Lawrey Jul 08 '11 at 09:03
  • Sounds like this person has the same homework http://stackoverflow.com/questions/6620295/how-to-generate-random-numbers-with-restrictions-on-like-numbers-and-powers-of-te – Peter Lawrey Jul 08 '11 at 09:12

7 Answers7

6

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

Theo
  • 131,503
  • 21
  • 160
  • 205
  • 2
    There is nothing like `continue repeat;` It's just `continue`. – iammilind Jul 08 '11 at 06:52
  • Why goto's considered harmful: http://david.tribble.com/text/goto.html – Tobias Langner Jul 08 '11 at 06:54
  • 6
    @iammilind, yes there is. It allows to `continue` _further_ out than the innermost loop. http://www.java2s.com/Tutorial/Java/0080__Statement-Control/CalculatingPrimesusingcontinuestatementandlabel.htm – Thorbjørn Ravn Andersen Jul 08 '11 at 06:55
  • 4
    @iammilind, I beg to differ. http://download.oracle.com/javase/tutorial/java/nutsandbolts/branch.html search for "continue test". – Theo Jul 08 '11 at 06:56
  • @Theo, you wrote, `Your code could be rewritten with continue repeat`; I considered that in C++ context. Ok, I will take back the downvote. – iammilind Jul 08 '11 at 07:02
  • That C and C++ do not have a way to break/continue out of a multiply nested loop is one of the still-condoned uses of `goto` in C/C++. Java has such a construct; there is no need for this particular still-condoned use of `goto` in C and C++. – David Hammen Jul 08 '11 at 07:18
  • I tried to use continue. But it gives a error- not a loop label: myLable. Does continue works only for loops? – Sachin Mhetre Apr 17 '12 at 10:47
  • Yes, it's not a general `goto` feature. You need to put the label before a loop, like `repeat: for (...)` – Theo Apr 17 '12 at 17:29
3

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.

iammilind
  • 68,093
  • 33
  • 169
  • 336
  • Not in this case. There is a `goto`less construct in Java that would enable the author to accomplish what they want, but not in C/C++. The only choices are kludgy flags, which many see as being worse than `goto`, or a well-constrained `goto`, which many see as being better than those kludgy flags. – David Hammen Jul 08 '11 at 07:22
  • 1
    @David this is not actually the case here. The purpose of the gotos is to simply abort the current iteration of the loop so that the `printf` statement at the end isn't reached. This naturally translates using `continue`. Unless of course the OP **intends** to perform one more iteration of the loop in the case that `k` is ever equal to `l` or `d`... – Karl Knechtel Jul 08 '11 at 08:23
  • That is the case here, and I was also alluding to the general case. The general case is to break out of or continue some outer loop. That is exactly how the OP is using goto here. This could be implemented directly in Java by substituting the goto statements with Java continue statements (which optionally take a label as an argument). C/C++ break and continue do not take an argument; they only apply to the innermost loop. – David Hammen Jul 08 '11 at 09:22
  • What's the difference between `goto` and `continue` or `break` (other than at the end of a `case`)? They all break logical program flow, and make it more difficult to reason about things like loop invariants and such. (Of course, if the function is large enough for it to make a significant difference, it is too large. Which one could also formulate as: if the function is large enough that you're tempted to use any of these, it is too large.) – James Kanze Jul 08 '11 at 09:30
1

Short answer, No.

You can also refer this question

Community
  • 1
  • 1
chedine
  • 2,384
  • 3
  • 19
  • 24
1

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;
}
Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
Rupok
  • 2,062
  • 16
  • 16
1

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.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • This does not do the same thing that the OP's program does. The OP's program omits printing numbers that are a multiple of 10, 2 digit numbers that are a multiple of 11, and 3 digit numbers that are a multiple of 111. – David Hammen Jul 08 '11 at 09:35
  • Ah, I see, the `continue`s are currently in inner for-loops. Careless of me. Probably comes from not writing useless nonsense like this normally :) – Karl Knechtel Jul 09 '11 at 09:00
1

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).
David Hammen
  • 32,454
  • 9
  • 60
  • 108
0

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);
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130