Not output of the array value when used scanner - java

Below is the code. After entering the array, the console just goes blank and does not further output the array:
import java.util.Scanner;
public class advancedArrays {
public static void main(String[] args) {
System.out.println("Provide us the size of the array:");
Scanner scanner = new Scanner(System.in);
int value = scanner.nextInt();
int i = 0;
int[] array = new int[value];
System.out.println("Enter the array:");
Scanner input = new Scanner(System.in);
while(input.hasNextInt()) {
array[i] = input.nextInt();
i++;
}
System.out.println("Array entered:");
for(i=0;i<value;i++)
{
System.out.println(array[i]);
}
input.close();
scanner.close();
}
}
Output:
Provide us the size of the array:
5
Enter the array:
1 2 3 4 5

you are stuck in the "reading the array" part because of this
while (input.hasNextInt()) {
array[i] = input.nextInt();
hint: you know the size of the array, then why don't you do a for loop same as you did for printing out the array's content?? like:
for (int j = 0; j < value; j++) {
array[i] = scanner.nextInt();
i++;
}

The problem is that with the while loop that you keep it waiting for more integers, it is better to convert to a normal for loop with condition on the entered array size value.
Also there is no need to use two scanner objects
public static void main(String[] args) {
System.out.println("Provide us the size of the array:");
Scanner scanner = new Scanner(System.in);
int value = scanner.nextInt();
int i = 0;
int[] array = new int[value];
System.out.println("Enter the array:");
for (int j = 0; j < value; j++) {
if (scanner.hasNextInt()) {
array[i] = scanner.nextInt();
i++;
}
}
System.out.println("Array entered:");
for (i = 0; i < value; i++) {
System.out.println(array[i]);
}
scanner.close();
}

package Main;
import java.util.Scanner;
public class advancedArrays {
public static void main(String[] args) {
System.out.println("Provide us the size of the array:");
Scanner scanner = new Scanner(System.in);
int value = scanner.nextInt();
int i = 0;
int[] array = new int[value];
System.out.println("Enter the array:");
Scanner input = new Scanner(System.in);
while(input.hasNextInt()) {
array[i] = input.nextInt();
i++;
//Changed Code
if (i == value) {
break;
}
}
System.out.println("Array entered:");
for(i=0;i<value;i++)
{
System.out.println(array[i]);
}
input.close();
scanner.close();
}
}
Fixed code, you were stuck reading your inputs for your array because you never checked if your inputs were the length of your array.
Fixed code.
if (i == value) {
break;
}

Related

Input numeric ranges with java.util.Scanner

I would input numeric ranges (int arrays with two elements) like this:
Enter a number: 3
Enter a range: -3 5
Enter a range: 0 4
Enter a range: 6 10
I use java.util.Scanner, but I do not know how to proceed:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number = input.nextInt();
for(int i=0;i<number;i++)
String str = input.nextLine();
}
}
I think, you just nead a solution for input a numeric array. Check out this: Java Scanner Array
You can read the whole line, then split it into a String array:
public static void main(String[] args) {
try (var scanner = new Scanner(System.in)) {
System.out.print("Enter the count of arrays: ");
int arrayCount = scanner.nextInt();
scanner.nextLine();
// System.out.print("Enter the length of an array: ");
int arraySize = 2;
int[][] ranges = new int[arrayCount][arraySize];
for (int i = 0; i < arrayCount; i++) {
System.out.printf("[%d] Enter the elements: ", i);
String line = scanner.nextLine();
String[] numbers = line.split("\\D+", arraySize + 1); // separator: 1+ non-digit
for (int j = 0; j < arraySize; j++) {
ranges[i][j] = Integer.parseInt(numbers[j]);
}
}
// Arrays.stream(ranges).map(Arrays::toString).forEach(System.out::println);
}
}
Or simply scan ints one-by-one:
public static void main(String[] args) {
try (var scanner = new Scanner(System.in)) {
System.out.print("Enter the count of arrays: ");
int arrayCount = scanner.nextInt();
// System.out.print("Enter the length of an array: ");
int arraySize = 2;
int[][] ranges = new int[arrayCount][arraySize];
for (int i = 0; i < arrayCount; i++) {
System.out.printf("[%d] Enter the elements: ", i);
for (int j = 0; j < arraySize; j++) {
ranges[i][j] = scanner.nextInt();
}
}
// Arrays.stream(ranges).map(Arrays::toString).forEach(System.out::println);
}
}

I have to print the array , but for each loop is not working

import java.util.Scanner;
public class TeacherCoins {
public static void main(String[] args){
int k;
System.out.print("Enter total number of coins :");
Scanner sc = new Scanner(System.in);
k =sc.nextInt();
int [] arr= new int[k-1];
System.out.print("Enter array :");
for(int i=0;i<=(k-1);i++)
{
Scanner sc1 = new Scanner(System.in);
arr[i] =sc1.nextInt();
}
for(int element :arr)
{
System.out.println("Print array");
System.out.println(element);
}
}
I am giving output using Scanner class. But is not printing the array.
You don't need to declare the Scanner again inside the loop. Another thing that you should do to be sure of your code, is to have this condition on the loop if i < arr.length. Lastly, I moved the "Print array" message outside the last for.
public class TeacherCoins {
public static void main(String[] args){
int k;
System.out.print("Enter total number of coins :");
Scanner sc = new Scanner(System.in);
k =sc.nextInt();
int [] arr = new int[k];
System.out.print("Enter array :");
for(int i=0; i<arr.length; i++) {
arr[i] =sc1.nextInt();
}
System.out.println("Print array");
for(int element :arr){
System.out.println(element);
}
}
}
There are two problems with this code,
1. You don't need to create a new Scanner object for each user input.
2. You are declaring an array size of k-1 and then asking user input k times.
public static void main(String[] args) {
int k;
System.out.print("Enter total number of coins :");
Scanner sc = new Scanner(System.in);
k = sc.nextInt();
int[] arr = new int[k]; // To store k elements, you need k sized array
System.out.print("Enter array :");
for (int i = 0; i <= (k - 1); i++) {
// Scanner sc1 = new Scanner(System.in); / / Not required here
arr[i] = sc.nextInt();
}
System.out.println("Print array");
for (int element : arr) {
System.out.println(element);
}
}
There is only one problem in your code you are declaring the size of array as k-1 instead declare it for k elements.You just need to give each inputs in new line. For more refer this :Scanner class.
And your for each loop is correct and working.
import java.util.Scanner;
public class TeacherCoins {
public static void main(String[] args){
int k;
System.out.print("Enter total number of coins :");
Scanner sc = new Scanner(System.in);
k =sc.nextInt();
int [] arr= new int[k];//it was giving java.lang.ArrayIndexOutOfBoundsException
System.out.print("Enter array :");
for(int i=0;i<=(k-1);i++)
{
Scanner sc1 = new Scanner(System.in);//not required
arr[i] =sc1.nextInt();//use arr[i] =sc.nextInt();
}
for(int element :arr)
{
System.out.println("Print array");
System.out.println(element);
}
}
}
Above code will work. But you don't need new scanner objects for taking input, creating only single object will work.
import java.util.Scanner;
public class TeacherCoins {
public static void main(String[] args) {
int k;
System.out.print("Enter total number of coins :");
Scanner sc = new Scanner(System.in);
k = sc.nextInt();
int[] arr = new int[k];
System.out.print("Enter array :");
for (int i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
}
sc.close();
System.out.println("Print array");
for (int element : arr) {
System.out.println(element);
}
for (int i = 0; i < arr.length; i++) {
int count = 0;
for (int j = 0; i < arr.length; j++) {
arr[i] = arr[j];
count++;
}
System.out.println(arr[i] + " " + count);
}
}
}

return array from one method to another method

This is my program and every time it is asking me to input the array.
I want to input a array once and process on that array.
But this program is asking me to input array again.
from method named "first" I just want to return array and use that array in two different methods add and delete. But it is always asking me to input all the elements of array that is every time the first method is running while i call any add or delete method from main method.
package Program;
import java.util.Arrays;
import java.util.Scanner;
public class Functionality {
public static int[] first( )
{
System.out.println("Enter the number of element in array");
Scanner num = new Scanner(System.in);
int data = num.nextInt();
//return data;
Scanner ar = new Scanner(System.in);
int arr[] = new int[data];
System.out.println("Enter "+data+" Numbers");
for(int i =0; i<data; i++){
System.out.println("Enter NUmber :"+(i+1));
arr[i] = num.nextInt();
}
System.out.println();
System.out.println(Arrays.toString(arr));
return arr;
}
public static void main(String[] args) {
add();
delete();
}
static void add(){
int arr[]=first();
System.out.println("Enter the number you want to add");
Scanner one = new Scanner(System.in);
int naya = one.nextInt();
for(int i = 0; i<=arr.length-1; i++){
arr[i]= arr[i] + naya;
}
System.out.println("The added array is");
System.out.println(Arrays.toString(arr));
}
static void delete(){
int arr[]=first();
System.out.println("Enter the number you want to substract");
Scanner two = new Scanner(System.in);
int arko = two.nextInt();
for(int i =0; i <= arr.length-1; i++ ){
arr[i]=arr[i]-arko;
}
System.out.println("The Substracted array is");
System.out.println(Arrays.toString(arr));
}
You should obtain reference to an array and passing it during subsequent methods invocations.
This should do the trick:
class Functionality {
static int[] first() {
System.out.println("Enter the number of element in array");
Scanner num = new Scanner(System.in);
int data = num.nextInt();
//return data;
Scanner ar = new Scanner(System.in);
int arr[] = new int[data];
System.out.println("Enter " + data + " Numbers");
for (int i = 0; i < data; i++) {
System.out.println("Enter NUmber :" + (i + 1));
arr[i] = num.nextInt();
}
System.out.println();
System.out.println(Arrays.toString(arr));
return arr;
}
public static void main(String[] args) {
int arr[] = first();
add(arr);
delete(arr);
}
static void add(int arr[]) {
System.out.println("Enter the number you want to add");
Scanner one = new Scanner(System.in);
int naya = one.nextInt();
for (int i = 0; i <= arr.length - 1; i++) {
arr[i] = arr[i] + naya;
}
System.out.println("The added array is");
System.out.println(Arrays.toString(arr));
}
static void delete(int arr[]) {
System.out.println("Enter the number you want to substract");
Scanner two = new Scanner(System.in);
int arko = two.nextInt();
for (int i = 0; i <= arr.length - 1; i++) {
arr[i] = arr[i] - arko;
}
System.out.println("The Substracted array is");
System.out.println(Arrays.toString(arr));
}
}
Your program is asking You every time to input array, because every time You invoke method first() new array is being created

how to match entries and display entries

I do not know how to display entries entered by user, and also to match and sort them.
import java.util.Scanner;
public class Case1
{
public static void main(String[] args) {
Scanner in=new Scanner (System.in);
System.out.println("Input a size of an array: ");
int size = in.nextInt();
int num[]=new int[size];
int i=0;
for (i=0;i<num.length;i++) {
System.out.println("Input a number: ");
num[i]=in.nextInt();
}
for (int c=0;i<num.length;c++){
for (int a=0; a<num.length;a++){
if(num[c]>num[a]){
int temp = num[c];
num[c]= num[a];
num[a]=temp;
}
}
}
for (int d=0;i<num.length;d++){
int value = 0;
if(value==num[i]) {
System.out.println("Match Found!");
}
}
}
}
help please.
It should look like this ->
import java.util.Scanner;
public class Case1
{
public static void main(String[] args) {
Scanner in=new Scanner (System.in);
System.out.println("Input a size of an array: ");
int size = in.nextInt();
int num[]=new int[size];
int i=0;
for (i=0;i<num.length;i++) {
System.out.println("Input a number: ");
num[i]=in.nextInt();
}
// DISPLAY ENTRIES
System.out.println("You entered the following entries.");
for (int index=0; index<num.length; index++) {
System.out.print(index + ": " + num[index] + " ");
}
// END DISPLAY ENTRIES
for (int c=0;c<num.length;c++){ // Changed i to c
for (int a=0; a<num.length;a++){
if(num[c]>num[a]){
int temp = num[c];
num[c]= num[a];
num[a]=temp;
}
}
}
for (int d=0;d<num.length;d++){ // Changed i to d
int value = 0;
if(value==num[d]) { // Changed i to d
System.out.println("Match Found!");
}
}
}
}
This should work, but when you asked in your question about matching, did you want to match each entry with 0 (which makes no sense) or did you want to compare each entry to 0?

How to put a Scanner input into an array... for example a couple of numbers

Scanner scan = new Scanner(System.in);
double numbers = scan.nextDouble();
double[] avg =..????
You could try something like this:
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
double[] numbers = new double[5];
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Please enter number");
numbers[i] = input.nextDouble();
}
}
It seems pretty basic stuff unless I am misunderstanding you
You can get all the doubles with this code:
List<Double> numbers = new ArrayList<Double>();
while (scan.hasNextDouble()) {
numbers.add(scan.nextDouble());
}
import java.util.Scanner;
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
Scanner in=new Scanner (System.in);
int num[]=new int[10];
int average=0;
int i=0;
int sum=0;
for (i=0;i<num.length;i++) {
System.out.println("enter a number");
num[i]=in.nextInt();
sum=sum+num[i];
}
average=sum/10;
System.out.println("Average="+average);
}
}
**Simple solution**
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int size;
System.out.println("Enter the number of size of array");
size = sc.nextInt();
int[] a = new int[size];
System.out.println("Enter the array element");
//For reading the element
for(int i=0;i<size;i++) {
a[i] = sc.nextInt();
}
//For print the array element
for(int i : a) {
System.out.print(i+" ,");
}
}
For the values of the array given by separated with space " " you can try this cool one liner Java 8 & onwards suppported streams based solution:
Scanner scan = new Scanner(System.in);
double[] arr = Arrays.stream(scan.nextLine()
.trim()
.split(" "))
.filter(x -> !x.equals(""))
.mapToDouble(Double::parseDouble)
.toArray();
For int array you can try:
Scanner scan = new Scanner(System.in);
int[] arr = Arrays.stream(scan.nextLine()
.trim()
.split(" "))
.filter(x -> !x.equals(""))
.mapToInt(Integer::parseInt)
.toArray();
With filter() method you can also avoid more than one spaces in between the inputs.
Complete code reference:
import java.util.Scanner;
import java.util.Arrays;
public class Main{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double[] arr = Arrays.stream(scan.nextLine()
.trim()
.split(" "))
.filter(x -> !x.equals(""))
.mapToDouble(Double::parseDouble)
.toArray();
for(double each: arr){
System.out.print(each + " ");
}
}
}
Input: 1 2 3 4 5 6 7 8 9
Output: 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0
If you observe carefully, there are extra spaces in between the input randomly, that has also been handled with line .filter(x -> !x.equals("")) so as to avoid blank inputs ("")
import java.util.Scanner;
class Array {
public static void main(String a[]){
Scanner input = new Scanner(System.in);
System.out.println("Enter the size of an Array");
int num = input.nextInt();
System.out.println("Enter the Element "+num+" of an Array");
double[] numbers = new double[num];
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Please enter number");
numbers[i] = input.nextDouble();
}
for (int i = 0; i < numbers.length; i++)
{
if ( (i%3) !=0){
System.out.print("");
System.out.print(numbers[i]+"\t");
} else {
System.out.println("");
System.out.print(numbers[i]+"\t");
}
}
}
double [] avg = new double[5];
for(int i=0; i<5; i++)
avg[i] = scan.nextDouble();
This is a program to show how to give input from system and also calculate sum at each level and average.
package NumericTest;
import java.util.Scanner;
public class SumAvg {
public static void main(String[] args) {
int i,n;
System.out.println("Enter the number of inputs");
Scanner sc = new Scanner(System.in);
n=sc.nextInt();
int a[] = new int [n];
System.out.println("Enter the inputs");
for(i=0;i<n;i++){
a[i] = sc.nextInt();
System.out.println("Inputs are " +a[i]);
}
int sum = 0;
for(i=0;i<n;i++){
sum = sum +a[i];
System.out.println("Sums : " +sum);
}
int avg ;
avg = sum/n;
System.out.println("avg : " +avg);
}
}
List<Double> numbers = new ArrayList<Double>();
double sum = 0;
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
double value = scan.nextDouble();
numbers.add(value);
sum += value;
}
double average = sum / numbers.size();
public static void main (String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Please enter size of an array");
int n=s.nextInt();
double arr[] = new double[n];
System.out.println("Please enter elements of array:");
for (int i=0; i<n; i++)
{
arr[i] = s.nextDouble();
}
}
If you don't know the size of the array, you need to define, when to stop reading the sequence (In the below example, program stops when the user introduces 0 and obviously, last zero shouldn't be taken into account).
import java.util.Scanner;
import java.util.ArrayList;
public class Main
{
public static void main (String[]args)
{
System.out.println("Introduce the sequence of numbers to store in array. Each of the introduced number should be separated by ENTER key. Once you're done, type in 0.");
Scanner scanner = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<Integer>();
boolean go = true;
while (go) {
int value = scanner.nextInt();
numbers.add(value);
if (value == 0) {
go = false;
numbers.remove(numbers.size() - 1);
}
}
System.out.println(numbers);
}
}
Scanner scan = new Scanner (System.in);
for (int i=0; i<=4, i++){
System.out.printf("Enter value at index"+i+" :");
anArray[i]=scan.nextInt();
}
import java.util.Scanner;
public class sort {
public static void main(String args[])
{
int i,n,t;
Scanner sc=new Scanner(System.in);
System.out.print("Enter the size of array");
n=sc.nextInt();
int a[] = new int[n];
System.out.println("Enter elements in array");
for(i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
t=a[1];
for(i=0;i<n;i++)
{
if(a[i]>t)
t=a[i];
}
System.out.println("Greates integer is" +t);
}
}

Categories

Resources