Creating an array with user input - java

I'm trying to create a code that lets the user determine the size and elements of an array and then print it out. So far I have this.
import java.util.Scanner;
public class test3 {
public static void main (String[] args)
{
Scanner keyboard=new Scanner(System.in);
System.out.println("Input how many numbers you want to find the median for (numerical value) :");
int num = keyboard.nextInt();
System.out.println("Please enter " + num + " numbers.");
int[] values = new int[num];
for (int i = 0; i < num; i++) {
values[i] = keyboard.nextInt();
System.out.println(values[i]);
}
}
}
I don't know if it is right because when a user inputs the size and then the elements, the code is just displaying the element as the user inputs it. For example,
input how many numbers you want to find the median for
5
please enter 5 numbers
3//user input
3//what is displayed.
I want to make it so that the user inputs all of their numbers and THEN it displays the inputed numbers as an array.
We are not allowed to use the array class by the way.

import java.util.Scanner;
public class test3 {
public static void main (String[] args) {
Scanner keyboard=new Scanner(System.in);
System.out.println("Input how many numbers you want to find the median for (numerical value) :");
int num = keyboard.nextInt();
System.out.println("Please enter " + num + " numbers.");
int[] values = new int[num];
for (int i = 0; i < num; i++) {
values[i] = keyboard.nextInt();
}
for (int i = 0; i < num; i++) {
System.out.println(values[i]);
}
}
}

Your for loop will execute for as many number as the user has entered, in your test case 5. Every iteration will take a number from the keyboard input, place it into the array and display it. Since you want to capture all the numbers first and then want to display them you should remove
System.out.println(values[i]);
from the for loop and place that into another for loop to display the numbers like so
for(int x=0 ;i < num ; i++)
{
System.out.println(values[x]);
}
This way the first loop will gather all the numbers and after the numbers are collected the second loop will display the numbers one by one iterating over the array.
Hope this helps!

Related

How to resolve Exception in thread error (ArrayIndexOutOfBoundsException) in Java?

This code is to input n integer values and calculate the no. of even and odd values among those inputted values.
This java code shows ArrayIndexOutOfBoundsException when used do..while loop, however when used for loop it worked fine. Haven't changed any thing just rearranged the syntax so as to convert for loop into do while loop.
FOR LOOP:
import java.util.*;
public class EvenOddCount
{
public static void main(String args[]) throws Exception
{
System.out.print("Enter the no. of inputs to be taken : ");
int evenCount=0, oddCount=0;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a[] = new int[n];
System.out.println("Enter the inputs : ");
for(int i=0;i<n;i++)
a[i] = sc.nextInt();
for(int i=0;i<a.length;i++)
{
if(a[i]%2==0)
evenCount++;
else
oddCount++;
}
System.out.println("\nThe number of even numbers in input numbers are : "+evenCount);
System.out.println("The number of odd numbers in input numbers are : "+oddCount);
}
}
The above code works fine and gives suitable output.
DO...WHILE LOOP:
import java.util.*;
public class EvenOddCount
{
public static void main(String args[]) throws Exception
{
System.out.print("Enter the no. of inputs to be taken : ");
int evenCount=0, oddCount=0, i=0;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a[] = new int[n];
System.out.println("Enter the inputs : ");
do
{
a[i] = sc.nextInt();
i++;
} while (i<n);
do
{
if(a[i]%2==0)
evenCount++;
else
oddCount++;
i++;
} while (i<a.length);
System.out.println("\nThe number of even numbers in input numbers are : "+evenCount);
System.out.println("The number of odd numbers in input numbers are : "+oddCount);
}
}
The above code has a runtime exception i.e.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at EvenOddCount.main(EvenOddCount.java:20)
In your original code, you had two separate i variables:
for(int i=0;i<n;i++)
...
for(int i=0;i<a.length;i++)
In your do/while version, you've got one i variable. Once you've gone through the first loop, the value of i will be n - but you start on the second loop without resetting it to 0, so on the very first iteration it will be out of range.
You can fix that by adding:
i = 0;
just before the second do/while loop, but be aware that you'll still have a problem (even in the first loop) if n is 0, because you're not checking the condition until the end of the iteration. If you use:
while (i < n)
and
while (i < a.length)
instead, that will check the condition before the first iteration, so it will execute 0 times when n is 0. (You still need to reset i to 0 before the second loop though.)
U need to reset the value of i :
do
{
a[i] = sc.nextInt();
i++;
} while (i<n);
i =0;
do
{
if(a[i]%2==0)
evenCount++;
else
oddCount++;
i++;
} while (i<a.length);

How to separate this array?

How do I solve the following problem?
Please see link here.
My code only works when the data is entered horizontally.
How would I go about changing my code in order to be able to display the sums like my 2nd example above in the link?
Here's my code:
import java.util.Scanner;
public class sums_in_loop {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
String code = scanner.nextLine();
String list[] = code.split(" ");
for( int counter = 0; counter < list.length; counter++) {
int sum = 0;
System.out.println(sum + " ");
}
}
}
Judging by the URL you provided, the solution is rather straight-forward.
Ask the user how many pairs to enter
Declare an array of integers with a size of the user input from step 1
Run a loop based on the user input from step 1
Declare an array of integers with a size of 2
Run a nested loop of two to get user input for the two integers
Add the two numbers into the array from step 2
Display results
With that in mind (I assume only valid data is being used):
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
System.out.print("How many pairs do you want to enter? ");
int numberOfPairs = input.nextInt();
int[] sums = new int[numberOfPairs];
for (int i = 0; i < numberOfPairs; i++) {
int[] numbers = new int[2];
for (int j = 0; j < numbers.length; j++) {
// Be sure to enter two numbers with a space in between
numbers[j] = input.nextInt();
}
sums[i] = numbers[0] + numbers[1];
}
System.out.println("Answers:");
for (int sum : sums) {
System.out.print(sum + " ");
}
}
Results:
How many pairs do you want to enter? 3
100 8
15 245
1945 54
Answers:
108 260 1999

Java - Calculating mean of grades stored in array + printing grades below mean

Beginner Java programmer here. I am trying to make a program that asks the user how many grades they would like to enter. Then, I want to store the grades the user entered into an array. Finally, I want to find the mean of the grades entered and print out a list of every grade below the mean. As of now, my code calculates the mean of the grades that the user enters but I cannot figure out how to print the grades below the mean. I believe the problem lies in my last for loop but I cannot figure out how to fix it. Also, did I implement the array correctly? Thanks to every who took the time to help me!
public static void grades() {
int q = 0;
double grades = 0;
double total = 0;
Scanner in = new Scanner(System.in);
// user input how many grades user would like to enter
System.out.println("How many grades would you like to enter? ");
q = in.nextInt();
// user enters # of grades they requested to enter
for (int counter = 0; counter < q; counter++) {
System.out.println("Enter your grades: ");
grades = in.nextInt();
// This creates an array that stores the grades the user entered
double[] scores = new double[] {grades};
// adds up all elements (grades)
for (int k = 0; k < scores.length; k++) {
total += scores[k]; //sums up entered grades
}
}
total = total / q; //calcs mean
//loops prints grades less than mean
for (grades = 0; grades < total; grades++){
System.out.println(grades);
}
}
public static void grades(){
Scanner in = new Scanner(System.in);
System.out.println("How many grades would you like to enter? "); //user input how many grades user would like to enter
int q = in.nextInt();
double[] grades = new double[q];
double sum = 0;
for (int counter = 0; counter < q; counter++){ //user enters # of grades they requested to enter
System.out.println("Enter your grades: ");
double grade = in.nextInt();
grades[counter] = grade;
sum += grade;
}
double mean = sum / q;
System.out.println("Mean: " + mean);
for (int i = 0; i < q; i++){ //loops prints grades less than mean
if (grades[i] < mean) {
System.out.println(grades[i]);
}
}
}
Your last loop makes no sense
You should be counting through ALL the items in the array and then doing an IF to test if it's below the mean and then printing it if it is below the mean
You have made the loop iterate from 0 up to the mean.. that just makes no sense it's like saying the mean score among a group of students was 30% now print all the grades from student0 to student30 That makes no sense to do that. You should be interested in student 31 and student 32.. dont' stop at student number 30. student1 might have a grade above the mean and student 40 may have a grade below the mean. you're mixing up the student number(the index of the location in the array) with the grade.
ADDED
You are actually doing even worse than that..because grades isn't even an array it is a variable with one number in it. You have an array that increments a variable and prints the variable like printing 1,2,3,4,5
You're meant to do a loop i=1 to n, and print array[i]
You are doing a loop i=1 to n and you are printing i
You should figure out what an array is all about rather than worrying about calculating a mean. Make your own simpler exercises testing what you do/don't understand rather than something out of a book or something the teacher gave you. And use your explorations to understand this exercise your teacher/book gave you.
Your code had some issues. First off your array was being initialized with every iteration for a new grade being entered, which would result in one index since the previous inputs were overriding it. The array scores should be initialized outside the for loop.
Also, your for loop for printing out the grades wasn't correct. You needed to iterate over the scores array and print out each individual value.
The code below works and demonstrates where you went wrong:
public static void grades() {
int q = 0;
double grades = 0;
double total = 0;
Scanner in = new Scanner(System.in);
// user input how many grades user would like to enter
System.out.println("How many grades would you like to enter? ");
q = in.nextInt();
double[] scores = new double[q];//initialize here
// user enters # of grades they requested to enter
for (int i = 0; i < scores.length; i++) {
System.out.println("Enter your grades: ");
grades = in.nextInt();
// This creates an array that stores the grades the user entered
scores[i] = grades;//append values to each index
// adds up all elements (grades)
total += scores[i]; //sums up entered grades
}
total = total / q; //calcs mean
System.out.println("Mean: " + total);
//iterate through the scores array with filled values
for (int i = 0; i < scores.length; i++) {
System.out.println("Grade #" + i + ": " + scores[i]);
}
}
what might be the problem of that .. the total and average is wrong.
import java.io.*;
class overloading2
{
String name;
int year;
String section;
String subject[];
double grade[];
double average;
public void enrolSubjects()throws Exception
{
DataInputStream mat=new DataInputStream(System.in);
try
{
System.out.println("Enter 3 subject:");
subject=new String[3];
for(int sub=0;sub<3;sub++)
{
subject[2]=(mat.readLine());
}
}
catch(IOException ioe)
{
}
}
public double enterGrades(double grade1,double grade2,double grade3)
{
DataInputStream math=new DataInputStream(System.in);
try
{
System.out.println("Enter 3 grades:");
grade=new double[3];
for(int x=0; x<3; x++)
{
grade[2]=Double.parseDouble(math.readLine());
}
}
catch(IOException ioe)
{
}
return enterGrades();
}
double enterGrades()
{
double total=0.0;
for(int x=0; x<3; x++)
{
total+=grade[2];
average=total/3;
}
return average;
}
public static void main(String []args)throws Exception
{
overloading2 ostud1=new overloading2();
double a=0.0,b=0.0,c=0.0;
ostud1.enrolSubjects();
ostud1.enterGrades(a,b,c);
System.out.println("average grade is "+ostud1.enterGrades());
}
}

set number entered by user and save it in array

I have to save 10 numbers entered by a user into an array using a for loop. After that, I have to use an enhanced for loop to find the largest and smallest values in the array. I don't know how to save numbers in an array. I also have problems finding the smallest and largest values from the array and displaying them. I got an error on the for loop section where I set highestvalue and lowestvalue=inputnumber.
Here is my code:
import java.util.Scanner;
public class ArrayTester
{
public static void main(String[] args)
{
//create a scanner object
Scanner input= new Scanner (System.in);
//declare largestNumber
int largestNumber;
//declare smallestNumber
int smallestNumber;
//declare inputNumber
int inputNumber = 0;
//declare array named number and set it to 10
int[] number = new int[10];
//display message
System.out.print ("Enter an integer: ");
//column headings
for (int counter = 0; counter < number.length; counter++)
{
//set number equal to next input
inputNumber = input.nextInt();
number[inputNumber] = inputNumber;
//for (number[inputNumber]>=largestNumber && number[inputNumber]>=smallestNumber)
//{
//largestNumber=inputNumber;
//smallestNumber=inputNumber;
//}
}
System.out.printf("%s%8s\n", "index", "value");
System.out.printf("%5d%8d\n", counter, number[inputNumber]);
System.out.printf("The largest value in the array is %d\nThe smallest value in the array is %d\n", largestNumber, smallestNumber);
}
}
Replace
number[inputNumber] = inputNumber;
with
number[counter] = inputNumber;
and thats it. As for finding mix and max, use Collections.sort() on your array. First element will be min, and the last max.
Change
number[inputNumber] = inputNumber;
to
number[counter] = inputNumber;
You want to add each new number to the counter position of the array.
As for finding the minimum, maximum. The same loop that reads the inputs into the array can do that. Initialize largestNumber to Integer.MIN_VALUE and smallestNumber to Integer.MAX_VALUE. Then, each time you get a new number, compare it to both largestNumber and smallestNumber, and update them if the new number is higher/lower respectively.
assuming that you don't have to store the numbers in the same order in which they were entered by the user, you would make a sorted insert. that means, for each value entered, find the index at which this number can be inserted while maintaining a sorted array (if there exists a number at this index you have to move it move it to the right)
provided a sorted array you can find min and max in O(1):
min = number[0];
max = number[n-1];
make the following changes
//create a scanner object
Scanner input= new Scanner (System.in);
//declare largestNumber
int largestNumber;
//declare smallestNumber
int smallestNumber ;
//declare inputNumber
int inputNumber = 0;
//declare array named number and set it to 10
int[] number = new int[10];
//display message
System.out.print ("Enter an integer: ");
//column headings
for (int counter = 0; counter < number.length; counter++)
{
//set number equal to next input
inputNumber = input.nextInt();
number[counter] = inputNumber;
// for loop that will check for largest and smallest no
}
smallestNumber = number[0];
largestNumber = number[0];
for(int i=1; i< number.length; i++)
{
if(number[i] > largestNumber)
largestNumber = number[i];
else if (number[i] < smallestNumber)
smallestNumber = number[i];
}
// System.out.printf("%s%8s\n", "index", "value");
// System.out.printf("%5d%8d\n", counter, number[inputNumber]);
System.out.printf("The largest value in the array is %d\nThe smallest value in the array is %d\n", largestNumber, smallestNumber);
Also: you cannot use a for loop in this way
for (number[inputNumber]>=largestNumber && number[inputNumber]>=smallestNumber)
this is a conditional case not a loop
I would suggest you to try out this one.Let me know if it works.:-
import java.util.Scanner;
public class Practice {
public static void main(String[] args){
Scanner in=new Scanner(System.in);
int num[]=new int[10];
int max=0,min=0;
for(int i=0;i<10;i++){
System.out.println("Enter number:-");
num[i]=in.nextInt();
if(num[i]>=max)
max=num[i];
if(num[i]<=min)
min=num[i];
}
min=num[0];
for(int i=0;i<10;i++){
if(num[i]<=min)
min=num[i];
}
System.out.println("The array elements are:-");
for(int i=0;i<10;i++)
System.out.print(num[i]+" ");
System.out.println();
System.out.println("Largest is:-"+max+" "+"Smallest is:"+min);
}
}

Using arrays in Java

Im working on an assignment for a beginners Java course, and Im having a problem with printing out an array the way that its asking for. The problem is as follows:
"Write a program that asks the user "How many numbers do you want to enter?" With that value, create an array that is big enough to hold that amount of numbers (integers). Now ask the user to enter each number and store these numbers into the array. When all the numbers have been entered, display the numbers in reverse order from the order in which they were entered."
I have everything except the last part, displaying the numbers in reverse order.
Any help on this would be appreciated.
Heres What I have so far:
import java.util.Scanner;
public class ArraysNickGoldberg
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("How many numbers do you want to enter?");
final int NUMBER_OF_ELEMENTS = input.nextInt();
int[] myList = new int[NUMBER_OF_ELEMENTS];
for( int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
System.out.println("Enter a new number: ");
myList[i] = input.nextInt();
}
for( int i = 0; i < NUMBER_OF_ELEMENTS; i++){
System.out.print(myList[i] + " ");
}
}
}
try
for( int i = NUMBER_OF_ELEMENTS - 1; i >= 0; i--){
System.out.print(myList[i] + " ");
}
You may also want to look at
Java Array Sort
to print it in reverse order, you just need to simply reverse your for loop :)
so instead of
for(int i=0; i< NUMBER_OF_ELEMENTS; i++){
}
use this instead:
for(int i=NUMBER_OF_ELEMENTS - 1; i >= 0; i--){ //remember to minus 1 or else you'll get index of out of bound
}

Categories