in one line from the standard input I have 3 types of integers: the first integer is id, the second integer is N - some number, and after that follows N integers, separeted by a single space which I want to store in array or ArrayList. How can I do this using BufferedReader? I have the following code:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] line = br.readLine().split(" ");
int ID = Integer.parseInt(line[0]);
int N = Integer.parseInt(line[1]);
My question is is there any elegant way to read the rest of the line and to store it into array?
Use Scanner and method hasNextInt()
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
arr[i]=scanner.nextInt();
i++;
}
}
How can I do this using BufferedReader?
You've already read/split the line, so you can just loop over the rest of the inputted integers and add them to an array:
int[] array = new int[N]; // rest of the input
assert line.length + 2 == N; // or some other equivalent check
for (int i = 0; i < N; i++)
array[i] = Integer.parseInt(line[i + 2]);
This will also let you handle errors within the loop (I'll leave that part to you, should you find it necessary).
Related
I cannot get out of while loop.
I do not why sc.hasNextInt() does not return false after last read number.
Should I use another method or is there a mistake in my code?
public static void main(String[] args) {
// Creating an array by user keyboard input
Scanner sc = new Scanner(System.in);
System.out.println("Length of array: ");
int[] numbers = new int[sc.nextInt()];
System.out.printf("Type in integer elements of array ", numbers.length);
int index = 0;
**while ( sc.hasNextInt()) {**
numbers[index++] = sc.nextInt();
}
// created method for printing arrays
printArray(numbers);
sc.close();
}
Do the following:
Use the input length as the end of the loop.
// Creating an array by user keyboard input
Scanner sc = new Scanner(System.in);
System.out.println("Length of array: ");
int len = sc.nextInt();
int[] numbers = new int[len]; // use len here
System.out.printf("Type in integer elements of array ", numbers.length);
int index = 0;
for (index = 0; index < len; index++) { // and use len here
numbers[index] = sc.nextInt();
}
// created method for printing arrays
printArray(numbers);
sc.close();
And don't close the scanner.
When you are receiving your input from the console, the Scanner hasNextInt() method placed inside a while loop condition will continue to read (meaning the loop will continue), until one of the following happens:
You submit a non-numeric symbol (e.g. a letter).
You submit a so-called "end of file" character, which is a special symbol telling the Scanner to stop reading.
Thus, in your case you cannot have the hasNextInt() inside your while loop condition - I am showing a solution below with a counter variable that you can use.
However, the hasNextInt() method inside a while loop has its practical usage for when reading from a different source than the console - e.g. from a String or a file. Inspired from the examples here, suppose we have:
String s = "Hello World! 3 + 3.0 = 6 ";
We can then pass the string s as an input source to the Scanner (notice that we are not passing System.in to the constructor):
Scanner scanner = new Scanner(s);
Then loop until hasNext(), which checks if there is another token of any type in the input. Inside the loop, perform a check if this token is an int using hasNextInt() and print it, otherwise pass the token to the next one using next():
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
System.out.println("Found int value: " + scanner.next());
} else {
scanner.next();
}
}
Result:
Found int value: 3
Found int value: 6
In the example above, we cannot use hasNextInt() in the while loop condition itself, because the method returns false on the first non-int character that it finds (so the loop closes immediately, as our String begins with a letter).
However, we could use while (hasNextInt()) to read the list of numbers from a file.
Now, the solution to your problem would be to place the index variable inside the while loop condition:
while (index < numbers.length) {
numbers[index++] = sc.nextInt();
}
Or for clarity`s sake, make a specific counter variable:
int index = 0;
int counter = 0;
while (counter < numbers.length) {
numbers[index++] = sc.nextInt();
counter++;
}
I have to make a method to print out the elements in an array, separated by ‘‘|’’
#param values, an array of integers.
Essentially its suppose to take user input, and then from there separate it with |. This is what I have so far. Any help chaps?
int [] scans = new int [3];
System.out.println("Enter 4 Numbers into the array: " );
Scanner scanner = new Scanner(System.in);
int s = scanner.nextInt();
for (int i = 0; i < scans.length; i++)
{
scans [i] = scanner.nextInt();
}
First, you're ignoring the first input number by assigning it to s, but you never use that thereafter. For the joining problem, you can use a stream. Below will ask the user to input 3 numbers, save them to your int[3] and output it joined by |
int [] scans = new int[3];
System.out.println("Enter 3 Numbers into the array: " );
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < scans.length; i++) {
scans [i] = scanner.nextInt();
}
String joined = Arrays.stream(scans)
.mapToObj(String::valueOf)
.collect(Collectors.joining("|"));
System.out.println(joined);
Here is a solution that might be easier to understand without using the mapToObj solution #baao used (which is fine, but maybe harder to understand if your new to Java).
First of all if you want to store 4 numbers in the array, then your array should hold 4 not 3 elements. Another trick you can use is to create a prefix variable that is used to prepend each number in a loop over the values in the array. After the first iteration the prefix should be set to your separator variable.
You can see it working here: https://ideone.com/QCNPZQ
int [] scans = new int[4];
System.out.println("Enter 4 numbers into the array: " );
Scanner scanner = new Scanner(System.in);
for (int i=0; i<scans.length; i++) {
scans [i] = scanner.nextInt();
}
String prefix = "";
String result = "";
for(int i=0; i<scans.length; i++){
result = result + prefix + scans[i];
prefix = "|";
}
System.out.println(result);
I am using BufferedReader class to read inputs in my Java program.
I want to read inputs from a user who can enter multiple integer data in single line with space.
I want to read all these data in an integer array.
Input format-
the user first enters how many numbers he/she want to enter
And then multiple integer values in the next single line-
INPUT:
5
2 456 43 21 12
Now, I read input using an object (br) of BufferedReader
int numberOfInputs = Integer.parseInt(br.readLine());
Next, I want to read next line inputs in an array
int a[] = new int[n];
But we cannot read using this technique
for(int i=0;i<n;i++)
{
a[i]=Integer.parseInt(br.readLine()); //won't work
}
So, is there any solution to my problem or we can't just read multiple integers from one line using BufferedReader objects
Because using Scanner object we can read this type of input
for(int i=0;i<n;i++)
{
a[i]=in.nextInt(); //will work..... 'in' is object of Scanner class
}
Try the next:
int a[] = new int[n];
String line = br.readLine(); // to read multiple integers line
String[] strs = line.trim().split("\\s+");
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(strs[i]);
}
Late to the party but you can do this in one liner in Java 8 using streams.
InputStreamReader isr= new InputStreamReader();
BufferedReader br= new BufferedReader(isr);
int[] input = Arrays.stream(br.readLine().split("\\s+")).mapToInt(Integer::parseInt).toArray();
If you want to read integers and you didn't know number of integers
String[] integersInString = br.readLine().split(" ");
int a[] = new int[integersInString.length];
for (int i = 0; i < integersInString.length; i++) {
a[i] = Integer.parseInt(integersInString[i]);
}
Integer.parseInt(br.readLine()) -> Reads a whole line and then converts it to Integers.
scanner.nextInt() -> Reads every single token one by one within a single line then tries to convert it to integer.
String[] in = br.readLine().trim().split("\\s+");
// above code reads the whole line, trims the extra spaces
// before or after each element until one space left,
// splits each token according to the space and store each token as an element of the string array.
for(int i = 0; i < n; i++)
arr[i] = Integer.parseInt(in[i]);
// Converts each element in the string array as an integer and stores it in an integer array.
import java.io.*;
public class HelloWorld{
public static void main(String []args){
int i;
System.out.println("enter the array element");
InputStreamReader isr= new InputStreamReader();
BufferedReader ib= new BufferedReader(isr);
int a[]=new int [5];
for(i=0;i<5;i++)
{
a[i]= Integer.parseInt(ib.readLine(a[i]));
}
for(i=0;i<5;i++)
{
System.out.println(a[i]);
}
}
}
I use this code for List:
List<Integer> numbers = Stream.of(reader.readLine().split("\\s+")).map(Integer::valueOf).collect(Collectors.toList());
And it is almost the same for array:
int[] numbersArray = Arrays.stream(reader.readLine().split("\\s+")).mapToInt(Integer::valueOf).toArray();
You can use StringTokenizer class of java.util package. The StringTokenizer class allows an application to break a string into tokens. You can use this tokens using nextToken() method of StringTokenizer class.
You can use following constructor of StringTokenizer:
StringTokenizer(String str, String delimiter);
you can use space(" ") as delemeter.
int a[] = new int[N];
StringTokenizer st = new StringTokenizer(br.readLine() , " ");
for(int i=0 ; i<N ; i++) {
a[i] = Integer.parseInt(st.nextToken());
}
Well as you mentioned there are two lines-
First line takes number of integers and second takes that many number
INPUT: 5 2 456 43 21 12
So to address this and covert it into array -
String[] strs = inputData.trim().split("\\s+"); //String with all inputs 5 2 456 43 21 12
int n= Integer.parseInt(strs[0]); //As you said first string contains the length
int a[] = new int[n]; //Initializing array of that length
for (int i = 0; i < n; i++)
{
a[i] = Integer.parseInt(strs[i+1]); // a[0] will be equal to a[1] and so on....
}
i/p:34 54
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine()," ");
for(int i=0;i<st.countTokens();i++){
a=Integer.parseInt(st.nextToken());
b=Integer.parseInt(st.nextToken());
}
//For fast input output for one line
I am working on a program and I want to allow a user to enter multiple integers when prompted. I have tried to use a scanner but I found that it only stores the first integer entered by the user. For example:
Enter multiple integers: 1 3 5
The scanner will only get the first integer 1. Is it possible to get all 3 different integers from one line and be able to use them later? These integers are the positions of data in a linked list I need to manipulate based on the users input. I cannot post my source code, but I wanted to know if this is possible.
I use it all the time on hackerrank/leetcode
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String lines = br.readLine();
String[] strs = lines.trim().split("\\s+");
for (int i = 0; i < strs.length; i++) {
a[i] = Integer.parseInt(strs[i]);
}
Try this
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
if (in.hasNextInt())
System.out.println(in.nextInt());
else
in.next();
}
}
By default, Scanner uses the delimiter pattern "\p{javaWhitespace}+" which matches at least one white space as delimiter. you don't have to do anything special.
If you want to match either whitespace(1 or more) or a comma, replace the Scanner invocation with this
Scanner in = new Scanner(System.in).useDelimiter("[,\\s+]");
You want to take the numbers in as a String and then use String.split(" ") to get the 3 numbers.
String input = scanner.nextLine(); // get the entire line after the prompt
String[] numbers = input.split(" "); // split by spaces
Each index of the array will hold a String representation of the numbers which can be made to be ints by Integer.parseInt()
Scanner has a method called hasNext():
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext())
{
System.out.println(scanner.nextInt());
}
If you know how much integers you will get, then you can use nextInt() method
For example
Scanner sc = new Scanner(System.in);
int[] integers = new int[3];
for(int i = 0; i < 3; i++)
{
integers[i] = sc.nextInt();
}
Java 8
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int arr[] = Arrays.stream(in.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
Here is how you would use the Scanner to process as many integers as the user would like to input and put all values into an array. However, you should only use this if you do not know how many integers the user will input. If you do know, you should simply use Scanner.nextInt() the number of times you would like to get an integer.
import java.util.Scanner; // imports class so we can use Scanner object
public class Test
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner( System.in );
System.out.print("Enter numbers: ");
// This inputs the numbers and stores as one whole string value
// (e.g. if user entered 1 2 3, input = "1 2 3").
String input = keyboard.nextLine();
// This splits up the string every at every space and stores these
// values in an array called numbersStr. (e.g. if the input variable is
// "1 2 3", numbersStr would be {"1", "2", "3"} )
String[] numbersStr = input.split(" ");
// This makes an int[] array the same length as our string array
// called numbers. This is how we will store each number as an integer
// instead of a string when we have the values.
int[] numbers = new int[ numbersStr.length ];
// Starts a for loop which iterates through the whole array of the
// numbers as strings.
for ( int i = 0; i < numbersStr.length; i++ )
{
// Turns every value in the numbersStr array into an integer
// and puts it into the numbers array.
numbers[i] = Integer.parseInt( numbersStr[i] );
// OPTIONAL: Prints out each value in the numbers array.
System.out.print( numbers[i] + ", " );
}
System.out.println();
}
}
There is more than one way to do that but simple one is using String.split(" ")
this is a method of String class that separate words by a spacial character(s) like " " (space)
All we need to do is save this word in an Array of Strings.
Warning : you have to use scan.nextLine(); other ways its not going to work(Do not use scan.next();
String user_input = scan.nextLine();
String[] stringsArray = user_input.split(" ");
now we need to convert these strings to Integers. create a for loop and convert every single index of stringArray :
for (int i = 0; i < stringsArray.length; i++) {
int x = Integer.parseInt(stringsArray[i]);
// Do what you want to do with these int value here
}
Best way is converting the whole stringArray to an intArray :
int[] intArray = new int[stringsArray.length];
for (int i = 0; i < stringsArray.length; i++) {
intArray[i] = Integer.parseInt(stringsArray[i]);
}
now do any proses you want like print or sum or... on intArray
The whole code will be like this :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String user_input = scan.nextLine();
String[] stringsArray = user_input.split(" ");
int[] intArray = new int[stringsArray.length];
for (int i = 0; i < stringsArray.length; i++) {
intArray[i] = Integer.parseInt(stringsArray[i]);
}
}
}
This works fine ....
int a = nextInt();
int b = nextInt();
int c = nextInt();
Or you can read them in a loop
Using this on many coding sites:
CASE 1: WHEN NUMBER OF INTEGERS IN EACH LINE IS GIVEN
Suppose you are given 3 test cases with each line of 4 integer inputs separated by spaces 1 2 3 4, 5 6 7 8 , 1 1 2 2
int t=3,i;
int a[]=new int[4];
Scanner scanner = new Scanner(System.in);
while(t>0)
{
for(i=0; i<4; i++){
a[i]=scanner.nextInt();
System.out.println(a[i]);
}
//USE THIS ARRAY A[] OF 4 Separated Integers Values for solving your problem
t--;
}
CASE 2: WHEN NUMBER OF INTEGERS in each line is NOT GIVEN
Scanner scanner = new Scanner(System.in);
String lines=scanner.nextLine();
String[] strs = lines.trim().split("\\s+");
Note that you need to trim() first: trim().split("\\s+") - otherwise, e.g. splitting a b c will emit two empty strings first
int n=strs.length; //Calculating length gives number of integers
int a[]=new int[n];
for (int i=0; i<n; i++)
{
a[i] = Integer.parseInt(strs[i]); //Converting String_Integer to Integer
System.out.println(a[i]);
}
created this code specially for the Hacker earth exam
Scanner values = new Scanner(System.in); //initialize scanner
int[] arr = new int[6]; //initialize array
for (int i = 0; i < arr.length; i++) {
arr[i] = (values.hasNext() == true ? values.nextInt():null);
// it will read the next input value
}
/* user enter = 1 2 3 4 5
arr[1]= 1
arr[2]= 2
and soo on
*/
It's working with this code:
Scanner input = new Scanner(System.in);
System.out.println("Enter Name : ");
String name = input.next().toString();
System.out.println("Enter Phone # : ");
String phone = input.next().toString();
A simple solution can be to consider the input as an array.
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); //declare number of integers you will take as input
int[] arr = new int[n]; //declare array
for(int i=0; i<arr.length; i++){
arr[i] = sc.nextInt(); //take values
}
You're probably looking for String.split(String regex). Use " " for your regex. This will give you an array of strings that you can parse individually into ints.
Better get the whole line as a string and then use StringTokenizer to get the numbers (using space as delimiter ) and then parse them as integers . This will work for n number of integers in a line .
Scanner sc = new Scanner(System.in);
List<Integer> l = new LinkedList<>(); // use linkedlist to save order of insertion
StringTokenizer st = new StringTokenizer(sc.nextLine(), " "); // whitespace is the delimiter to create tokens
while(st.hasMoreTokens()) // iterate until no more tokens
{
l.add(Integer.parseInt(st.nextToken())); // parse each token to integer and add to linkedlist
}
Using BufferedReader -
StringTokenizer st = new StringTokenizer(buf.readLine());
while(st.hasMoreTokens())
{
arr[i++] = Integer.parseInt(st.nextToken());
}
When we want to take Integer as inputs
For just 3 inputs as in your case:
import java.util.Scanner;
Scanner scan = new Scanner(System.in);
int a,b,c;
a = scan.nextInt();
b = scan.nextInt();
c = scan.nextInt();
For more number of inputs we can use a loop:
import java.util.Scanner;
Scanner scan = new Scanner(System.in);
int a[] = new int[n]; //where n is the number of inputs
for(int i=0;i<n;i++){
a[i] = scan.nextInt();
}
This method only requires users to enter the "return" key once after they have finished entering numbers:
It also skips special characters so that the final array will only contains integers
ArrayList<Integer> nums = new ArrayList<>();
// User input
Scanner sc = new Scanner(System.in);
String n = sc.nextLine();
if (!n.isEmpty()) {
String[] str = n.split(" ");
for (String s : str) {
try {
nums.add(Integer.valueOf(s));
} catch (NumberFormatException e) {
System.out.println(s + " cannot be converted to Integer, skipping...");
}
}
}
//Get user input as a 1 2 3 4 5 6 .... and then some of the even or odd number like as 2+4 = 6 for even number
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int evenSum = 0;
int oddSum = 0;
while (n > 0) {
int last = n % 10;
if (last % 2 == 0) {
evenSum += last;
} else {
oddSum += last;
}
n = n / 10;
}
System.out.println(evenSum + " " + oddSum);
}
}
if ur getting nzec error, try this:
try{
//your code
}
catch(Exception e){
return;
}
i know it's old discuss :) i tested below code it's worked
`String day = "";
day = sc.next();
days[i] = Integer.parseInt(day);`
How can i get the value of a java array using Scanner class with a fixed length of 2, and which will iterate until its value is equal to a given value?
For example; for the following inputs,
A G
N H
D F
I wrote a for loop to take the values of fixed array road, in which the length is 2 using Scanner class.
for(int i = 0; i<block.length; i++){
System.out.println("enter number");
block[i]=input2.next().charAt(0);
}
I want to iterate this loop while the user input is {'C','C'}. THat means the array loop shpuld stop if the inputs are as follow;
A G
N H
D F
C C
How can i write the code to take user input values using Scanner class and to iterate the array? And the user input values should be copied without replacing them with newly entered values.
Thank you!
Try this way:
Scanner input2 = new Scanner(System.in);
char[] block = new char[2];
ArrayList<String> arrayList = new ArrayList<String>();
int i = 0;
o:
while (block[0] != 'C' && block[1] != 'C') {
System.out.println("enter character");
block[i % 2] = input2.next().charAt(0);
i++;
arrayList.add(input2.next());
if(arrayList.size()>=2){
if(arrayList.get(arrayList.size()-1).equals("C") && arrayList.get(arrayList.size()-2).equals("C"))
{
break o;
}
}
}
System.out.println(arrayList);
assuming that your block and input2 variables are already set up and your loop as shown is working, put that loop inside a controller loop
do {
for(int i = 0; i<block.length; i++){
System.out.println("enter number");
block[i]=input2.next().charAt(0);
}
} while (block[0] != 'C" && block[1] != 'C' )
All you need is this
char[] block = new char[2];
while (block[0] != 'C' && block[1] != 'C') {
System.out.println("enter number");
block[0]=input2.next().charAt(0);
System.out.println("enter number");
block[1]=input2.next().charAt(0);
}
I assume the following from your question
You have an array of fixed length into which you would like to read
values using a Scanner
Once you read values into the array,you would like to compare this
array with values from another array and do something if the input
array matches your array.
This is a simple program that does this:
String[] scannedValues=new String[2];
String[] matchValue={"X","Y"};
boolean isMatched=false;
Scanner s=new Scanner(System.in);
while(!isMatched)
{
for(int i=0;i<scannedValues.length;i++)
{
scannedValues[i]=s.nextLine();
}
for(int i=0;i<scannedValues.length;i++)
{
if(matchValue[i].equals(scannedValues[i]))
isMatched=true;
else
isMatched=false;
}
if(isMatched)
s.close();
}
You can use some of the Scanner methods such as nextInt() etc for finding various types of values.You can also pass regular expressions to the Scanner such as next("[A-Z]{1}")
However,in case you use a regular expression be aware that a mismatch between the input provided by the user and your expression will cause an InputMismatchException.