Scanner.next() taking in more than 1 word in loop - java

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());
}
}

Related

Take input as a string in Java and limit the user to not enter integer

I want to take input as a string in Java and limit the user to not enter integer by using try catch.
import java.util.*;
public class trycatch {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
String a;
System.out.println("\n\nEnter the name");
try {
a=sc.nextLine();
System.out.println("You name is "+a);
}
catch(InputMismatchException b) {
System.out.println("There is problem with your input");
}
}
}
Test to see if it is an int and if not a Exception is thrown
a=sc.nextLine();
Integer.valueOf(a); // throws NumberFormatException
// this is number so go to top of loop
continue;
} catch(NumberFormatException b) {
System.out.println("There is NO problem with your input");
// we can use `a` out side the loop
}
Take a look at this:
Does java have a int.tryparse that doesn't throw an exception for bad data?
Use that technique to try to parse what the user entered as an int. If the conversion succeeds, it means they entered an int, and you should throw an exception because you said you don't want them to enter an int (which I understood to mean you don't want them to enter a sequence of numbers only)
I haven't given you the exact answer/written your code for you because you're clearly learning java and this is an academic exercise. Your university/school isn't interested in teaching/assessing my programming ability, they're interested in yours, so there isn't any value to you in me doing your work for you :)
If you get stuck implementing what I suggest, edit your question to include your improved code and we can help again
As a side note, I suggest you make your error messages better that "there was a problem"
Nothing is more frustrating to a user than being told there was a problem but not what it was or how to fix it.
You should check you string for numbers like this:
a=sc.nextLine();
if (a.matches(".*\\d+.*")) {
throw new InputMismatchException();
}
This problem can be solved best with using Regular expression but since your requirement is to use try catch so you can you use below approach
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = null;
System.out.println("\n\nEnter the name");
try {
// try to get Integer if it is number print invalid input(because we
// don't want number)
sc.nextInt();
System.out.println("There is problem with your input");
}
//getting exception means input was not an integer
// if input was not an Integer then try to read that as string and print
// the name
catch (InputMismatchException b) {
a = sc.next();
System.out.println("You name is " + a);
}
}

Java if (Yes or No Statement)

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

Is there an equivalent of while(scanf()==1) in java?

I have been using the following code in c and c++ for looping till user feeds the correct value till the program comes out of it:
while((scanf("%d",&num)==1)//same way in for loop
{
//some code
}
Can i some how use the same way to accept and loop the program till i keep entering let's say an integer and floating or a char or a special character breaks it.
Use :
Scanner sc = new Scanner(System.in); // OR replace System.in with file to read
while(sc.hasNext()){
//code here
int x = sc.nextInt();
//...
}
There are different variants of hasNext() for specific expected input types: hasNextFloat(), hasNextInt()..
Same goes for next() method so you can find nextInt(), nextFloat() or even nextLine()
You can go to Java doc for more info.
As proposed in comments, you can use the Scanner class.
Note you need to read the in buffer with a nextLine() when it is not an int.
public static void main(String[] args) {
try (Scanner in = new Scanner(System.in)) {
System.out.println("Enter an int: ");
while (!in.hasNextInt()) {
System.out.println("That's not an int! try again...");
in.nextLine();
}
int myInt = in.nextInt();
System.out.println("You entered "+myInt);
}
}

Jumping to lines in Java

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();
}
}

how to accept multiple lines of input just once and making sure the user is not asked for input once again

I have tried to solve the 3n+1 problem, and got very close. I think what happens here is the answer should accept multiple lines of input at once should not ask the user to give input again. I have tried the nextLine() method in a loop conditioned by the hasNextLong(), but the problem is whenever it does not find any more long types, it asks the user to give another input instead of breaking the loop. Is there any way to make sure it takes input only once, regardless of how many lines the user inputs?
The loop breaks if I enter a String. What I want to do is break when only the first input has no more long variables to deal with.
import java.util.Scanner;
import java.io.*;
public class te{
public static void main(String[] args){
Scanner key=new Scanner (new BufferedInputStream(System.in));
String s="";
while(key.hasNextInt()){
System.out.println("Entered loop");
s=s+""+key.nextLong();
}
System.out.println(s);
}
}
Not 100% sure what your trying to accomplish, but to answer this problem:
"..whenever it does not find any more long types, it asks the user to give another input instead of breaking the loop."
I just used a try/catch block. If the input is not a number, it breaks the loop. You can keep inputting numbers and hitting enter, and if an input is not a number, the loop will break; and it will print out the concatenated numbers.
import java.util.Scanner;
public class StackOverflow {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String s = "";
System.out.println("Enter Numbers: ");
while (true) {
try {
s += String.valueOf(scanner.nextInt()); // if input is not an int
} catch (Exception ex) { // it will throw exception
break;
}
}
System.out.println(s);
}
}
Edit: Scanning a line
Scanner input = Scanner(System.in);
System.out.printline("Enter some numbers: ");
String line = scanner.nextLine();
Scanner lineScanner = new Scanner(line);
while (lineScanner.hasNextLong()){
long num = lineScanner.nextLong();
// do something with num
}

Categories