Convert input strings into int array - java

I want to read in five numbers from the console. To convert the input strings into int[x] for each number i tried to use a for loop. But it turns out that #1 incrementation is dead code and #2 my array is not initialized, even though i just did.
I'm on my first Java practices and would be happy to hear some advices.
My code:
public static void main(String[] args) throws IOException {
System.out.println("Type in five Numbers");
int [] array;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
for(int x=0; x<5; x++){
String eingabe = br.readLine();
array[x] = Integer.parseInt(eingabe);
break;
}
reserve(array); }

First off, you didn't initialize your array, you only declared an array variable (named array). I highly suggest reading and practicing this fundamental concept of Java before proceeding further, because otherwise you will likely be confused later on. You can read more about the terms declaration, initialization, and assignment here.
Another issue, as Andrew pointed out, is that you used the keyword break in your first iteration of the loop. This keyword terminates a block of code, so your loop will only run once and then exit for good.
This code can be greatly simplified with a Scanner. A Scanner reads input from a specified location. The scanner's constructor accepts two inputs: System.in, for the default input device on your computer (keyboard), or a File object, such as a file on your computer.
Scanners, by default, have their delimeter set to the whitespace. A delimeter specifies the boundary between successive tokens, so if you input 2 3 5 5, for example, and then run a loop and invoke the scanVarName.nextInt() method, it will ignore the white spaces and treat each integer in that single line as its own token.
So if I understand correctly, you want to read input from the user (who will presumably enter integers) and you want to store these in an integer array, correct? You can do so using the following code if you know how many integers the user will enter. You can first prompt them to tell you how many integers they plan to enter:
// this declares the array
int[] array;
// declares and initializes a Scanner object
Scanner scan = new Scanner(System.in);
System.out.print("Number of integers: ");
int numIntegers = scan.nextInt();
// this initializes the array
array = new int[numIntegers];
System.out.print("Enter the " + numIntegers + " integers: ");
for( int i = 0; i < numIntegers; i ++)
{
// assigns values to array's elements
array[i] = scan.nextInt();
}
// closes the scanner
scan.close();
You can then use a for-each loop to run through the items in your array and print them out to confirm that the above code works as intended.

Related

How can user inputs be typed in so that I can separate each value by a comma instead of pressing Enter after each value?

Instead of having to press Enter after each value input with Scanner, is there a way to type all values at once, and then press enter and be done?
import java.util.Arrays;
import java.util.Scanner;
class Arrayex {
public static void main(String[] args)
{
int [] numbers = new int[5];
Scanner s=new Scanner(System.in);
System.out.println("Current array: " + Arrays.toString(numbers));
System.out.println("Type in the numbers: ");
for(int i=0; i< numbers.length; i++)
{
numbers[i] = s.nextInt();
}
System.out.println("Array elements are: " + Arrays.toString(numbers));
}
}
Current array input by pressing Enter after every number
How I want to type in the numbers into the array
My friend told me I can use a String array and convert it to int array and type the string as "1,2,3,4,5".
Wouldn't this only use up the location at numbers[0] instead of numbers[0] to numbers[5]?
Enter all int elements in one line using space, it will use as separate int values.
it will look like this.
No need to take input as String and parse it to an integer.
(White)space as delimiter
As others have noted, if you just use space as separator, then you could leverage the Scanner to convert the input to ints. The input 2 3 5 7 11 will yield an int[] with the given integers als elements.
Comma as delimiter
If you want to use comma as delimiter instead, the current code won't work. The input 2,3,5,7,11 will indeed try to shove 2,3,5,7,11 into numbers[0], which obviously will fail, and an InputMismatchException will be thrown at you.
Instead, you could set the delimiter:
Scanner s = new Scanner(System.in);
s.useDelimiter("[,\n]")
This will cause the Scanner to process the tokens between each comma or newline as separate elements.
Note that we couldn't just use , alone, because then the Scanner keeps reading from System.in indefinitely.

How to finish program with "Scanner.hasNext" in Java

I'm wondering how the program with "java scanner" can be finished
especially when I use this with System.in and scanner.hasNext()
Scanner sc = new Scanner(System.in);
For example, when I run the code below on some IDE
public static void main(String[] args){
Scanner sc = new Scanner(System.in)
int[] arr = new int[3];
int i = 0;
// put all the number from scanner to the array.
while(sc.hasNext()){
arr[i++] = sc.nextInt();
}
System.out.println(Arrays.toString(arr));
and input some numbers(for the inputs for scanner) in the console,
it doesn't stop receiving the numbers.
I wanted to use sc.hasNext() for the purpose of after finishing getting some input for the user, putting all the numbers received, as I commented on the code.
How can I finish the scanner getting the input on console?
Your code will run while stdin (System.in in Java) is open. You could close it programmatically if you want but it's usually done by pressing Ctrl+d
in the terminal that program is running (Shortcut is for Linux/macOS in Windows console it's Ctrl+z I think).
The Scanner will continue to read until it finds an "end of file" condition.
As you're reading from stdin, that'll either be when you send an EOF character (usually ^d on Unix), or at the end of the file if you use < style redirection.
However, to put the input from the user in your array, can be done by replacing your while condition with this:
while (sc.hasNext() && i!=arr.length) {
arr[i++] = sc.nextInt();
}
Since your store the user's input inside a fixed size (4) structure, you can use a for loop,
after all this is the case to use it:
when the number of repetitions is predefined
for (int i = 0; i < arr.length; i++){
arr[i] = sc.nextInt();
}
You don't need to put the condition for hasNext as it will always return true after entering an input.
You should have a condition on array length.
try this
int[] arr = new int[3];
int i = 0;
while(i<arr.length)
arr[i++] = sc.nextInt();
System.out.println(Arrays.toString(arr));
just add a condition in while as you limit your array to a specific length so when it reach this length t can't take any more input and it will just close the loop and print your array
like this:
Scanner sc = new Scanner(System.in);
int[] arr = new int[3];
int i = 0;
// put all the number from scanner to the array.
while(sc.hasNext() && i < arr.length){
arr[i++] = sc.nextInt();
}
System.out.println(Arrays.toString(arr));
You can change your while loop and put a conditional break when your number of integers reach array length. Try this,
while (sc.hasNext()) {
arr[i++] = sc.nextInt();
if (i == arr.length) {
break;
}
}
Or you can write it as a simple for loop,
// int i = 0;
for (int i = 0; i<arr.length;i++) {
arr[i] = sc.nextInt();
}
Here it will be useful for you to understand how sc.nextInt() works.
Whenever sc.nextInt() gets executed, the scanner objects sc looks for an integer and returns the next integer it finds in the stream scanned by sc object. If it doesn't find an integer in the stream, it will throw some Exception.
Now coming to your code, when your while loop gets executed, every time the code gets inside while loop, it calls sc.nextInt() and one integer is read and assigned into the array but as you have declared your array size as 3 only you need to break the loop else it will try to access an index greater than 3 in your array and will result into ArrayIndexOutOfBounds exception which you will not want. Due to which I have put that condition in while loop and it breaks as soon as the index reaches 3. Similar thing is achieved in the for loop. Hope my explanation helps. Let me know if you have any queries further.
Another thing you could have done is, change sc.hasNext() to sc.hasNextInt() in your while loop as hasNext() captures any data (integer or non-integer) from the stream and returns true and you would not want it to return true if the next incoming data is not an integer else that will run into exception.
Once you change sc.hasNext() to sc.hasNextInt() in while loop condition, your program will automatically end once you provide 3 integers as input to your program but if user tried to enter more than 3 integers, it will run into ArrayIndexOutOfBounds exception as your array length is limited to 3 only. Hence you need that condition if (i==arr.length) { break; } So your while loop can also be like this,
while (sc.hasNextInt()) {
arr[i++] = sc.nextInt();
if (i == arr.length) {
break;
}
}

is it possible to scan multiple lines of input, each line a new element in an array, when you copy/paste?

Trying to populate an array with input through the scanner .nextLine() function. The problem specifications give a sample input as follows:
3 5 4
abc
bca
dac
dbc
cba
(ab)(bc)(ca)
abc
(abc)(abc)(abc)
(zyx)bc
Just as I copied and pasted that whole chunk into this box, I'd like to do the same with my code, but when I try, the code only reads in the last line. I want each line to be read in and stored in it's own index in the array, NOT a multi-line string in one index or only the last line being read in and stored (which is what is happening now).
This is my method for initializing the array, which I've tested and it works when I feed in the input line by line, but that's just really annoying to be honest.
public static void initialize_array(String [] arr)
{
Scanner kbreader = new Scanner(System.in);
for (int i = 0 ; i < arr.length ; i++)
{
arr[i] = kbreader.nextLine();
System.out.println("this is just loading in: " + arr[i]);
}
}
When I run the program, (it also takes in 3 integers at the top and I print them just to test them, but that's not important) it only registers the last line.
A screenshot:
enter image description here
I think I've done something like this in C, but that might be because I used scanf() and C is relatively low level so it literally had to walk through the entire chunk.
It might not be possible, but I figured I'd ask to see.
Also, just so you know this is for practice, not an actual graded assignment or anything important, so don't hold anything back. :)
If you know the exact length of the array, then this would work:
Scanner scn = new Scanner(System.in);
scn.useDeliminator("\n");
for (int i = 0 ; i < arr.length ; i++)
{
arr[i] = scn.next();
System.out.println("this is just loading in: " + arr[i]);
}
The key here is the useDeliminator method call. The next methods reads from the stream until it reaches the deliminator pattern. In this case, it is \n, a new line. Please use the new line character of your OS.
This may be off point, but have you tried just using array.add(scanner.next()) and looping until scanner.hasNext() returns false?

How can i create as many scanners as the user wants

I want to write a code that will allow the user to pick how many scanners he wants to use. First I created a simple scanner and assigned an int to it
Scanner scanner = new Scanner(System.in);
int input = scanner.nextInt();
now the user will enter ANY integer (ex. 7). Then I want the program to create an array of scanners that will then allow a number of lines of input (in this case 7). Any help is appreciated!
To create a specific number of objects and store them somewhere you can easily use arrays:
Scanner[] scanners = new Scanner[num_of_scanners];
At this point you will have an array of null scanner objects. To declare them properly you have to use a loop like this:
for (int i = 0; i < scanners.length; i++)
{
scanners[i] = new Scanner(System.in);
}
Now you succesfully initialized all the scanners. To get your scanner at certain index see the example below:
Scanner first_scanner = scanners[0];
More on arrays here.

A simple Java code that doesn't work well

The following simple code in Java behaves somewhat in a strange way that I can not understand.
final public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("\nHow many names? ");
int n = sc.nextInt();
String[] a = new String[n];
a[0] = sc.nextLine(); //This line serves no purpose at all. It's useless and should be removed.
for (int i=0; i<n; i++)
{
System.out.print("\nEnter the name:->");
a[i] = sc.nextLine(); //request for input only inside the loop.
}
for (int i=0; i<a.length; i++)
{
System.out.println(a[i]);
}
}
}
The above is working well with no problem at all and displays the number of names inputted into the array a[] on the console but when I remove the line a[0] = sc.nextLine(); //This line serves no purpose at all. It's useless and should be removed., it displays for number of users first. let's say 3. there is no problem but when the loop starts iterating, it will ask for the name and first time the message Enter the name:-> is displayed twice
and the output would be something like shown below.
How many names? 3
Enter the name:-> Don't allow to enter the name here.
Enter the name:->Tiger
Enter the name:->Pitter
Tiger
Pitter
Although I entered 3 for "How many names?", it allows only two names to enter. Why?
Note again that the code shown above is working well. The problem occurs only when the line specified with bold latters in the above paragraph is commented out.
When you use Scanner.nextInt(), it does not consume the new line (or other delimiter) itself so the next token returned will typically be an empty string. Thus, you need to follow it with a Scanner.nextLine(). You can discard the result instead of assigning it to a[0]:
int n = sc.nextInt();
sc.nextLine();
It's for this reason that I suggest always using nextLine (or BufferedReader.readLine()) and doing the parsing after using Integer.parseInt().
You are reading three lines. The problem you have is that nextInt() reads an int value, it doesn't read and consume the end of the line. (A common mistake)
You need the nextLine() after it to say that you want to ignore the rest of the line.
The nextInt call reads from input until the end of the int, but does not read the newline character after the int. So, the first iteration displays "enter the name", then calls nextLine() which reads the end of the line where you typed the number of players (an empty string). Then the second iteration starts and displays "enter the name", and nextLine() blocks until you type a newline character.

Categories