Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
Alternative for 'GOTO' function in java?
I know that Goto is a reserved function in java,i wonder if there is any alternatives to it.I could not understand how to use label and continue instead of goto.
Here am presenting a C code to friend the prime numbers which has goto function employed in it.I want you to re-write this code using java with the same functionalities.
#include <stdio.h>
#include <conio.h>
void main()
{
int n,m,k,i,max;
char c;
clrscr();
repeat: max=0;
k=2;
n=1;
printf("You want prime numbers upto:- ");
scanf("%d",&max);
printf("
");
for (i=1;i<=max;i++)
{
again: m=(n/k)*k;
if (m!=n)
k=k+1;
else
goto try1;
if (k < n/2)
goto again;
else
printf("%d",n);
printf(" ");
try1: n=n+1;
k=2;
}
fflush(stdin);
printf ("
Do you want to continue?(y/n):- ");
scanf("%c",&c);
if (c=='y')
goto repeat;
getch();
}
please help me,iam new to java.
PS:Sorry for the confusing code,using goto labels will make the code confusing,but it is a powerful construct .what to do if i want an action to be repeated based on the user input,as in the above program?
3 Answers
- 1 decade ago
REPLACE your label (repeat) with
while(true)
REPLACE your whole goto thing with
if(c!= 'y')break;
This is already pretty poor code in C. getch() isn't a portable function between compilers, if/else clauses should be blocks even if they're a single statement, using "try1" as a label, no functions...
--------------------------------------------------
what to do if i want an action to be repeated based on the user input
What you do is what I said above. Put an infinite loop around what you want to run and use a
"if(userInput means break the loop) break";
This is what it should look like (except I haven't bothered with input validation and in true C spirit, I decided that if you pass things to functions that you shouldn't then you get crazy results.):
- 1 decade ago
The goto construct is highly abused in all programming languages by novices. Create a function, and call the function when needed, instead of jumping around in your script.