Java input for array

Take Array Input in Java

Take Array Input in Java | Array Programs in Java – 2 | In the previous Java program, we have seen how to find the length of an array in Java. Now in this post, we will see how to take array input in Java? Prerequisite:- Array in Java

We can get array input in Java from the end-user or from a method. First, we will develop a program to get array input from the end-user through the keyboard, and later we will develop a Java program to take an array as an argument.

Java Program to Get Array Input From End-user

To get input from the end-user we can use the Scanner class. For this, first, we need to create an object for the Scanner class and call the appropriate method to read the input value.

import java.util.Scanner; public class Test < public static void main(String[] args) < // Scanner class object to read input Scanner scan = new Scanner(System.in); // declaring and creating array objects int[] arr = new int[5]; // displaying default values System.out.println("Default values of array:"); for (int i=0; i < arr.length; i++) < System.out.print(arr[i]+"\t"); >// initializing array System.out.println("\n\n***Initializing Array***"); System.out.println("Enter "+ arr.length + " integer values:"); for(int i=0; i < arr.length; i++) < // read input arr[i] = scan.nextInt(); >System.out.println("***Initialization completed***\n"); //displaying initialized values System.out.println("Array elements are:"); for (int i=0; i < arr.length; i++) < System.out.print(arr[i]+"\t"); >> >

Default values of array:
0 0 0 0 0
***Initializing Array***
Enter 5 integer values:
10
20
30
40
50
***Initialization completed***
Array elements are:
10 20 30 40 50

array input in Java

In this array program, array elements are not initialized with explicit values, they are initialized with a default value. The default value of the int data type is 0, so they are initialized with 0. Later we updated array elements with values 10, 20, 30, 40, and 50.

Passing Array as Argument

To pass array object as an argument the method parameters must be the passes array object type or its superclass type.

Program2:- Develop a Java program to define a method to receive the number of integer values dynamically from another method as an argument in this method. Read and display all values.

public class ArrayMethod < public static void main(String[] args) < int[] array=; display(array); > static void display(int[] a) < for(int i=0; i< a.length; i++) < System.out.print(a[i]+"\t"); >> >

Program3: Develop a program to find the sum of array elements. Display array elements, and use a user-defined method for calculating the sum of array elements.

public class ArraySum < // main method public static void main(String[] args) < // array with explicit values int[] array = ; int sum = 0; sum = sumOfArrayElements(array); System.out.println("\nSum of" + " array elements: " + sum); > // method to display array elements // and calculate sum static int sumOfArrayElements(int[] a) < int sum=0; // display array and calculate sum for(int i=0; i< a.length; i++)< System.out.print(a[i]+"\t"); sum += a[i]; >return sum; > >

5 15 25 35 45 55 65
Sum of array elements: 245

When we pass an array object as an argument into a method, and if we modify array object values with method parameters then the modification is effected to the original referenced variable.

Читайте также:  How to store dates in java

Q) Guess the output of the below program?

public class Array < public static void main(String[] args) < int[] a = ; m1(a); for(int i=0; i < a.length; i++)< System.out.print(a[i]+"\t"); >> static void m1(int[] ia) < ia[1] = 4; ia[2] = 5; >>

You may think the output 10, 20, 30, and 40 but it is the wrong output. The actual output is- 10 4 5 40; The Java language uses pass by reference not the pass by value. That’s why we get this output.

Program description:- Develop a Java program to read an array of double data-type values from the end-user. Pass this array to a method to calculate the sum of the array elements. Also, pass this array to a method to display the array elements and later display the sum of the array elements.

import java.util.Scanner; class Test < // method to display array elements public static void display(double[] a) < for (int i=0; i < a.length; i++) < System.out.print(a[i]+"\t"); >> // method to find sum of array elements public static double sumOfArray(double[] a) < double sum = 0.0; for (int i=0; i < a.length; i++) < sum += a[i]; >return sum; > // main method public static void main(String[] args) < // Scanner class object to read input Scanner scan = new Scanner(System.in); // declare variables int n = 0; double[] arr = null; double sum = 0.0; // read number of elements System.out.print("How many numbers" + " you want to enter:: "); n = scan.nextInt(); // declare array arr = new double[n]; // initializing array System.out.println("Enter "+ arr.length + " numbers:"); for(int i=0; i < arr.length; i++) < // read input arr[i] = scan.nextDouble(); >// pass array to find sum sum = sumOfArray(arr); // display array System.out.println("Array elements are:"); display(arr); // display sum value System.out.println("\nSum = " + sum); > >

How many numbers you want to enter:: 5
Enter 5 numbers:
12.5
19.8
10
20
58
Array elements are:
12.5 19.8 10.0 20.0 58.0
Sum = 120.3

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Источник

Java input for array

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Read input as array

I want to make something read from inputstream to store in an int[] when I type «read 1 2 3 4». what should i do? I do not know the size of the array, everything is dynamic. Here is the current code:

BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)); String line = stdin.readLine(); StringTokenizer st = new StringTokenizer(line); String command = st.nextToken(); if (command.equals("read")) < while (st.nextToken() != null) < //my problem is no sure the array size >> 

3 Answers 3

You need to build something to parse the input stream. Assuming it’s literally as uncomplex as you’ve indicated the first thing you need to do is get the line out of the InputStream , you can do that like this:

// InputStream in = . ; // read and accrue characters until the linebreak StringBuilder sb = new StringBuilder(); int c; while((c = in.read()) != -1 && c != '\n') < sb.append(c); >String line = sb.toString(); 

Or you can use a BufferedReader (as suggested by comments):

BufferedReader rdr = new BufferedReader(new InputStreamReader(in)); String line = rdr.readLine(); 

Once you have a line to process you need to split it into pieces, then process the pieces into the desired array:

// now process the whole input String[] parts = line.split("\\s"); // only if the direction is to read the input if("read".equals(parts[0])) < // create an array to hold the ints // note that we dynamically size the array based on the // the length of `parts`, which contains an array of the form // ["read", "1", "2", "3", . ], so it has size 1 more than required // to hold the integers, thus, we create a new array of // same size as `parts`, less 1. int[] inputInts = new int[parts.length-1]; // iterate through the string pieces we have for(int i = 1; i < parts.length; i++)< // and convert them to integers. inputInts[i-1] = Integer.parseInt(parts[i]); >> 

I’m sure some of these methods can throw exceptions (at least read and parseInt do), I’ll leave handling those as an exercise.

Читайте также:  Readutf java io eofexception

Источник

how to take user input in Array using java?

how to take user input in Array using Java? i.e we are not initializing it by ourself in our program but the user is going to give its value.. please guide!!

9 Answers 9

Here’s a simple code that reads strings from stdin , adds them into List , and then uses toArray to convert it to String[] (if you really need to work with arrays).

import java.util.*; public class UserInput < public static void main(String[] args) < Listlist = new ArrayList(); Scanner stdin = new Scanner(System.in); do < System.out.println("Current list is " + list); System.out.println("Add more? (y/n)"); if (stdin.next().startsWith("y")) < System.out.println("Enter : "); list.add(stdin.next()); >else < break; >> while (true); stdin.close(); System.out.println("List is " + list); String[] arr = list.toArray(new String[0]); System.out.println("Array is " + Arrays.toString(arr)); > > 

See also:

package userinput; import java.util.Scanner; public class USERINPUT < public static void main(String[] args) < Scanner input = new Scanner(System.in); //allow user input; System.out.println("How many numbers do you want to enter?"); int num = input.nextInt(); int array[] = new int[num]; System.out.println("Enter the " + num + " numbers now."); for (int i = 0 ; i < array.length; i++ ) < array[i] = input.nextInt(); >//you notice that now the elements have been stored in the array .. array[] System.out.println("These are the numbers you have entered."); printArray(array); input.close(); > //this method prints the elements in an array. //if this case is true, then that's enough to prove to you that the user input has //been stored in an array. public static void printArray(int arr[]) < int n = arr.length; for (int i = 0; i < n; i++) < System.out.print(arr[i] + " "); >> > 
import java.util.Scanner; class bigest < public static void main (String[] args) < Scanner input = new Scanner(System.in); System.out.println ("how many number you want to put in the pot?"); int num = input.nextInt(); int numbers[] = new int[num]; for (int i = 0; i < num; i++) < System.out.println ("number" + i + ":"); numbers[i] = input.nextInt(); >for (int temp : numbers) < System.out.print (temp + "\t"); >input.close(); > > 
 import java.util.Scanner; public class Test < public static void main(String[] args) < int arr[]; Scanner scan = new Scanner(System.in); // If you want to take 5 numbers for user and store it in an int array for(int i=0; i// For printing those numbers for(int i=0; i > 

It vastly depends on how you intend to take this input, i.e. how your program is intending to interact with the user.

Читайте также:  Css icon before text

The simplest example is if you’re bundling an executable — in this case the user can just provide the array elements on the command-line and the corresponding array will be accessible from your application’s main method.

Alternatively, if you’re writing some kind of webapp, you’d want to accept values in the doGet / doPost method of your application, either by manually parsing query parameters, or by serving the user with an HTML form that submits to your parsing page.

If it’s a Swing application you would probably want to pop up a text box for the user to enter input. And in other contexts you may read the values from a database/file, where they have previously been deposited by the user.

Basically, reading input as arrays is quite easy, once you have worked out a way to get input. You need to think about the context in which your application will run, and how your users would likely expect to interact with this type of application, then decide on an I/O architecture that makes sense.

Источник

How to take input for ‘char’ array in Java?

I am developing a small application to grade Multiple Choice Questions submitted by the user. Each question has obviously 4 choices. A,B,C,D. Since these answers will be stored in a two dimensional array, I want to ask how can I take input from user for char variable. I have not learnt any method to take input for char arrays on console. i.e I have just worked with nextInt(), nextDouble(), nextLine() etc. These methods are for Strings and Integers not for char. How to take input for char arrays? I am going to post code snippet of taking input so that you people can better understand.

4 Answers 4

Once you get the .next() value as a String , check if its .length() == 1 , then use yourString.charAt(0) .

@AmitD Your answer is a complete rewrite of the OP’s problem and situation. Giving him a full solution teaches him nothing, as all you’ve done is overwhelm him with concepts of enum s and extra class es. His method will work fine for the small scale on which he’s executing this project.

 students[i][j]=input.next().charAt(0); 

What you need is more than char to handle your requirement. Create a question class which will have question and correct answer, user entered answer.

public static class Question < private Choice correctChoice = Choice.NONE; private Choice userChoice = Choice.NONE; private String question = ""; public Question(String questionString, Choice choice) < this.question = questionString; this.correctChoice = choice; >public void setUserChoice(String str) < userChoice = Choice.valueOf(str); >public boolean isQuestionAnswered() < return correctChoice == userChoice; >public String question() < return question; >> enum Choice

Now you can create a List of questions and for each question you can check whether it was answered correctly or not.

public static void main(String[] args) < Scanner input = new Scanner(System.in); Listquestions = new ArrayList(); questions.add(new Question("question1", Choice.A)); questions.add(new Question("question2", Choice.A)); questions.add(new Question("question3", Choice.A)); for (Question q : questions) < System.out.println("Please enter the answer of " + q.question()); String str = input.next(); q.setUserChoice(str); System.out.println("You have answered question " + (q.isQuestionAnswered() == true ? "Correctly" : "Incorrectly")); >> 

Above program now allows you to ask questions and reply to user accordingly. When question is asked if choice entered other than correct answer then question will be marked incorrectly.

In above example if other character is entered than A then it will tell user that you are incorrect.

Источник

Оцените статью