How can I create a global or local script terminater?
I tried this,
Code :
System.out.println("Enter your number: ");
nr1 = scn.nextDouble();
if(nr1.equals("stop") || nr1.equals("Stop")){
String nr1 = nr1(double);
System.exit(0);
}
but I need to define the String nr1 before the if-statement. How can I do this?
Also, is there any other way to do this? As in if I write stop in any place it will shutdown the program?
EDIT:
I want the nr1 to be converted from a double to a string in the if-statement. I do not want it to be converted so it will work outside the if-statement, as it will only ruin the rest of my code.
Re: How can I create a global or local script terminater?
Quote:
I need to define the String nr1 before the if-statement
There is already a variable named nr1 defined that looks like it is type double.
You will have to use a different name for the String.
I don't know of any general way to convert a double to a String like "stop".
Can you explain what you are trying to do?
Why don't you use the Scanner class's next() method to read a String from the user that you could compare to "stop"?
The Scanner class has methods that will test the datatype of what the user entered. See the methods that begin with has
Re: How can I create a global or local script terminater?
Hello YourCrazyFriend !
Quote:
I want the nr1 to be converted from a double to a string in the if-statement. I do not want it to be converted so it will work outside the if-statement, as it will only ruin the rest of my code.
There is a toString(double d) method in the Double class.
But since you want to compare the String you will create with another("stop") in the if statement, you have to define it at the same level and before the if statement.
Hope it helps.
Re: How can I create a global or local script terminater?
I don't know if I did it the correct way, but this is where I have gotten so far. This code is not working yet.
Code :
Scanner scn = new Scanner(System.in);
double nr1, nr2, answer;
String str;
System.out.println("Enter your number: ");
nr1 = scn.nextDouble();
toString(double nr1);
if(nr1.equalsIgnoreCase("stop")){
System.exit(0);
}
Re: How can I create a global or local script terminater?
Quote:
Originally Posted by
YourCrazyFriend
I don't know if I did it the correct way, but this is where I have gotten so far. This code is not working yet.
No, this isn't the correct way. You should assign what the toString() method returns to the String you created (str). You can find many examples if you Google it. Here is one of them.
Re: How can I create a global or local script terminater?
Quote:
This code is not working yet.
I don't think it will ever work. You won't get the String "stop" from a double value.