Using multiple scanners failed - Java - java

I have a problem with Scanner class. I have a few methods which read certain input from the user, however after invoking first method others crash (cannot read input). I searched for the solution and it looked like adding "scanner.nextLine()" will solve the problem but it didn't.
public class GameController {
private int numberOfPlayers = 2;
private Board board = new Board('.');
String players[] = new String[numberOfPlayers];
char playersMarkers[] = new char[numberOfPlayers];
public void getPlayersNames() {
Scanner input = new Scanner(System.in);
for (int i = 0; i < players.length; i++) {
System.out.print("Insert player " + (i + 1) + "'s name: ");
players[i] = input.nextLine();
}
input.nextLine(); // <- this one was suppose to solve the problem
input.close();
}
public static void main(String[] args) {
GameController gc = new GameController();
gc.getPlayersNames();
Scanner scanner = new Scanner(System.in);
int array[] = new int[5];
for (int i = 0; i < array.length; i++) {
if (scanner.hasNext()) {
array[i] = scanner.nextInt();
}
}
scanner.close();
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
Output:
Insert player 1's name: John
Insert player 2's name: George
1
0
0
0
0
0

You are not getting anything from scanner (in the main method) because you already closed System.in (when closing input, at the end of the getPlayersNames method).
You should not close System.in yourself, as it prevent any future attempt to read from this stream.

Related

Java loop ignoring first input each loop

I am a beginner and have a simple piece of code that works - it is designed to ask a user for seven numbers and store them in an array then print out what they entered
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] inputs = new int[7];
System.out.println("Enter 6 numbers and a bonus ball");
for (int i = 0; i < 7; i++) {
inputs[i] = in .nextInt();
}
System.out.println("You have entered the numbers:");
for (int i: inputs) {
System.out.println(i);
}
}
What I want to do is add an error trap to make sure the number is not greater than 49 - I have added the following code and there are no errors and it runs fine but I have to add two numbers for each loop as it only stores the second input - can anyone help tell me why?
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] inputs = new int[7];
System.out.println("Enter 6 numbers and a bonus ball");
for (int i = 0; i < 7; i++) {
if ( in .nextInt() > 49) {
System.out.println("please enter a number less than 49");
inputs[i] = in .nextInt();
} else
inputs[i] = in .nextInt();
}
System.out.println("You have entered the numbers:");
for (int i: inputs) {
System.out.println(i);
}
}
when you do in.nextInt() it give you the "next" integer in the input, so you are doing this twice for each loop cycle, once in the if statement and the other in the if or else body. so you need invoke that function only once. something like this:
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int [] inputs = new int [7];
System.out.println("Enter 6 numbers and a bonus ball");
for (int i = 0; i < 7; i++)
{
int current_input = in.nextInt()
if ( current_input > 49)
{
System.out.println("please enter a number less than 49");
inputs [i] = in.nextInt();
}
else
inputs [i] = current_input;
}
System.out.println("You have entered the numbers:");
for (int i : inputs)
{
System.out.println(i);
}
}
I don't test the code but you have the idea.
here you have another problem still, and is that when the user types a number over 49, the second time you ask the number to the user, you don't test again that it's below 49 so the user can enter any number.

Prevent trailing character when printing values in a loop [duplicate]

This question already has answers here:
Printing with delimiter only between values
(3 answers)
Closed 2 years ago.
I was tasked to do a looping problem for Java, but I'm currently having a problem on how to display a factorial of a number. For example, 1x2x3x4x5 = 120.
I'm almost there, but I can't seem to figure out how to, or is there any possible way to display the factorial of a number because there is always an additional "x" at the end of the 5.
Here is my code:
import java.util.*;
public class trylangpo2 {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int fctr;
System.out.println ("number");
fctr = input.nextInt();
for (int i = 1; i <=fctr; i++){
System.out.print(i);
int j;
for (j =1; j <=1 ; j++){
System.out.print("*");
}
}
}
}
Example output:
1x2x3x4x5x
Your loop for (j =1; j <=1 ; j++) can be removed. It only loops once so, just write System.out.print("*"). No loop required
Then if you think about it, you want to print the number and the * all the time, except when it is the last number (fctr)
So write it that way:
Scanner input = new Scanner (System.in);
int fctr;
System.out.println ("number");
fctr = input.nextInt();
for (int i = 1; i <=fctr; i++){
System.out.print(i);
if(i<fctr) {
System.out.print("*");
}
}
Try to add a condition if it’s not at the end of the loop. Then add start and if it’s the end, then just print the number:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int fctr;
System.out.println("number");
fctr = input.nextInt();
for (int i = 1; i <= fctr; i++) {
if (i < fctr) {
System.out.print(i + " * ");
} else {
System.out.print(i);
}
}
}
I always use a construct like
String sep="";
for (...) {
System.out.print(sep);
System.out.print(payload);
sep="x";
}
You need to make the printing of ***** condition. Don't print ***** if i == fctr. And you don't need that additional loop of j. As below :
public static void main(final String[] args) {
final Scanner input = new Scanner(System.in);
int fctr;
System.out.println("number");
fctr = input.nextInt();
// IntStream.range(1, fctr).
long factorial = 1;
for (int i = 1; i <= fctr; i++) {
factorial = factorial * i;
if (i == fctr) {
System.out.print(i);
} else {
System.out.print(i + "*");
}
}
System.out.print("=" + factorial);
}

Scanner - Matrix of char in Java

I just started learning this language and I have a problem trying to create a Matrix of type char from user input.
For example I want to read this as my input:
3 // this is an int n that will give me a square matrix[n][n]
.#.
###
.#.
For this example, this is what I have:
//...
Scanner stdin = new Scanner(System.in);
int n = stdin.nextInt();
char[][] matrix = new char[n][n]
for(int i = 0; i < n; i++){
matrix = stdin.nextLine();
}
Obviously this is wrong, and I know that. I'm just not seeing a way to correctly read this input.
If anyone could help me I would appreciate it.
ps: if possible, keep it simple, because like I said, I just started learning java :)
First, you need to add stdin.nextLine(); after reading n to skip the new line character.
Second, this is what you need inside your loop:
matrix[i] = stdin.nextLine().toCharArray();
This reads next line and converts it to an array of chars.
This is a runnable version of your question with output
import javafx.application.Application;
import javafx.stage.Stage;
import java.util.Arrays;
import java.util.Scanner;
public class MainNoFXML extends Application {
#Override
public void start(Stage stage) {
System.out.println("Enter Matrix Size:");
Scanner stdin = new Scanner(System.in);
int n = stdin.nextInt();
char[][] matrix = new char[n][n];
stdin.nextLine();
for(int i = 0; i < n; i++) {
System.out.println("Enter "+n+" Number of Chars");
System.arraycopy(stdin.nextLine().toCharArray(), 0, matrix[i], 0, n);
}
System.out.println("\nYour Matrix:");
for(int i = 0; i < n; i++)
System.out.println(Arrays.toString(matrix[i]));
}
public static void main(String[] args) { launch(args); }
}
Output:
Enter Matrix Size:
3
Enter 3 Number of Chars
.#.
Enter 3 Number of Chars
###
Enter 3 Number of Chars
.#.
Your Matrix:
[., #, .]
[#, #, #]
[., #, .]
First of all, thank you for all your answers.
I emailed my teacher and this was the solution he gave to me, if anyone is wondering:
Scanner stdin = new Scanner(System.in);
int n = stdin.nextInt();
stdin.nextLine();
char[][] matrix = new char[n][n]
for(int i = 0; i < n; i++){
String line = stdin.nextLine();
for(int j = 0; i < n; j++){
matrix[i][j] = line.charAt(j);
}
}
see code sample:
public class MatInput {
public static void main(String[] args) {
int matX = 3;
int matY = 3;
String matrix [][]=new String[matX ][matY];
Scanner input = new Scanner(System.in);
System.out.println("enter the strings for the Matrix");
for(int row=0;row<matX;row++){
for(int col=0;col<matY;col++){
matrix[row][col]=input.nextLine();
}
System.out.println("");
}
for(int r=0;r<matrix.length; r++) {
for (int c=0; c<matrix [r].length; c++) {
System.out.print(matrix [r][c] + " ");
}
System.out.println("");
}
input.close();
}
}

How can I exit a program asking for inputs in an array?

I am taking a course and I have the programs run in a loop so you can easily exit by entering "Quit". I am running into trouble working with arrays. This has the user type in sentences and then at the end shows the user what they typed. I want to have the program check each input the user types in and if it is "Quit", I want to exit the program. I am new to Java so looking for something that is within my understanding without using a break if possible.
I have attempted to use a boolean in my while loop to quit when it is set to false.
public static void main(String[] args)
{
String [] Responses = new String [10];
boolean ExitLoop = true;
do
{
Scanner Input = new Scanner(System.in);
int n = 0;
for (int i = 0; i < 10; i++)
{
System.out.println("Please enter sentence " + (i+1) + ": ");
Responses[n] = Input.nextLine();
if (Responses[n] == "Quit")
{
ExitLoop = false;
}
n++;
}
System.out.println();
for (int j = 0; j < 10; j++)
{
System.out.println("Sentence " + (j+1) + " " + Responses[j]);
}
}
while (ExitLoop);
}
To exit the application you can call the following line from anywhere.
System.exit(0);
Integrated into you code it would look like this.
for (int i = 0; i < 10; i++)
{
System.out.println("Please enter sentence " + (i+1) + ": ");
Responses[n] = Input.nextLine();
if (Responses[n].equals("Quit"))
{
System.exit(0); //add this to exit the application
}
n++;
}
If you wanted to keep separation of concerns you could make a method that exits the application.
public void ExitApplication()
{
//you can add pre-exit checks and other items here
System.exit(0);
}
Then you could simply call the method from inside you loop.
if (Responses[n].equals("Quit"))
{
ExitApplication();
}
The '==' operator only checks if the strings refer to the same memory location, which they do not. Try using the string.equals() method for comparing the actual string values.
if (Responses[n].equals("Quit")) {
ExitLoop = false;
}
You can use one variable for iteration, and you need to use equals for comparing string.
Try that:
public static void main(String[] args) {
final int countSentences = 10;
final String[] sentences = new String[countSentences];
final Scanner scanner = new Scanner(System.in);
for (int i = 0; i < countSentences; i++) {
System.out.println("Please enter sentence "+(i+1)+": ");
sentences[i] = scanner.nextLine();
if (sentences[i].equals("Quit")) System.exit(0);
}
System.out.println();
for (int j = 0; j < countSentences; j++)
System.out.println("Sentence "+(j+1)+" "+sentences[j]);
}

Java Take String input from console

I was trying to take string input in java. My input should be like this
3
1,1,bugs#bunny.com,123 Sesame St.,New York,NY,10011,12345689010
1,2,bugs#bunny.com,123 Sesame St.,New York,NY,10011,12345689010
1,3,bugs#bunny.com,123 Sesame St.,New York,NY,10011,12345689010
So, I tried this
Scanner in = new Scanner(System.in);
int TotalNumber = in.nextInt();
String[] Data = new String[TotalNumber];
for (int Counter = 0; Counter < TotalNumber; Counter++) {
Data[Counter] = in.next();
}
in.close();
for (int counter = 0; counter < Data.length; counter++) {
System.out.println(Data[counter]);
}
My output is showing this
1,1,bugs#bunny.com,123
Sesame
St.,New
What is my problem ? How take input string line properly ?
Update
I found my solution at here Scanner issue when using nextLine after nextXXX
next() breaks at a whitespace. Instead, you should use nextLine() to input the entire line to your string:
int TotalNumber = in.nextInt();
String[] Data = new String[TotalNumber];
for (int Counter = 0; Counter < TotalNumber; Counter++) {
Data[Counter] = in.nextLine();
}
Try with Data[Counter] = in.nextLine();
What about:
import java.util.Scanner;
import java.lang.String;
public class Test
{
public static void main(String[] args)
{
char[] sArray;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a Palindrome : ");
String s = scan.nextLine();
s = s.replaceAll("\\s+", "");
sArray = new char[s.length()];
for(int i = 0; i < s.length(); i++)
{
sArray[i] = s.charAt(i);
System.out.print(sArray[i]);
}
}
}
Try this (Mureinik modified code)..
int TotalNumber = in.nextInt();
in.nextLine();
String[] Data = new String[TotalNumber];
for (int Counter = 0; Counter < TotalNumber; Counter++) {
Data[Counter] = in.nextLine();
}
You need a nextLine() after taking the int because you will press enter after taking int and that enter is read by nextLine() in the Data[0].

Categories