Cannot get input in simple output program in Java - java

I will keep this short and simple, here's the program-
class Sample{
private int n;
public void getDetails(){
Scanner y=new Scanner(System.in);
n=y.nextInt();
System.out.println("Entered 'n' = "+n);
}
public void displayDetails(){
int i,j;
int arr[]=new int[n];
Scanner x=new Scanner(System.in);
for(j=0;j<n;j++) {
arr[j] = x.nextInt();
System.out.println("Entered element = "+arr[j]);
}
System.out.println("Entered array: ");
for(i=0;i<n;i++)
System.out.print(arr[i]+" ");
}
}
public class TestClass {
public static void main(String[] args) {
Sample obj = new Sample();
obj.getDetails();
obj.displayDetails();
}
}
This simple program just takes number of elements(n) and the elements of array(arr[]) as input in different methods.
When the input is given in interactive mode, everything works fine. Here's the console output-
5
Entered 'n' = 5
1 2 3 4 5
Entered element = 1
Entered element = 2
Entered element = 3
Entered element = 4
Entered element = 5
Entered array:
1 2 3 4 5
But when I give it as Stdin input(or all input at once), it just takes the number of elements(n) and ignores my array input(arr[]). Here I had to give the array elements again. Console output-
5
1 2 3 4 5Entered 'n' = 5
1
Entered element = 1
2
Entered element = 2
3 4 5
Entered element = 3
Entered element = 4
Entered element = 5
Entered array:
1 2 3 4 5
I have no idea what is happening. Is it a bug? Please help

Part of the problem is that you are creating multiple scanners. Create one scanner and use it everywhere, like so:
import java.util.Scanner;
public class TestClass {
public static void main(String[] args) {
Sample obj = new Sample();
obj.getArraySize();
obj.displayDetails();
}
}
class Sample{
private int arraySize;
Scanner scanner = new Scanner(System.in);
public void getArraySize(){
System.out.print("Enter size of array: ");
arraySize = scanner.nextInt();
System.out.println("Entered array size = " + arraySize);
}
public void displayDetails(){
//Create an integer array of size arraySize
int intArray[] = new int[arraySize];
//Repeatedly request integers for the array
for( int i=0; i<arraySize; i++) {
int nextInt = scanner.nextInt();
intArray[i] = nextInt;
System.out.println("Entered element = " + intArray[i]);
}
//Print out the entered elements
System.out.println("Entered array: ");
for( int i=0; i<arraySize; i++) {
System.out.print(intArray[i]+" ");
}
scanner.close();
}
}
console output:
Enter size of array: 5
Entered array size = 5
5 4 3 2 1
Entered element = 5
Entered element = 4
Entered element = 3
Entered element = 2
Entered element = 1
Entered array:
5 4 3 2 1
You still need to check that the next value is actually an int. If you put a different type of value in there, like a letter, it will crash. See these links for additional details:
https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html
Java Multiple Scanners
Why is not possible to reopen a closed (standard) stream?

You areusing scanner to take userinput.
Scanner y=new Scanner(System.in);
In Scanner class if we call nextLine() method after any one of the seven nextXXX() method then the nextLine() doesn’t not read values from console and cursor will not come into console it will skip that step. The nextXXX() methods are nextInt(), nextFloat(), nextByte(), nextShort(), nextDouble(), nextLong(), next().
In BufferReader class there is no such type of problem. This problem occurs only for Scanner class, due to nextXXX() methods ignore newline character and nextLine() only reads newline character. If we use one more call of nextLine() method between nextXXX() and nextLine(), then this problem will not occur because nextLine() will consume the newline character.
Please check this SO link it has good explaination.

Related

Using scanner various times in a loop Java

I'm new in this, i'm trying to write a code which stores user input in a array of n length (the length is also decided by the user).
So I decided to use a while loop to use Scanner n times, so that each time the user could store an String in that location as the loop advances.
But when I run the code, it just prints the statements don't letting me (or the user) to input the String.
public static void main(String[] args) {
String[] contadores;
Scanner cont= new Scanner(System.in);
System.out.println("Input the length of the array + 1: ");
int cuenta = cont.nextInt();
// Thread.sleep(4000);
contadores = new String[cuenta];
Scanner d = new Scanner(System.in);
int i=0;
while (i<= (contadores.length-1)) {
System.out.println("Input the word in the space: "+(i));
String libro = d.toString();
contadores[i] = libro;
i++;
}
When I run it, the output is:
Input the length of the array + 1:
3
Input the word in the space: 0
Input the word in the space: 1
Input the word in the space: 2
As you see it doesn't give me enough time to input something, I don't know if it JDK (I think not), or it is because is inside the main, I tried using Thread.sleep(4000); but the output is an error Unhandled exception type InterruptedException.
The problem is that you are not scanning inside the while loop. You need to scan the words the way you have scanned the integer. Instead of using d.next(), you've used d.toString().
Do it as follows:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String[] contadores;
Scanner cont = new Scanner(System.in);
System.out.print("Input the length of the array: ");
int cuenta = cont.nextInt();
contadores = new String[cuenta];
int i = 0;
while (i < contadores.length) {
System.out.print("Input the word for the index " + (i) + ": ");
String libro = cont.next();
contadores[i] = libro;
i++;
}
// Display the array
for (String s : contadores) {
System.out.println(s);
}
}
}
A sample run:
Input the length of the array: 4
Input the word for the index 0: Hello
Input the word for the index 1: World
Input the word for the index 2: Good
Input the word for the index 3: Morning
Hello
World
Good
Morning
Also, note that I've used only one instance of Scanner. You do not need two instances of Scanner. You can reuse the same instance of Scanner everywhere in your program.

modifying arrays in java

So I'm trying to figure out how to take user input thru the Scanner object, place it in each slot of an array, then read those numbers back to the user plus one. Problem is I have to use a a loop for the read back statement.Heres what I have so far. I figured out the first loop fine with the scanner, but I don't know how to modify each element in the array using a loop.
import java.util.Scanner;
public class Lab7
{
public static void main(String [] Args)
{
Scanner console = new Scanner(System.in);
System.out.println("Enter your 5 integers: ");
int index =0;
final int SIZE = 5;
int[] arrayOfSize = new int[SIZE];
while(index<arrayOfSize.length )
{
arrayOfSize[index]=console.nextInt();
index++;
}
System.out.println("Processing each array element...");
You can do the below, Here i am first taking the user input integers and increasing it by 1 and then storing it in the a[] array of integers code for it is int j = scanner.nextInt();
// store it in array as incremented by 1.
a[i]=j+1;,
which i am iterating later to get the user input value+1 for example if user input was 1, then in array it would be stored as 2 :-
Complete runnable code is below with the comments and sample input and output :-
public class SOTest {
public static void main(String[] args) {
// create scanner object
Scanner scanner = new Scanner(System.in);
// create an array of 10 integers
int a[] = new int[10];
for(int i=0;i<10;i++){
int j = scanner.nextInt();
// store it in array as incremented by 1.
a[i]=j+1;
}
// Now array of integers have the user input value+1.
for(int i=0;i<10;i++) {
System.out.println(" "+ a[i]);
}
}
}
My program input and output is below, which will make it easy to understand :-
1 2 3 4 5 6 7 8 9 11 printing user input value by adding 1 to it 2 3
4 5 6 7 8 9 10 12
I Think this code will easily understand by you
import java.util.Scanner;
public class Demo
{
public static void main(String [] Args)
{
Scanner console = new Scanner(System.in);
System.out.println("Enter your 5 integers: ");
int index =0;
final int SIZE = 5;
int[] arrayOfSize = new int[SIZE];
while(index<arrayOfSize.length )
{
arrayOfSize[index]=console.nextInt();
index++;
}
System.out.println("Processing each array element...");
for(int i=0;i<arrayOfSize.length;i++){
System.out.print((arrayOfSize[i]+1)+" ");//(arrayOfSize[i]+1)this will take current value stored in array and add 1 to it
}
}
}

How can I make an input read out multiple integers on a single line?

How can I make it so that I can prompt the user to input multiple integers on one line that are seperated by spaces. And if the first integer is 0 or less than 0 it will print out "Bad Input" when all the integers are inputted and the user presses enter. Also how can I make it so that when the user enters a negative number at the end of the line, it will stop entering numbers and make multiply all of them together.
This is what I have so far but i'm not sure I am doing this right.
import java.util.Scanner;
public class tempprime {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int count = 1;
String inputnumbers;
System.out.print("Enter integers: ");
inputnumbers = input.nextLine();
for (int i = 0; i < inputnumbers.length(); i++){
if (inputnumbers.charAt(i) == ' ')
count++;
}
int[] numbers = new int[count];
}
}
You already have it so the user can enter in values until they hit enter. Now you can do is use a split operation to break the string up into an array of values.
String[] values = inputnumbers.split('\s');
Then you could replace charAt with access to the array.
Alternatively, Scanner already allows the user to enter in as many integers as they need on the same line. nextLine() finds the first occurance of a new line, but you can use input.nextInt(), grabs the next int stopping at a space, multiple times and read them in one at a time. You can also check if there are any more values remaining using the scanners hasNext methods.
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
You can see an example of reading multiple ints below. The user can enter them in one at a time, or 3 at a time and should still work the same.
Scanner in = new Scanner(System.in);
System.out.print("Enter 3 ints:");
int a,b,c;
a = in.nextInt();
b = in.nextInt();
c = in.nextInt();
System.out.printf("A: %d B: %d C: %d", a, b ,c);

Splitting several integers in java

I am very new to java. I am trying to prompt the user to enter 4 integer numbers followed by a space and eventually print them out at the end. I am a little confused with the order of how I write things out and using the split(" ");
import java.util.Scanner;
public class calculations {
public static void main(String[] args) {
Scanner Keyboard = new Scanner(System.in);
System.out.println("Enter 4 integer numbers here: ");
int numbers = keyboard.nextInt();
// Need split(" "); here?
} // End main string args here
} // End class calculations here
Any help or advice is appreciated. I have looked at other ways on stackoverflow but somehow I keep getting errors.
Read it in one String with keyboard.nextLine
Use the split method of String for get an array of Strings
Convert every element of the array to int with Integer.parseInt
Print your ints.
import java.util.Scanner;
public class calculations {
public static void main(String[] args) {
Scanner Keyboard = new Scanner(System.in);
System.out.println("Enter 4 integer numbers here: ");
// Scan an entire line (containg 4 integers separated by spaces):
String lineWithNumbers = Keyboard.nextLine();
// Split the String by the spaces so that you get an array of size 4 with
// the numbers (in a String).
String[] numbers = lineWithNumbers.split(" ");
// For each String in the array, print them to the screen.
for(String numberString : numbers) {
System.out.println(numberString);
}
} // End main string args here
} // End class calculations here
This code will print all numbers, in case you actually want to do something with the Integers (for example mathematical operations) you can parse the String to an int, like so:
int myNumber = Integer.parseInt(numberString);
Hope this helps.
If would suggest to use the abilities of the Scanner class to retrieve numbers from the user input:
Scanner keyboard = new Scanner(System.in);
int[] numbers = new int[4];
System.out.println("Enter 4 integer numbers here: ");
for (int i = 0; i < 4 && keyboard.hasNextInt(); i++) {
numbers[i] = keyboard.nextInt();
}
System.out.println(Arrays.toString(numbers));
This code creates an array of size 4 and then loops over the user input reading the numbers from it. It will stop parsing the input if he has the four numbers, or if the user enters something different than a number. For example, if he enters 1 blub 3 4, then the array will be [1, 0, 0, 0].
This code has some advantages compared to the nextLine approaches of the over answers:
you don't have to care about the integer conversion (exception handling)
you can either write these number onto one line or each number on its own line
If you like to read an arbitrary amount of numbers, then use a List instead:
List<Integer> numbers = new ArrayList<>();
System.out.println("Enter some integer numbers here (enter something else than a number to stop): ");
while (keyboard.hasNextInt()) {
numbers.add(keyboard.nextInt());
}
System.out.println(numbers);

Scanner object behaves differently for Integer vs String inputs [duplicate]

This question already exists:
Closed 10 years ago.
Possible Duplicate:
Scanner issue when using nextLine after nextInt
In the following two code snippets, I first ask for the number of inputs required and let the user input that many inputs of a particular kind. When the required inputs are String types, it takes one less input unless I use s.next() first, while for Integers it works fine. I don't understand why. Can someone please explain?. Thanks
First Code with String inputs and nextLine function:
public static void main(String args[]){
Scanner s = new Scanner(System.in);
int num = s.nextInt();
String[] inputs = new String[num];
for (int i = 0; i < inputs.length; i++) {
inputs[i]=s.nextLine();
}
System.out.println("end of code");
}
Second Code with Integer inputs and nextInt function:
public static void main(String args[]){
Scanner s = new Scanner(System.in);
int num = s.nextInt();
Integer[] inputs = new Integer[num];
for (int i = 0; i < inputs.length; i++) {
inputs[i]=s.nextInt();
}
System.out.println("end of code");
}
It is because of the following line:
int num = s.nextInt();
Your next INT only returns the INT until it gets to the \n character.
If you had a test file like this:
4
1
2
3
4
Your character code will look like this:
4'\n'
1'\n'
2'\n'
3'\n'
4'\n'
So when you grab the integer, it will grab the 4 for your "nextInt()" method on the scanner. When you tell it to grab the next line "nextLine()", it will grab the remainder of that line which is just '\n' and store nothing into the first value into your array.
On the reverse side, if you tell it to grab the next integer "nextInt()", it will search until it finds the next integer, which will cause the 1 to go into the first value into the array.

Categories