A simple Java code that doesn't work well - java

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.

Related

I want to read those inputs in a single line separated by space in java without using String?

System.out.println("Number of pages + Number of lost pages + Number of Readers");
int n = s.nextInt();
int m = s.nextInt();
int q = s.nextInt();
I want to read input values all the values are going to be integer but I want to read it in a same line with changing it form Integer.
Assuming s is an instance of Scanner: Your code, as written, does exactly what you want.
scanners are created by default with a delimiter configured to be 'any whitespace'. nextInt() reads the next token (which are the things in between the delimiter, i.e. the whitespace), and returns it to you by parsing it into an integer.
Thus, your code as pasted works fine.
If it doesn't, stop setting up a delimiter, or reset it back to 'any whitespace' with e.g. scanner.reset(); or scanner.useDelimiter("\\s+");.
class Example {
public static void main(String[] args) {
var in = new Scanner(System.in);
System.out.println("Enter something:");
System.out.println(in.nextInt());
System.out.println(in.nextInt());
System.out.println(in.nextInt());
}
}
works fine here.

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?

Convert input strings into int array

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.

list.add(String) in LinkedList doesnt work properly for me

I want write program with this functionality:
User will input how many things he have. He will input these things and things will be added to the list.
I made this code :
public class lists {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
LinkedList<String> list= new LinkedList<String>();
System.out.println("How many things you have?");
int size=input.nextInt();
LinkedList<String> list= new LinkedList<String>();
System.out.println("Enter those things");
for(int c=1;c<=size;c++) list.add(input.nextLine().toString());
System.out.printf("%s",list);
}
}
For example Output for number 5 looks like this:
[, 1st Inputed, 2nd Inputed,3rd Inputed, 4nd inputed]
I want to know why the first String in the list is empty and it lets me input less things that I want. Thank you for your help.
Your code should be like this:
public class lists {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("How many things you have?");
int size=input.nextInt();
LinkedList<String> list= new LinkedList<String>();
System.out.println("Enter those things");
for(int c=0 ;c < size; c++)
{
String s = input.next();//use next() instead of nextLine()
list.add(s);
}
System.out.printf("%s",list);
}
}
Scanner.nextLine() as described in official document is:
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.
After nextInt() is called it isn't properly terminating the allocated line of memory. So when nextLine() is called first time it is actually terminating the previous line that actually had value in it -- entered via nextInt() rather than taking in a new String value.That's why the String at index 0 of list is blank. So , in order to carry on reading the entered value rather than the previous blank line (because of non-termination of value returned by nextInt()) you can use Scanner.next() which according to official document states that:
Finds and returns the next complete token from this scanner.
The issue is that input.nextInt() does not consume the trailing newline, so the first input.nextLine() returns an empty string.
There are several ways to work around this. I'll leave it as an exercise to figure out how best to do it.

System.out.println repeating itself

Would anyone point me in the right direction, of why when i use a for loop the println function comes up two times in the output. Thanks
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of employees to calculate:");
int numberEmployees = scan.nextInt();
for(int i=0; i<numberEmployees; i++){
System.out.println("Enter First Name:");
name = scan.nextLine();
System.out.println("Enter Last Name:");
last = scan.nextLine();
System.out.println("Enter Document #:");
document = scan.nextInt();
System.out.println("Enter Basic Salary");
basicSalary = scan.nextInt();
System.out.println("Enter # of Hours");
hours = scan.nextInt();
}
}
OUTPUT
Enter the number of employees to calculate:
1
Enter First Name:
Enter Last Name:
daniel
Enter Document #:
The problem is that when you entered 1 with a new line, the nextInt() function doesn't remove the newline that you had from entering in the 1. Change your calls to scan.nextInt() to Integer.parseInt(scan.nextLine()) and it should behave the way you want.
To further explain; here's stuff from the Java API.
A Scanner breaks its input into tokens using a delimiter pattern,
which by default matches whitespace. The resulting tokens may then be
converted into values of different types using the various next
methods.
and
The next() and hasNext() methods and their primitive-type companion
methods (such as nextInt() and hasNextInt()) first skip any input that
matches the delimiter pattern, and then attempt to return the next
token. Both hasNext and next methods may block waiting for further
input.
So, what evidently happens (I didn't see anything on the page to confirm it) is that after next(), hasNext(), and their related methods read in a token, they immediately return it without gobbling up delimiters (in our case, whitespace) after it. Thus, after it read in your 1, the newline was still there, and so the following call to nextLine() had a newline to gobble and did so.
It appears that the newline character remains in your input after the first entry. When the next input is requested, the Scanner sees a newline character and interprets it as the end of the input. This makes it appear to skip every other input request. I would suggest checking out the Java API docs as to the exact behavior of Scanner's methods.

Categories