I am writing a random chance game to pick a random winner. I am using a for loop to input the players into an array, but it doesn't let me input anything for the first player. Here is the code:
import java.util.Scanner;
import java.util.Random;
public class Run {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
Random rand = new Random();
System.out.println("How many people will play???");
int playernum = input.nextInt();
String players[] = new String[playernum];
for(int i = 0; i < playernum; i++){
System.out.println("Who is player #" + (i+1)+"?");
players[i] = input.nextLine();
}
System.out.println("The winner is: " + players[rand.nextInt(playernum)]);
}
}
The input.nextInt() call reads the integer but leaves the new line character unread in the input stream, so the input.nextLine() call in the loop just reads that character in the first iteration.
So, you need the following -
int playernum = input.nextInt();
input.nextLine(); //read the unread new line character from the input stream
Use the following code. Comments in the code explain changes.
import java.util.Scanner;
import java.util.Random;
public class Run {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
Random rand = new Random();
System.out.println("How many people will play???");
int playernum = input.nextInt();
input.nextLine(); //ADDED LINE
String players[] = new String[playernum];
for(int i = 0; i < playernum; i++){
System.out.println("Who is player #" + (i+1)+"?");
players[i] = input.nextLine();
}
System.out.println("The winner is: " + players[rand.nextInt(playernum)]);
}
}
We added input.nextLine(); because input.nextInt(); leaves a leftover new line character that we need to clear out. It was putting this new line character as player 1
-Henry
Use input.next() instead of input.nextLine() in the for loop. That way, the unused new line character won't be a problem, like #BheshGurung explains in his answer.
I think your issue is on this line players[i] = input.nextLine();.
I think what you're looking for is, players[i] = input.next();
"Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end."
See the API description here.
Related
// Problem Statement: WAP to create a class Library and use methods addBook and showAvailableBooks to store and show books in the library.
// I am new to java and I am getting an issue after running the below program. I am not able to fill the first index place of the array addBook.
package com.company;
import java.util.Scanner;
class Library{
Scanner sc = new Scanner(System.in);
int numOfBooks;
String[] addBook;
Library(){
System.out.print("Enter the number of books you want to add to the library: ");
numOfBooks = sc.nextInt();
this.addBook = new String[numOfBooks]; //New String called "addBook" is being created.
}
public String[]addBook(){
for(int i=0; i<numOfBooks; i++){
int j = i+1;
System.out.print("Add Book "+j+" Name: ");
this.addBook[i] = sc.nextLine();
}
return addBook;
}
public void showAvailableBooks(){
for(int i=0; i<numOfBooks; i++){
System.out.println(addBook[i]);
}
}
}
public class CWH_51_Exercise_4 {
public static void main(String[] args) {
Library l = new Library();
l.addBook();
l.showAvailableBooks();
}
}
That it's probably caused by sc.nextInt() in your Library contructor. It reads the int given, but it does not read the '\n' character (origined when you press enter).
When nextLine() is called for first time, it reads that missing '\n'.
Try calling nextLine() after every nextInt().
System.out.print("Enter the number of books you want to add to the library: ");
numOfBooks = sc.nextInt();
sc.nextLine(); // Consume '\n'
this.addBook = new String[numOfBooks];
i suggest you avoid using sc.nextInt() and use this instead:
numOfBooks = Integer.parseInt(sc.nextLine());
See this question for the explanation
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
The question is that write a class named Seyyed includes a method named seyyed. I should save the name of some people in a String array in main method and calculate how many names begin with "Seyyed". I wrote the following code. But the output is unexpected. The problem is at line 10 where the sentence "Enter a name : " is printed two times at the first time.
import java.util.Scanner;
public class Seyyed {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of names :");
int n = in.nextInt();
String[] names = new String[n];
for (int i = 0; i < names.length; i++) {
System.out.println("Enter a name : ");
names[i] = in.nextLine();
}
int s = seyyed(names);
System.out.println("There are " + s + " Seyyed");
in.close();
}
static int seyyed(String[] x) {
int i = 0;
for (String s : x)
if (s.startsWith("Seyyed"))
i++;
return i;
}
}
for example When I enter 3 to add 3 names the program 2 times repeats the sentence "Enter a name : " and the output is something like this:
Enter the number of names :3
Enter a name :
Enter a name :
Seyyed Saber
Enter a name :
Ahmad Ali
There are 1 Seyyed
I can enter 2 names while I expect to enter 3 names.
The problem occurs as you hit the enter key, which is a newline \n character. nextInt() consumes only the integer, but it skips the newline \n. To get around this problem, you may need to add an additional input.nextLine() after you read the int, which can consume the \n.
Right after in.nextInt(); just add in.nextLine(); to consume the extra \n from your input. This should work.
Original answer: https://stackoverflow.com/a/14452649/7621786
When you enter the number, you also press the Enter key, which does an "\n" input value, which is captured by your first nextLine() method.
To prevent that, you should insert an nextLine() in your code to consume the "\n" character after you read the int value.
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of names :");
int n = in.nextInt();
in.nextLine();
String[] names = new String[n];
Good answer for the same issue: https://stackoverflow.com/a/7056782/4983264
nextInt() will consume all the characters of the integer but will not touch the end of line character. So when you say nextLine() for the first time in the loop it will read the eol left from the previous scanInt(), so basically reading an empty string. To fix that use a nextLine() before the loop to clear the scanner or use a different scanner for Strings and int.
Try this one:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of names :");
int n = in.nextInt();
in.nextLine();
String[] names = new String[n];
for (int i = 0; i < names.length; i++) {
System.out.println("Enter a name : ");
names[i] = in.nextLine();
}
int s = seyyed(names);
System.out.println("There are " + s + " Seyyed");
in.close();
}
static int seyyed(String[] x) {
int i = 0;
for (String s : x)
if (s.startsWith("Seyyed"))
i++;
return i;
}
I am going to post my code right away and ask the question below it.
System.out.println("Enter your starting integer: ");
firstInt = scnr.nextInt();
System.out.println("Enter your last integer: ");
secondInt = scnr.nextInt();
int i = firstInt;
while (i < secondInt) {
The first input is taken just fine. But when I try to input to secondInt, I hit enter and it wont move onto my while loop it is just stuck in the scanner. I hit enter and i just move down a line to input more. I watn it to move to my while loop. This is probably an easy fix but im pretty new to coding so any help would be appreciated. Thanks in advance!
import java.util.Scanner;
public class Tyler
{
public static void main(String[] args)
{
Scanner stdin = new Scanner(System.in);
// input first int
System.out.print("Enter your starting integer: ");
int firstInt = stdin.nextInt();
//input second int
// consume line
stdin.nextLine();
System.out.print("Enter your last integer: ");
int secondInt = stdin.nextInt();
// output data
// There was no way to break out of your while loop so this should be done with an If/else
if (firstInt <= secondInt)
{
System.out.println("First number is less then second number");
}
else
{
System.out.println("Second number is less then first number");
}
}
}
I need to read user inputs line by line (may be included spaces). I had already read Scanner doesn't see after space question. So I used with scanner.nextLine() but this method does not help my program. Below is my sample program ....
public class TestingScanner {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many friends do you have ?");
int size = sc.nextInt();
String[] names = new String[size];
for (int i = 0; i < size; i++) {
System.out.println("Enter your name of friend" + (i + 1));
names[i] = sc.nextLine();
}
System.out.println("*****************************");
System.out.println("Your friends are : ");
for (int i = 0; i < names.length; i++) {
System.out.println(names[i]);
}
System.out.println("*****************************");
}
}
While runnig my program , after inserted no: of friend , my program produces two lines as below. How can I solve it ? Thanks.
After int size = sc.nextInt(); use sc.nextLine() to consume the newline characters, otherwise, they will be consumed by nextLine() in your loop and that is not what you want.
Solution
int size = sc.nextInt();
sc.nextLine();
import java.util.Scanner;
public class Cardhelp2{
private static String[] pairArray={"A,A","K,K","Q,Q","J,J","10,10","9,9","8,8","7,7","6,6","5,5","4,4","3,3","2,2"};
public static void generateRandom(int k){
int minimum = 0;
int maximum = 13;
for(int i = 1; i <= k; i++)
{
int randomNum = minimum + (int)(Math.random()* maximum);
System.out.print("Player " + i +" , You have been dealt a pair of: ");
System.out.println(pairArray[randomNum]);
}
} //reads array and randomizes cards
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many players would you like to play with? ");
int m = scan.nextInt();
generateRandom(m);
//displays the cards
___________________________________________________
System.out.println("Would you like to play?");
Scanner scanner = new Scanner(System.in);
if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes")) {
System.out.println("This will be fun");
} else if(scanner.next().equalsIgnoreCase("n")||scanner.next().equalsIgnoreCase("no")) {
System.out.println("Maybe next time");
} else {
System.out.println("Invalid character");
}
}
}
Im having trouble understanding why the end part is not working, I've been told i need to change scanner.next(); to a variable but im not sure how to do it and get the code working. Is there a simple way of reading in the users answer then displaying a response to the user?
Thanks
Your conditional expression
if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes"))
calls scanner.next() twice, which means the second call will read/wait for more input. Instead you need to call it only once, store the result and use that in the comparison:
String tmp = scanner.next();
if(tmp.equalsIgnoreCase("y")||tmp.equalsIgnoreCase("yes"))
Let's assume the user inputs "yes".
At
if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes")) {
Scanner.next() produces "yes" in the first test. So the code is effectively
"yes".equalsIgnoreCase("y")
Which is false, so it moves to the next test:
scanner.next().equalsIgnoreCase("yes")
Here's where your issue is.
the "yes" entered has already been consumed by the first test. Now the Scanner has nothing in the buffer.
If you want to test the SAME input again, you must capture it, and use that in your tests.
So
String userReply= Scanner.next();
if(userReply.equalsIgnoreCase("y")||userReply.equalsIgnoreCase("yes")) {...
This is becauswe, with each call to scanner.next(), the Scanner returns the next value in the stream, and then MOVES PAST IT
If the user had entered "yes" and then "no", the tests would be performed like this:
if("yes".equalsIgnoreCase("y")||"no".equalsIgnoreCase("yes")) {...
You need change the way of Scanner's calls.
The user input \n and Scanner seems don't follow with the next token. Then you need read line by line.
:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("How many players would you like to play with? ");
int m = Integer.parseInt(sc.nextLine()); // May thrown NumberFormatException
generateRandom(m);
//displays the cards
System.out.print("Would you like to play? ");
String input = sc.nextLine();
if (input.equalsIgnoreCase("y") || input.equalsIgnoreCase("yes")) {
System.out.println("This will be fun");
} else if (input.equalsIgnoreCase("n") || input.equalsIgnoreCase("no")) {
System.out.println("Maybe next time");
} else {
System.out.println("Invalid character");
}
}