I have just now started learning Java and one of the differences I noticed from C++ and VB is that Java has no goto statements, which I tend to use a lot while programming.
Is there any way I could jump between lines using another statement? I tried to use break and continue but to no avail (I might be doing something wrong).
Here is the code with goto statements and how I want it to operate:
public class HelloWorld {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args)
{
jump1:
System.out.print("What do you want to calculate? ");
String method = sc.nextLine();
if (method.equals("tax")) tax();
else {
System.out.print("Please input a valid method. \n\n");
goto jump1;
}
}
What is a good replacement for the goto commands?
A while loop in this instance.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/flow.html
For this (very specific) instance you could put
System.out.print("What do you want to calculate? ");
String method = sc.nextLine();
while (!method.equals("tax"))
{
System.out.print("Please input a valid method. \n\n");
method = sc.nextLine();
}
tax();
Obviously this only works if your only expected correct input is "tax", but it's a structure to build on.
You would want to put your if-statement in a while-loop by using the hasNextLine() function, which will loop until theres no more lines left to iterate over:
while(sc.hasNextLine()) {
// Your code..
}
For more info regarding the function check Scanner::hasNextLine documentation.
You should avoid "goto" statements in all languages, according to the rules of "structured programming", instead using if-then-else or do or while or for loops to control program flow.
Java DOES have a sort of "goto" statement that you COULD use to only slightly modify your code, but consider the while loop below and the break statement, which jumps out of the loop.
public static void main(String[] args) {
String method = "";
while(! method.equals("tax")){
System.out.print("What do you want to calculate? ");
method = sc.nextLine();
if(method.equals("tax"))
break;
System.out.print("Please input a valid method. \n\n");
}
tax();
}
The break statement enables your "Please ... valid" statement to display. You could also use this:
public static void main(String[] args) {
String method = "";
while(! method.equals("tax")){
System.out.print("What do you want to calculate? ");
method = sc.nextLine();
}
tax();
}
I also kind of like this:
public static void main(String[] args) {
String method = "";
while(1==1){
System.out.print("What do you want to calculate? ");
method = sc.nextLine();
if(method.equals("tax")
break;
System.out.print("Please input a valid method. \n\n");
}
tax();
}
You might go to the Java tutorials; they're good.
In this case you can use a do-while-loop, which will do the statement first and will only repeat if the statement is true:
public class HelloWorld {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args)
{
boolean right = true;
do {
if(right)
System.out.print("What do you want to calculate? ");
else
System.out.print("Please input a valid method. \n\n");
String method = sc.nextLine();
boolean right = false;
} while (!method.equals("tax"));
tax();
}
}
Related
I have this code that asks for a name and age in a do-while loop:
public class Test1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
do {
System.out.print("Enter name & age: ");
System.out.printf("%s %d",
scanner.next(), scanner.nextInt());
} while (scanner.hasNext());
}
}
It outputs:
Enter name & age: test 6
test 6
and then doesn't seem to react to my input, while it should have repeated the question on the third line. What is wrong here?
I think this should stop by the points it gets its input, since when you'll press enter, it would automatically enter the input and your method would end.
I would recommend you to use a while(true) statement if you want to have an infinite input. That issue shouldn't appear if you do it that way.
The java.util.Scanner.hasNext() method Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input. Read more
To avoid getting blocked by hasNext() you can simply pass true for loop condition.
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
do {
System.out.print("Enter name & age: ");
System.out.printf("%s %d", scanner.next(), scanner.nextInt());
} while (true);
}
}
I am making a game in my java class, and I am trying to ask users what kind of difficulty they want to play. However, it seems that the IN.next() is taking in more than 1 word because it is in a loop. How do I get it to take only the first word?
public int configureDifficulty() {
String level = "1";
println("At what difficulty would you like to play at?");
println("Type 1 for easy, 2 for medium, 3 for hard.");
while (true) {
level = IN.next();
try {
return Integer.parseInt(level);
}
catch (NumberFormatException ex) {
println("Try again");
}
}
}
Console
At what difficulty would you like to play at?
Type 1 for easy, 2 for medium, 3 for hard.
test test test test test
Try again
Try again
Try again
Try again
Try again
How to make my program prints just one "Try Again" line, even if users type more than 1 word?
You can use nextLine method of Scanner to read input as String and then later convert it like you want. You can do something like this.
import java.util.*;
class GFG {
public static void main (String[] args) {
int d = configureDifficulty();
System.out.println(d);
}
public static int configureDifficulty() {
String level = "1";
System.out.println("At what difficulty would you like to play at?");
System.out.println("Type 1 for easy, 2 for medium, 3 for hard.");
Scanner in = new Scanner(System.in);
while (true) {
level = in.nextLine();
try {
return Integer.parseInt(level);
}
catch (NumberFormatException ex) {
System.out.println("Try again");
}
}
}
}
If you want to take care of words typed on the same line, you will have to use nextLine method in scanner. The method will return a string and then you will have to parse and write the logic.
What you want to read is an integer (1,2 or 3) to determine difficulty, so I suggest you to use scanner.nextInt() so that you don't need to do the parsing and the extra try-catch block.
Also, you haven't given your complete code(how scanner object is initialized and used in other places) but with whatever you have given, I don't see next() consuming more than one character. If it does and you don't want to replace it with scanner.nextInt(), use scanner.nextLine() instead. Hope this helps
public static void main(String[] args) {
String level = "1";
System.out.println("At what difficulty would you like to play at?");
System.out.println("Type 1 for easy, 2 for medium, 3 for hard.");
Scanner scan = new Scanner(System.in);
while(true)
{
System.out.println(scan.nextInt());
}
}
Hey there I got into some trouble with my java Code.
I try to code a bit around with java for a few hours and I dont know much thats why im asking. I learn best by trying but I get into so many problems.
So: I want the scanner to scan the next Statement and if its "ja" it should do the if thing etc.
The problem is, when i try to compile it it has an error with the = s.nextInt thing. In the console it says: "cannot find symbole". I tried so many things I dont know what to do. Allready tried so much.
import java.util.Scanner;
public class Brotcrunsher {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println ("Hallo");
System.out.println ("A flag has more then 1 color right?");
String a = s.NextInt();
if (a.equals("ja")) {
System.out.println ("You arent dumb, nice.");
} // end of if
else {
System.out.println ("You arentn a genie");
} // end of if-else
}
}
thanks in advance.
EDIT: Problem solved. Thank you for every awnser. I try my best to Tag my posts better and to format my code better
Here:
String a = s.NextInt();
You want a to be String (which makes sense, as you want to compare it against other Strings later on); so you better use:
String a = s.nextLine();
instead!
The other method a) does not exist and b) nextInt() ... returns a number, not a string
I can see two errors, firstly you are taking a string input from the command line user so your scanner must be "scanner.nextLine()" which takes a string, as it stands you are expecting an integer value.
Second your "s.scanner" is not calling anything, you have declared your scanner with the name "scan", so you need to change that to "scan".
import java.util.Scanner;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("A flag has more than one colour?");
String input = scan.nextLine();
if (input.equals("yes")) {
System.out.println("well done");
} else {
System.out.println("wrong answer");
}
}
Try:
import java.util.Scanner;
public class Brotcrunsher {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
System.out.println ("Hallo");
System.out.println ("A flag has more then 1 color right?");
String a = scan.nextLine();
if (a.equals("ja")) {
System.out.println ("You arent dumb, nice.");
} // end of if
else {
System.out.println ("You arentn a genie");
} // end of if-else
}
}
You have got a compilation error that should be
String a = scan.next();
Since scan is your scanner object where you are using String a = s.NextInt(); which is not at all an object of scanner.
Two issues, one is a is a String not an int and the second is Scanner.nextLine() (or nextInt() or next()). And, the local reference is scan (not s). Like,
String a = scan.nextLine();
You can use like this.
import java.util.Scanner;
class ScannerTest{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter your rollno");
int rollno=sc.nextInt();
System.out.println("Enter your name");
String name=sc.next();
System.out.println("Enter your fee");
double fee=sc.nextDouble();
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
sc.close();
}
}
refrence: http://www.javatpoint.com/Scanner-class
I want to take input form user, i am sure my code is right but it don't work at all. Please help is there any thing that i am doing wrong?
`public void edit() throws IOException {
sll.insertAfter();
System.out.println("Enter text: ");
String sen;
sen = keyboard.next();
Object obj = sen;
sll.put(obj);
}
when i execute this an error appears at this line
sen = keyboard.next();
import java.util.*;
public class Example
{
public static void main(String[] args)
{
Edit();
}
public static void Edit()
{
Scanner scan = new Scanner(System.in);
String random;
System.out.print("Please input some text: ");
random = scan.nextLine();
System.out.println("You entered: " + random);
}
}
I don't know what your main method looks like so I can only assume it's empty That being said I can tell you why your current code doesn't work based off of the information you've given us.
Your edit method is not static, and in this situation assuming you've laid out your program simillar to this it must be static as it is in my example.
You've not setup a scanner, or maybe you did outside of your edit method but failed to make it static?
Scanner scan = new Scanner(System.in);
Why are you using Object, if you want to edit the string just use a for loop and substring.
Object
If you provide us with more information, your full code and the error you're getting we can better help you!
So the loop works but I have to press enter twice for it to print out the next input, I know it's with my loop and I know it's because the new input is set after the method scanz but I can't put it before/ eliminate it outside the loop because then the creation of the object Scanning doesn't work. Help is appreciated!
public class NumberScanned {
public static void main(String[] args) {
System.out.println("Please enter '.' when you want to terminate");
Scanner keyboard = new Scanner(System.in);
String scannedString=keyboard.nextLine();
Scanning scanz= new Scanning(scannedString);
do
{
System.out.println("Numbers: "+scannedString);
scanz.set(scannedString);
scanz.printState();
scannedString=keyboard.nextLine();
}
while(!keyboard.nextLine().equals("."));
keyboard.close();
}
}
Change your loop to the following pattern:
String scannedString = keyboard.nextLine();
do {
System.out.println("Numbers: "+scannedString);
scanz.set(scannedString);
scanz.printState();
} while (!(scannedString = keyboard.nextLine()).equals("."));
This way condition check is done together with reading a new line. There is even more readable approach available:
String scannedString = null;
while (!(scannedString = keyboard.nextLine()).equals(".")) {
System.out.println("Numbers: "+scannedString);
scanz.set(scannedString);
scanz.printState();
}