I simply cant figure out why I keep getting an indexoutofboundserror. I believe its pop up in the line
profits[i] = storeDays
The code is:
import java.util.Arrays;
import java.util.Scanner;
class Business
{
public static void main(String[] args) {
Scanner inputScanner;
inputScanner = new Scanner (System.in);
System.out.println("Welcome to the profit-calculation program.");
System.out.println("how many days of data do you have?");
int n = Integer.parseInt (inputScanner.nextLine());
//call upon a function to store the profits into an array for further use.
double[] dayProfitList = inputProfit(n);
//call upon a function to calculate average profit and its standard devation
//calcAverageProfit(dayProfitList);
}
public static double[] inputProfit(int days) {
Scanner inputScanner;
inputScanner = new Scanner (System.in);
System.out.println("input the profit on..");
double[] profits = new double [days];
for(int i = 1; i<days +1; i++) {
System.out.println("day " + i + "?");
double storedDays = Double.parseDouble(inputScan ner.nextLine());
profits[i] = storedDays;
}
return profits;
}
}
Arrays are enumarated from 0 so the first element of it is profits[0], next one is profits[1] and so on.
You are trying to reach an index that does not exist here:
for(int i = 1; i<days +1; i++) {
...
It actually should be
for(int i = 0; i<days; i++) {
...
Related
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
Scanner scan = new Scanner(System.in);
int amount = 0;
int input = 0;
int[] numbers = new int [amount];
for(int i = 0; i<1; i++ )
{
System.out.println("How many numbers do you plan to enter?");
amount = scan.nextInt();
if (amount==amount)
{
for(int x = 0; x<amount; x++)
{
System.out.println("Enter a number");
input = scan.nextInt();
input = input + input;
}
}
}
double average = input/amount;
System.out.println(average);
}
}
I want to every number the user inputs, but how would I go about that?
For example, if the input is a 2 then a 3 then a 4 how do i take those and print them out in the next line while stating their averages.
There are a few problems with the code as you have written it.
if (amount == amount) is the same as saying if (true), so you might as well remove it.
You are doubling your input for no particular reason.
You are trying to build an array to store the amount before knowing how big it needs to be.
Your outer for loop is looping exactly once, so you do not need that either.
Here is a working and simplified revision of your code.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int amount = 0;
int total = 0;
System.out.println("How many numbers do you plan to enter?");
amount = scan.nextInt();
// Now that we know the amount, we can build an array to hold that
// amount.
int[] numbers = new int [amount];
for(int x = 0; x<amount; x++)
{
System.out.println("Enter a number");
numbers[x] = scan.nextInt();
total += numbers[x];
}
double average = total * 1.0 /amount; // Prevent integer division
System.out.println(average);
}
}
Update: The code above will compute the average of the numbers that the user has provide.
The OP seems to hint that he wants the proportion of each input instead. Here is a modification using HashMap to accomplish that.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int amount = 0;
int total = 0;
// Create a Map to get the count of each input.
Map<Integer,Integer> counts = new TreeMap<Integer,Integer>();
System.out.println("How many numbers do you plan to enter?");
amount = scan.nextInt();
for(int x = 0; x<amount; x++)
{
System.out.println("Enter a number");
int input = scan.nextInt();
if (counts.containsKey(input)) counts.put(input, counts.get(input) + 1);
else counts.put(input,1);
}
// Print out the percentage of each input
for (Integer key : counts.keySet())
System.out.printf("%d\t%.2f%%\n", key, counts.get(key) * 100.0 / amount);
}
}
You can adapt your code to not even have to ask how many numbers you plan to enter.
import java.util.Scanner;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
ArrayList<Integer> values = new ArrayList<>();
System.out.println("Please enter some numbers, n to terminate: ");
while(kb.hasNextInt())
values.add(kb.nextInt());
System.out.println("\nYou entered the following values:");
double runningSum = 0;
for(int elem : values) {
runningSum += elem;
System.out.print(elem + " ");
}
System.out.println("\nThe average of the values entered is: "
+ runningSum / values.size());
}
}
We have a java assignment where in we're supposed to develop a method that scans one line that is supposed to contain three double values and returns the largest. Throwing all possible exceptions is allowed.
Here is what I've done so far:
import java.util.Scanner;
public class s3dv {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double entered;
System.out.println("Enter 3 values to find the maximum:");
entered = input.nextDouble();
System.out.println("Maximum is - " + getMaxValue(entered));
}
//Find maximum (largest) value in array using loop
public static double getMaxValue(double[] numbers){
double maxValue = numbers[0];
for(int i = 1; i < numbers.length; i++){
if(numbers[i] > maxValue){
maxValue = numbers[i];
}
}
return maxValue;
} // End getMaxValue method
}
I'm having an error at line 15.
change your code to
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
double[] entered = new double[3];
System.out.println("Enter 3 values to find the maximum:");
for(int i=0;i<3;i++){
entered[i] = input.nextDouble();
}
System.out.println("Maximum is - " + getMaxValue(entered));
}
//Find maximum (largest) value in array using loop
public static double getMaxValue(double[] numbers){
double maxValue = numbers[0];
for(int i = 1; i < numbers.length; i++){
if(numbers[i] > maxValue){
maxValue = numbers[i]; } } return maxValue;
}
You cannot give a double parameter to a method while it expects a double array. And also you request user to enter double value only once, you should repeat that procedure. Change your main method to this:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double[] entered = new double[3];
int counter = 0;
while (counter != 3)
{
System.out.println("Enter a double value:");
entered[counter++] = input.nextDouble();
}
System.out.println("Maximum is - " + getMaxValue(entered));
}
Your getMaxValue() method seems OK, however when entering doubles from console use comma(,) instead of dot(.), you might get InputMismatchException otherwise.
this main code will read the 3 double value in a single line, split them and pass it to the getMaxValue
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String userLine, lineSplitted[];
System.out.println("Enter 3 values to find the maximum:");
userLine = input.nextLine();
lineSplitted=userLine.split(" ");
double entered[]=new double[lineSplitted.length];
for (int i=0; i<lineSplitted.length; i++) entered[i]=Double.valueOf(lineSplitted[i]);
System.out.println("Maximum is - " + getMaxValue(entered));
}
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);
}
}
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!!
Here's a simple code that reads strings from stdin, adds them into List<String>, 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) {
List<String> list = new ArrayList<String>();
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:
Why is it preferred to use Lists instead of Arrays in Java?
Fill a array with List data
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();
}
}
You can do the following:
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<5; i++) {
System.out.print("Enter number " + (i+1) + ": ");
arr[i] = scan.nextInt(); // Taking user input
}
// For printing those numbers
for(int i=0; i<5; i++)
System.out.println("Number " + (i+1) + ": " + arr[i]);
}
}
It vastly depends on how you intend to take this input, i.e. how your program is intending to interact with the user.
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 accept array by user Input
Answer:-
import java.io.*;
import java.lang.*;
class Reverse1 {
public static void main(String args[]) throws IOException {
int a[]=new int[25];
int num=0,i=0;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Number of element");
num=Integer.parseInt(br.readLine());
System.out.println("Enter the array");
for(i=1;i<=num;i++) {
a[i]=Integer.parseInt(br.readLine());
}
for(i=num;i>=1;i--) {
System.out.println(a[i]);
}
}
}
import java.util.Scanner;
class Example{
//Checks to see if a string is consider an integer.
public static boolean isInteger(String s){
if(s.isEmpty())return false;
for (int i = 0; i <s.length();++i){
char c = s.charAt(i);
if(!Character.isDigit(c) && c !='-')
return false;
}
return true;
}
//Get integer. Prints out a prompt and checks if the input is an integer, if not it will keep asking.
public static int getInteger(String prompt){
Scanner input = new Scanner(System.in);
String in = "";
System.out.println(prompt);
in = input.nextLine();
while(!isInteger(in)){
System.out.println(prompt);
in = input.nextLine();
}
input.close();
return Integer.parseInt(in);
}
public static void main(String[] args){
int [] a = new int[6];
for (int i = 0; i < a.length;++i){
int tmp = getInteger("Enter integer for array_"+i+": ");//Force to read an int using the methods above.
a[i] = tmp;
}
}
}
int length;
Scanner input = new Scanner(System.in);
System.out.println("How many numbers you wanna enter?");
length = input.nextInt();
System.out.println("Enter " + length + " numbers, one by one...");
int[] arr = new int[length];
for (int i = 0; i < arr.length; i++) {
System.out.println("Enter the number " + (i + 1) + ": ");
//Below is the way to collect the element from the user
arr[i] = input.nextInt();
// auto generate the elements
//arr[i] = (int)(Math.random()*100);
}
input.close();
System.out.println(Arrays.toString(arr));
This is my solution if you want to input array in java and no. of input is unknown to you and you don't want to use List<> you can do this.
but be sure user input all those no. in one line seperated by space
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int[] arr = Arrays.stream(br.readLine().trim().split(" ")).mapToInt(Integer::parseInt).toArray();