How to take single array input from user? - java

In the following code i marked the line that doesn't work.
Can someone explain me why this doesn't work?
import java.util.Scanner;
public class ArrayLength {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println("Please enter the array : ");
double[] userArray = myScanner.nextDouble();//This line doesn't work
}
}

I guess you are trying to set a double array from a line-separated input. If so, you could use something like this:
Scanner myScanner = new Scanner(System.in);
System.out.println("Please enter the array : ");
String strScan = myScanner.nextLine();
String[] aScan = strScan.split(" ");
double[] userArray = new double[aScan.length];
int i = 0 ;
for (String str : aScan) {
userArray[i] = Double.parseDouble(str);
i++;
}

If you are expecting the user input to be located on exactly one line and you are sure that all the values (separated by a whitespace) could be parsed as Double I do recommend using the following statement:
double[] userArray = Arrays.stream(myScanner.nextLine().split(" "))
.mapToDouble(Double::parseDouble)
.toArray();
Read whole next line as string, split it by whitespace, and then do parse each value into double.
If you only need to read a single double value and you are required to store it into an array then you could simply use the Array Initializer like this:
double[] userArray = {myScanner.nextDouble()};
This way userArray will have 1 element in total and it's first and only value will be the user input.

You have to define array index in int, then only get double input
public class Example {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//Decide array length
System.out.print("Please enter the array : ");
int num = Integer.parseInt(scan.nextLine());
//Create a double array to store values
double userArray[] = new double[num];
for (int i = 0; i < userArray.length; i++) {
System.out.print("Enter value " + (i + 1) + " : ");
userArray[i] = scan.nextDouble(); // you can store input with double datatype now
}
//Now display one by one
for (int i = 0; i < userArray.length; i++) {
System.out.print("Value are " + (i + 1) + " : ");
System.out.print(userArray[i] + "\n");
}
}
}
If you don't want to take input as array
double num= myScanner.nextDouble();

myScanner.nextDouble() will output a single double instead of an array of doubles. So you would need to set that double equal to a specific index in the array instead of trying to set the whole array equal to a single double. I would suggest utilizing a for loop if you want to accept multiple doubles into the array.
For Example:
for(int x = 0; x < userArray.length; x++)
{
userArray[x] = myScanner.nextDouble(); // x in this scenario is a specific position in the array
}
Also if the user input is formatted with a space between each double (i.e. 1.0 2.0 3.0 4.0 etc) myScanner.nextDouble(); will take the first double then go through the for loop again and take the next double etc. This is useful because the user input can all be on one line so the user can input the entire array at once.

Related

Creating a run time array that takes user input and creates array at run time & accepts 3 variables to calculate sum and average

I keep getting the error "cannot find symbol 'arr' " How do I accept both the array as a user input (being a float not a double) and 3 float variables as elements in the array?
import java.util.Scanner;
public class runtime_array
{
public static void main(String[] args){
System.out.println("Program creates array size at run-time");
System.out.println("Program rounds sum and average of numbers to two decimal places");
System.out.println("Note: numbers *must* be float data type");
System.out.println(); //blank line
// taking String array input from user
Scanner input = new Scanner(System.in);
System.out.println("Please enter length of String array");
int length = input.nextInt();
arr[i] = input.nextInt();
// create an array to save user input
float[] input = new float[length];
float[] input = new float[arr];
// loop over array to save user input
System.out.println("Please enter array elements");
for (int i = 0; i < length; i++) {
}
float sum = 0;
System.out.println("The array input from user is : ");
for(int i = 0; i < arr.length; i++){
System.out.println(String.format("%.2f", Float.valueOf(arr[i])));
sum += Float.valueOf(arr[i]);
}
System.out.println("The sum is: " + String.format("%.2f",sum));
System.out.println("The average is: " + String.format("%.2f",(sum/length)));
}
}
You've got a couple issues here
First, you cannot declare float[] input because you've already given Scanner to the reference for input. You need to name your float[] something different. Let's go with userInput.
Scanner input = new Scanner(System.in);
System.out.println("Please enter length of String array");
int length = input.nextInt();
float[] userInput = new float[length];
Next, you are trying to do things with arr before you have declared it. However, I don't even think you need a reference to arr. You should remove this line.
arr[i] = input.nextInt();
Furthermore, you need to prompt your user during each loop iteration, as well as append the Scanner input to float[] userInput.
for (int i = 0; i < length; i++) {
System.out.println("Please enter array elements");
userInput[i] = input.nextInt();
}

How can I read 4 numbers as input from the user and print them as "|" separated values?

I have to make a method to print out the elements in an array, separated by ‘‘|’’
#param values, an array of integers.
Essentially its suppose to take user input, and then from there separate it with |. This is what I have so far. Any help chaps?
int [] scans = new int [3];
System.out.println("Enter 4 Numbers into the array: " );
Scanner scanner = new Scanner(System.in);
int s = scanner.nextInt();
for (int i = 0; i < scans.length; i++)
{
scans [i] = scanner.nextInt();
}
First, you're ignoring the first input number by assigning it to s, but you never use that thereafter. For the joining problem, you can use a stream. Below will ask the user to input 3 numbers, save them to your int[3] and output it joined by |
int [] scans = new int[3];
System.out.println("Enter 3 Numbers into the array: " );
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < scans.length; i++) {
scans [i] = scanner.nextInt();
}
String joined = Arrays.stream(scans)
.mapToObj(String::valueOf)
.collect(Collectors.joining("|"));
System.out.println(joined);
Here is a solution that might be easier to understand without using the mapToObj solution #baao used (which is fine, but maybe harder to understand if your new to Java).
First of all if you want to store 4 numbers in the array, then your array should hold 4 not 3 elements. Another trick you can use is to create a prefix variable that is used to prepend each number in a loop over the values in the array. After the first iteration the prefix should be set to your separator variable.
You can see it working here: https://ideone.com/QCNPZQ
int [] scans = new int[4];
System.out.println("Enter 4 numbers into the array: " );
Scanner scanner = new Scanner(System.in);
for (int i=0; i<scans.length; i++) {
scans [i] = scanner.nextInt();
}
String prefix = "";
String result = "";
for(int i=0; i<scans.length; i++){
result = result + prefix + scans[i];
prefix = "|";
}
System.out.println(result);

Passing Strings To array Java Eclipse

I have a java code and it work with success !
//data
double[] query = {0.65,0.78,0.21,0.29,0.58};
but now i want user put the strings manual like this :
println("insert the values like that {xx,xx,xx,xx,xx} ")
i think must use scanner but i don't know how ?
If you want to get double numbers from user, use nextDouble() method, like this:
Creating a Scanner object:
Scanner scan = new Scanner(System.in);
Reading inputted numers from user:
Double insertedDouble = scan.nextDouble();
Double insertedDouble2 = scan.nextDouble();
Making an array of inputted numers:
double[] array = {insertedDouble, insertedDouble2};
If input is to be taken in from user input, use scanner this way:
Scanner scanner = new Scanner(System.in);
Make sure to intialize array:
private double[] array = new double[10];
Prompt user for input:
System.out.println("Please enter double value: ");
array[0] = scanner.nextDouble(); //gets input from user using scanner, store in first index of array
Print:
System.out.println(array[0]);
It's straight forward to use scanner try this:
import java.util.Scanner;
public class Main {
public static void main(String[] arguments) {
// Set the number of values
int values = 5;
// Create an empty array for values
double query[] = new double[values];
// Create scanner object to use
Scanner input = new Scanner(System.in);
// Parse Items for input
for(int i = 0; i < values; ++i) {
System.out.println("Please input value num in 0.0 format ");
query[i] = input.nextDouble();
}
// Print the values for success
for(int i = 0; i < values; ++i)
System.out.println(query[i]);
}
}

Cannot do the sum of numbers using a comma and string tokenizer

I have a program but I dont know specifically what my mistake is or how to fix it: The question is:
Write a program that asks the user to enter a series of numbers separated by commas.
The program should calculate and display the sum of all the numbers.
For example, if I enter 4,5,6,7, the sum displayed should be 22.
This is what I have so far:
import java.util.Scanner;
public class SumAll {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String userNumber;
String sum = null;
//get numbers from user and store
System.out.println("Enter numbers seperated by coma's: ");
userNumber = keyboard.nextLine();
String[] tokens = userNumber.split("[, ]");
for (int i = 0; i < tokens.length; i++) {
sum = tokens.length[i++]; //showing me error here. Its written array required but int //found.
}
System.out.println("Sum is: " + sum);
}
}
Thank you very much for the help.
Sum should be an int
int sum = 0;
Your for loop should be
for (int i = 0; i < tokens.length; i++) {
sum += Integer.parseInt(tokens[i]);
}
Because it should be:
sum += Integer.parseInt(tokens[i]);
There are several things wrong with this one line of code.
sum = tokens.length[i++];
You can't index the length of the array like that. Just index the array (see below).
The for loop is already incrementing i. You don't need to do it again.
You need to convert the token to an integer before you can add it to the sum.
You need to add the new value to the sum, not replace the old sum.
Try this instead:
sum += Integer.parseInt(tokens[i]);
You'll also need to make sum an integer. Instead of
String sum = null;
you need
int sum = 0;
I know I am more than 2 years late but I started learning Java not too long ago and would like to share my solution. :) I used the StringTokenizer class. I hope this helps someone out there in 2017 and onward.
import java.util.Scanner;
import java.util.StringTokenizer;
public class SumOfNumbersInString {
public static void main(String[] args) {
// Create a Scanner object
Scanner keyboard = new Scanner(System.in);
// Get user input
System.out.print("Enter a series of numbers seperated by commas\n> ");
String input = keyboard.nextLine();
// Display sum by calling the getSum method
System.out.println("SUM: " + getSum(input));
}
/**
*
* #param input with the format --> (#,#,#,#)
* #return sum of numbers in the input
*/
public static int getSum(String input) {
// Declare and initialize the sum accumulator variable
int sum = 0;
// Create a StringTokenizer object
// The string to be tokenized is passed as 1st parameter
// The "," that separates tokens/numbers is the 2nd parameter
StringTokenizer stringTokenizer = new StringTokenizer(input, ",");
// The hasMoreTokens method of the StringTokenizer class returns true if there are more tokens left in the string
// Otherwise, it returns false
while (stringTokenizer.hasMoreTokens()) {
// While the string has another token (number), parse the number to an integer and add its value to sum
sum += Integer.parseInt(stringTokenizer.nextToken());
}
// Return sum's value to the method call
return sum;
}
}
OUTPUT
Enter a series of numbers seperated by commas
> 4,5,6,7
SUM: 22
/** #author Jerry Urena **/
public static void main(String[] args)
{
String userinput;
int total = 0;
//keyboard function
Scanner keyboard = new Scanner(System.in);
//Ask for input
System.out.print("Please enter a series of numbers separated by commas " );
//Get user input
userinput = keyboard.nextLine();
//Split numbers
String[] numbers = userinput.split("[,]");
//String loop
for (String number : numbers)
{
//Sum of numbers
total += Integer.parseInt(number);
}
//Print results
System.out.println("Total: " + total);
}

How to read multiple Integer values from a single line of input in Java?

I am working on a program and I want to allow a user to enter multiple integers when prompted. I have tried to use a scanner but I found that it only stores the first integer entered by the user. For example:
Enter multiple integers: 1 3 5
The scanner will only get the first integer 1. Is it possible to get all 3 different integers from one line and be able to use them later? These integers are the positions of data in a linked list I need to manipulate based on the users input. I cannot post my source code, but I wanted to know if this is possible.
I use it all the time on hackerrank/leetcode
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String lines = br.readLine();
String[] strs = lines.trim().split("\\s+");
for (int i = 0; i < strs.length; i++) {
a[i] = Integer.parseInt(strs[i]);
}
Try this
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
if (in.hasNextInt())
System.out.println(in.nextInt());
else
in.next();
}
}
By default, Scanner uses the delimiter pattern "\p{javaWhitespace}+" which matches at least one white space as delimiter. you don't have to do anything special.
If you want to match either whitespace(1 or more) or a comma, replace the Scanner invocation with this
Scanner in = new Scanner(System.in).useDelimiter("[,\\s+]");
You want to take the numbers in as a String and then use String.split(" ") to get the 3 numbers.
String input = scanner.nextLine(); // get the entire line after the prompt
String[] numbers = input.split(" "); // split by spaces
Each index of the array will hold a String representation of the numbers which can be made to be ints by Integer.parseInt()
Scanner has a method called hasNext():
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext())
{
System.out.println(scanner.nextInt());
}
If you know how much integers you will get, then you can use nextInt() method
For example
Scanner sc = new Scanner(System.in);
int[] integers = new int[3];
for(int i = 0; i < 3; i++)
{
integers[i] = sc.nextInt();
}
Java 8
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int arr[] = Arrays.stream(in.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
Here is how you would use the Scanner to process as many integers as the user would like to input and put all values into an array. However, you should only use this if you do not know how many integers the user will input. If you do know, you should simply use Scanner.nextInt() the number of times you would like to get an integer.
import java.util.Scanner; // imports class so we can use Scanner object
public class Test
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner( System.in );
System.out.print("Enter numbers: ");
// This inputs the numbers and stores as one whole string value
// (e.g. if user entered 1 2 3, input = "1 2 3").
String input = keyboard.nextLine();
// This splits up the string every at every space and stores these
// values in an array called numbersStr. (e.g. if the input variable is
// "1 2 3", numbersStr would be {"1", "2", "3"} )
String[] numbersStr = input.split(" ");
// This makes an int[] array the same length as our string array
// called numbers. This is how we will store each number as an integer
// instead of a string when we have the values.
int[] numbers = new int[ numbersStr.length ];
// Starts a for loop which iterates through the whole array of the
// numbers as strings.
for ( int i = 0; i < numbersStr.length; i++ )
{
// Turns every value in the numbersStr array into an integer
// and puts it into the numbers array.
numbers[i] = Integer.parseInt( numbersStr[i] );
// OPTIONAL: Prints out each value in the numbers array.
System.out.print( numbers[i] + ", " );
}
System.out.println();
}
}
There is more than one way to do that but simple one is using String.split(" ")
this is a method of String class that separate words by a spacial character(s) like " " (space)
All we need to do is save this word in an Array of Strings.
Warning : you have to use scan.nextLine(); other ways its not going to work(Do not use scan.next();
String user_input = scan.nextLine();
String[] stringsArray = user_input.split(" ");
now we need to convert these strings to Integers. create a for loop and convert every single index of stringArray :
for (int i = 0; i < stringsArray.length; i++) {
int x = Integer.parseInt(stringsArray[i]);
// Do what you want to do with these int value here
}
Best way is converting the whole stringArray to an intArray :
int[] intArray = new int[stringsArray.length];
for (int i = 0; i < stringsArray.length; i++) {
intArray[i] = Integer.parseInt(stringsArray[i]);
}
now do any proses you want like print or sum or... on intArray
The whole code will be like this :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String user_input = scan.nextLine();
String[] stringsArray = user_input.split(" ");
int[] intArray = new int[stringsArray.length];
for (int i = 0; i < stringsArray.length; i++) {
intArray[i] = Integer.parseInt(stringsArray[i]);
}
}
}
This works fine ....
int a = nextInt();
int b = nextInt();
int c = nextInt();
Or you can read them in a loop
Using this on many coding sites:
CASE 1: WHEN NUMBER OF INTEGERS IN EACH LINE IS GIVEN
Suppose you are given 3 test cases with each line of 4 integer inputs separated by spaces 1 2 3 4, 5 6 7 8 , 1 1 2 2
int t=3,i;
int a[]=new int[4];
Scanner scanner = new Scanner(System.in);
while(t>0)
{
for(i=0; i<4; i++){
a[i]=scanner.nextInt();
System.out.println(a[i]);
}
//USE THIS ARRAY A[] OF 4 Separated Integers Values for solving your problem
t--;
}
CASE 2: WHEN NUMBER OF INTEGERS in each line is NOT GIVEN
Scanner scanner = new Scanner(System.in);
String lines=scanner.nextLine();
String[] strs = lines.trim().split("\\s+");
Note that you need to trim() first: trim().split("\\s+") - otherwise, e.g. splitting a b c will emit two empty strings first
int n=strs.length; //Calculating length gives number of integers
int a[]=new int[n];
for (int i=0; i<n; i++)
{
a[i] = Integer.parseInt(strs[i]); //Converting String_Integer to Integer
System.out.println(a[i]);
}
created this code specially for the Hacker earth exam
Scanner values = new Scanner(System.in); //initialize scanner
int[] arr = new int[6]; //initialize array
for (int i = 0; i < arr.length; i++) {
arr[i] = (values.hasNext() == true ? values.nextInt():null);
// it will read the next input value
}
/* user enter = 1 2 3 4 5
arr[1]= 1
arr[2]= 2
and soo on
*/
It's working with this code:
Scanner input = new Scanner(System.in);
System.out.println("Enter Name : ");
String name = input.next().toString();
System.out.println("Enter Phone # : ");
String phone = input.next().toString();
A simple solution can be to consider the input as an array.
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); //declare number of integers you will take as input
int[] arr = new int[n]; //declare array
for(int i=0; i<arr.length; i++){
arr[i] = sc.nextInt(); //take values
}
You're probably looking for String.split(String regex). Use " " for your regex. This will give you an array of strings that you can parse individually into ints.
Better get the whole line as a string and then use StringTokenizer to get the numbers (using space as delimiter ) and then parse them as integers . This will work for n number of integers in a line .
Scanner sc = new Scanner(System.in);
List<Integer> l = new LinkedList<>(); // use linkedlist to save order of insertion
StringTokenizer st = new StringTokenizer(sc.nextLine(), " "); // whitespace is the delimiter to create tokens
while(st.hasMoreTokens()) // iterate until no more tokens
{
l.add(Integer.parseInt(st.nextToken())); // parse each token to integer and add to linkedlist
}
Using BufferedReader -
StringTokenizer st = new StringTokenizer(buf.readLine());
while(st.hasMoreTokens())
{
arr[i++] = Integer.parseInt(st.nextToken());
}
When we want to take Integer as inputs
For just 3 inputs as in your case:
import java.util.Scanner;
Scanner scan = new Scanner(System.in);
int a,b,c;
a = scan.nextInt();
b = scan.nextInt();
c = scan.nextInt();
For more number of inputs we can use a loop:
import java.util.Scanner;
Scanner scan = new Scanner(System.in);
int a[] = new int[n]; //where n is the number of inputs
for(int i=0;i<n;i++){
a[i] = scan.nextInt();
}
This method only requires users to enter the "return" key once after they have finished entering numbers:
It also skips special characters so that the final array will only contains integers
ArrayList<Integer> nums = new ArrayList<>();
// User input
Scanner sc = new Scanner(System.in);
String n = sc.nextLine();
if (!n.isEmpty()) {
String[] str = n.split(" ");
for (String s : str) {
try {
nums.add(Integer.valueOf(s));
} catch (NumberFormatException e) {
System.out.println(s + " cannot be converted to Integer, skipping...");
}
}
}
//Get user input as a 1 2 3 4 5 6 .... and then some of the even or odd number like as 2+4 = 6 for even number
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int evenSum = 0;
int oddSum = 0;
while (n > 0) {
int last = n % 10;
if (last % 2 == 0) {
evenSum += last;
} else {
oddSum += last;
}
n = n / 10;
}
System.out.println(evenSum + " " + oddSum);
}
}
if ur getting nzec error, try this:
try{
//your code
}
catch(Exception e){
return;
}
i know it's old discuss :) i tested below code it's worked
`String day = "";
day = sc.next();
days[i] = Integer.parseInt(day);`

Categories