Programs continually prints rather than waiting for input [duplicate] - java

This question already has answers here:
How can I read input from the console using the Scanner class in Java?
(17 answers)
Closed 5 years ago.
When I run this, int x = 0 and 1 is added to x to each time it runs. The program keeps on printing out "Round 1", not allowing any time in between to input anything. This is not about reading input, it's about being able to input something without the program going crazy.
while (!broken) {
int pointcount = 0;
System.out.println("Round " + x);
Scanner jumpOption = new Scanner(System.in);
if (jumpOption.equals("W")) {
pointcount += 1;
Random rand = new Random();
if (rand.nextInt(100) == 0) {
broken = true;

You're creating a Scanner object, but not using it for anything. To get any input from the Scanner you have to use one of its methods, like Scanner.nextLine()
Scanner myScanner = new Scanner(System.in);
// Here's where we get the actual input!
if (myScanner.nextLine().equals("Hello")

You have to actually read from the scanner with the next() method
if (jumpOption.next().equals("W")) {

Related

Java: Why while(true) loop breaks automatically when using nextInt()? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 2 years ago.
I am a beginner programmer student from Finland, this is my first post here so hello everyone! So, I am writing this Java program that reads user inputs and creates new Books according to the inputs and then adds them to list and sorts them according to their recommended ages and names. The following code doesn's seem to work, the loop breaks automatically after one go. I actually fixed the issue using "Integer.valueOf" instead of nextInt but I started wondering why the nextInt doesn't work here?
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ArrayList<Book> books = new ArrayList<>();
while (true) {
System.out.println("Enter books name, blank will end the loop:");
String bookName = reader.nextLine();
if (bookName.equals("")) {
break;
}
System.out.println("Enter the books recommended age:");
int minimAge = reader.nextInt();
Book book = new Book(bookName, minimAge);
books.add(book);
}
System.out.println("Total " + books.size() + " books.");
System.out.println();
System.out.println("Books:");
Comparator<Book> vertaus = Comparator
.comparing(Book::getMinimAge)
.thenComparing(Book::getName);
Collections.sort(books, vertaus);
for (Book k : books) {
System.out.println(k);
}
}
}
While entering number for minimAge when you press enter, the scanner takes two input, the number and a EOF character. As a result EOF character is set as the next bookname. Which is equivalent to empty string and breaks the loop. To skip this add the following code
int minimAge = reader.nextInt();
reader.nextLine();

How to fix NoSuchElementException [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Close a Scanner linked to System.in
(5 answers)
Closed 4 years ago.
I had setup a method to check if the input matches the type int and doesn't return until it does.
It worked fine for a couple of projects so far but when I used it in my current one I got this kind of error when going into the method for the second time around.
Exception in thread "main" java.util.NoSuchElementException
Here is the method:
private static int inputHandler() {
Scanner sc = new Scanner(System.in);
int num = 0;
try{
System.out.println("Enter a number:");
num = sc.nextInt();
} catch(InputMismatchException e){
System.out.println("Input must match type int");
num = inputHandler();
}
sc.close();
return num;
}
If anyone knows how to fix this issue I would appreciate the help.

Better way to read nextLine [duplicate]

This question already has answers here:
Using scanner.nextLine() [duplicate]
(5 answers)
Closed 6 years ago.
Working through a HackerRank tutorial, and I was wondering -- is there a better way to strip off the newline character that comes after reading in the double? It feels really manual and "hacky" to just repeat a nextLine()
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
double d = scan.nextDouble();
String b = scan.nextLine();
String s = scan.nextLine();
}
}
Note: code works as-is, just asking if there is a less hacky way to go about this
Operate on lines at a time, then you don't need to worry about the nextDouble() (or nextInt()) calls leaving a trailing newline. Like,
Scanner scan = new Scanner(System.in);
int i = Integer.parseInt(scan.nextLine());
double d = Double.parseDouble(scan.nextLine());
String s = scan.nextLine();
If, you want to allow the int and double to be on the same line then you could do
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
double d = Double.parseDouble(scan.nextLine());
String s = scan.nextLine();
But without knowing your input format, that may or not be helpful. I would prefer the version most readable for the problem at hand (parsing the input).

The constructor Scanner is undefined [duplicate]

This question already has answers here:
How to get the user input in Java?
(29 answers)
Closed 5 years ago.
I'm very very new to Java. I got stuck in this error where it states:
The constructor Scanner() is undefined
and
The method nextInt(int) in the type Scanner is not applicable for the arguments (InputStream).
import java.util.Random;
import java.util.Scanner;
public class NumberGenerator
{
public static void main(String[] args)
{
Scanner input = new Scanner();
Random randomNumber = new Random();
System.out.println("Please enter the maximum value: ");
int maxValue = input.nextInt(System.in);
for (int counter = 1; counter <= 1; counter++)
{
int number = randomNumber.nextInt(maxValue);
System.out.println("Your random number is: " + number);
}
}
}
As you may be able to see, I'm very new and I really appreciate your help.
You need to specify what the scanner is supposed to read from. I assume you want it to read from the console, in which case you would want to write:
Scanner input = new Scanner(System.in);
Also, nextInt() does not take parameters. Change it to:
int maxValue = input.nextInt();
The answer to both of your problems is here https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html. The Scanner class has only constructors that require arguments and the nextInt method either takes no argument or an int.
Advice: Googling " javadoc" is a good habit.

Java String automatically assigned null value [duplicate]

This question already has answers here:
Java calculator not executing if-statement [duplicate]
(3 answers)
Closed 9 years ago.
In the code below, in the first iteration of the first for loop, boxes[a] is automatically assigned a null value.
The remainder of the iterations are fine (user input is accepted). Only the first has the issue where a null value is automatically assigned.
Does anyone know why this may be? Thank you.
package testing;
import java.util.Scanner;
public class Testing {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Scanner in2 = new Scanner(System.in);
int boxNumber;
boxNumber = in.nextInt();
String[] boxes = new String[boxNumber];
System.out.println(boxNumber);
for(int a=0; a <= boxes.length - 1; a++){
boxes[a] = in.nextLine();
System.out.println(boxes[a]);
}
int packageNumber;
packageNumber = in2.nextInt();
String[] packages = new String[packageNumber];
System.out.println(packageNumber);
for(int n=0; n <= packageNumber - 1; n++){
packages[n] = in.nextLine();
System.out.println(packages[n]);
}
}
}
The scenario fitting the description of what occurs is when you type in a number on the first line, then the rest of the lines are strings for the boxes.
But the nextInt() method doesn't advance past the first newline character, so the first time you call nextLine(), it matches on the rest of the line until the first newline character, "" ( not null).
After the call to nextInt(), insert a call to newLine() before the for loop to bypass the first newline character.
String firstNewLine = in.nextLine();
for(int a=0; a <= boxes.length - 1; a++){
when you did hit enter after entring the first number you also have and empty line that's why nextLine() return empty string, you can use this boxNumber = in2.nextInt(); instead but I would suggest to think of another way, normally you don't need two Scanner instances

Categories

Resources