Java Take String input from console - java

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].

Related

how to take space separated integer inputs in int variables in java?

I tried this I want to input in integers, i don't want too use a string or array...
int sh=0,sm=0,eh=0,em=0;
t=sc.nextInt();
for(int i=0;i<t;i++)
{
sh=sc.nextInt();
sm=sc.nextInt();
eh=sc.nextInt();
em=sc.nextInt();
}
I want to take input as
2
1 44 2 14
2 33 5 12
There are 4 integers space separated in one line and then the next same as above line how I can?
You need to use the nextLine() method. Read full line in 1 time. Then separate it by the help of space using string split method. Store in array or in same variable you want.
for(int i=0;i<t;i++)
{
String s=sc.nextLine();
int a[] = new int[4];
String[] parts = s.split("\\s+");
sh=Integer.parseInt(parts[0]);
sm=Integer.parseInt(parts[1]);
eh=Integer.parseInt(parts[2]);
em=Integer.parseInt(parts[3]);
}
You should use nextLine() method and Integer.parseOf().
See short example below:
int sh, sm, eh, em;
int numberOfLines = Integer.parseInt(scanner.nextLine());
for (int i = 0; i < numberOfLines; ++i) {
String line = scanner.nextLine();
String[] s = line.split(" ");
sh = Integer.parseInt(s[0]);
sm = Integer.parseInt(s[0]);
eh = Integer.parseInt(s[0]);
em = Integer.parseInt(s[0]);
}
Without Integer.parse():
int sh, sm, eh, em;
int numberOfLines = scanner.nextInt();
for (int i = 0; i < numberOfLines; ++i) {
sh = scanner.nextInt();
sm = scanner.nextInt();
eh = scanner.nextInt();
em = scanner.nextInt();
}

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

Using multiple scanners failed - 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.

Scanner skipping first input in loop Java [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 7 years ago.
This is a basic name sorting program. Everything works except for the fact that the user cannot input the first name. This is the code:
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("How many names do you want to sort");
int num = sc.nextInt();
String[] names = new String[num];
for (int x = 0; x < names.length; x++){
int pos = x+1;
System.out.println("Enter name " + pos);
//String temp = sc.nextLine();
names[x] = sc.nextLine();
}
String sortedArray[] = sort(names);
for (int i = 0; i < sortedArray.length; i++){
System.out.print(sortedArray[i] + " ");
}
}
Update: I changed the code so if it is the first time, it calls sc.nextLine() and then sets the input equal to names[0]
One problem with .next() is that if a person's first name is 2 words to treats it as two names. This is the updated code that works:
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("How many names do you want to sort");
int num = sc.nextInt();
String[] names = new String[num];
//String[] temp = new String[names.length];
for (int x = 0; x < names.length; x++) {
int pos = x + 1;
if (x == 0) {
System.out.println("Enter name 1");
sc.nextLine();
names[0] = sc.nextLine();
} else {
System.out.println("Enter name " + pos);
//String temp = sc.nextLine();
names[x] = sc.nextLine();
}
}
String sortedArray[] = sort(names);
for (int i = 0; i < sortedArray.length; i++) {
System.out.print(sortedArray[i] + " ");
}
}
Use sc.next(); instead of sc.nextLine();
next() will find and return the next complete token from the input stream.
nextLine() will advance the scanner past the current line and will return the input that was skipped
Also, check below description from Scanner#nextLine().
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. The position is set to the
beginning of the next line.
Since this method continues to search through the input looking for a
line separator, it may buffer all of the input searching for the line
to skip if no line separators are present.
Scanner sc = new Scanner(System.in);
System.out.println("How many names do you want to sort");
int num = sc.nextInt();
String[] names = new String[num];
for (int x = 0; x < names.length; x++){
int pos = x+1;
System.out.println("Enter name " + pos);
//String temp = sc.nextLine();
names[x] = sc.next();
}
/*String sortedArray[] = sort(names);
for (int i = 0; i < sortedArray.length; i++){
System.out.print(sortedArray[i] + " ");
}*/

Pattern/Array issue in java

I am studying for an upcoming test next month and looking at some basic problems. This one is a program that requires entering a few sentences and reprinting any that contain a certain string, 'pattern' in this case.
My attempt is below and it compiles however I receive the following error when trying to run it:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at Grep.main(Grep.java:18)
import java.util.Scanner;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Grep {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("[Pp]attern");
String sentences[] = new String[10];
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter some sentences: ");
for (int i = 0; i <= sentences.length; i++) {
String s = scanner.next();
sentences[i] = s;
}
for (int i = 0; i < sentences.length; i++) {
Matcher matcher = pattern.matcher(sentences[i]);
while (matcher.find()) {
System.out.println(sentences[i]);
}
}
}
}
for (int i = 0; i <= sentences.length; i++) {
How many items are in the array? What is the last index? What is the last index your loop uses? How many sentances in total does your loop access?
Try this. It works.
Tips:
Make sure you use nextLine() so that the input will read full sentences. And I switched your while loop for an if statement within the for loop. No need for two loops there. And I also condensed your first for loop to just one line. No need to create a string variable if you only need it for a second. Just skip that step entirely and get to the point! Good luck, Hope this helps!
Below Is A Program That Mirrors Yours But Now Works
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Grep
{
public static void main(String[] args)
{
Pattern pattern = Pattern.compile("[Pp]attern");
String sentences[] = new String[3];
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter some sentences: ");
for (int i = 0; i < sentences.length; i++)
sentences[i] = scanner.nextLine();
for (int i = 0; i < sentences.length; i++)
{
Matcher matcher = pattern.matcher(sentences[i]);
if (matcher.find())
System.out.println(sentences[i]);
}
}
}
Below Is How I Would Write This Same Program. Comments Included For Clarification
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Grep
{
public static void main(String[] args)
{
// Initialize and Declare Variables
Pattern pattern = Pattern.compile("[Pp]attern");
String sentences[] = new String[3];
Scanner scanner = new Scanner(System.in);
int foundCount = 1;
// Present A Title For The End User
System.out.println("This Program Will Catch Sentences With The Term Pattern.\n");
// Read The Inputs From The Users
for (int i = 0; i < sentences.length; i++)
{
System.out.print("Enter Sentence #" + (i+1) + ": ");
sentences[i] = scanner.nextLine();
}
// Line Break
System.out.println();
// Write Sentences That Include The Term Pattern
for (int i = 0; i < sentences.length; i++)
{
Matcher matcher = pattern.matcher(sentences[i]);
if (matcher.find())
{
System.out.println(foundCount + ") " + sentences[i]);
foundCount++;
}
}
}
}
for (int i = 0; i <= sentences.length; i++) {
The <= needs to be < because you are starting from 0 and you have 10 items, so i has to go from 0 to 9.
The problem is in line :18 of your code which is for (int i = 0; i <= sentences.length; i++) it should be for (int i = 0; i < sentences.length; i++)
as you your own in the next for loop in your code has used < instead of <=
Try
for (int i = 0; i < sentences.length; i++)
and you'll be fine :)

Categories