I am working on a java code that calculates the average of an array and it is working perfectly in serving its purpose but I want to modify it to be a 2D array (Two-dimensional).
import java.util.*;
public class Test3{
public static void main(String [] args){
Scanner adnan = new Scanner(System.in);
System.out.println("Enter the length of the array : ");
int length = adnan.nextInt();
int [] input = new int [length];
System.out.println("Enter Numbers : ");
for ( int i = 0; i < length; i++){
input [i] = adnan.nextInt();
}
float average = average(input);
System.out.println("Average of all numbers in the array : " + average);
adnan.close();
}
public static float average(int [] input){
float sum = 0f;
for ( int number : input){
sum = sum + number;
}
return sum / input.length;
}
}
any help would be really appreciated because I am not too good at 2D arrays.
In Java a 2D Array is declared using double brackets T [][]:
public static void main(String[] args) {
// mock to not to use a stdin redirection or enter data manually
ByteArrayInputStream system_in = new ByteArrayInputStream("3 2 5 8 1 6 7 2".getBytes(UTF_8));
Scanner adnan = new Scanner(system_in);
System.out.println("Enter rows number: ");
final int rows = adnan.nextInt();
System.out.println("Enter rows number: ");
final int cols = adnan.nextInt();
final int [][] input = new int[rows][cols];
System.out.println("Enter Numbers : ");
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
input[row][col] = adnan.nextInt();
}
}
double average = average(input);
System.out.println("Average of all numbers in the array : " + average);
adnan.close();
}
public static double average(int[][] input) {
// use streams or you can use the `Enter Numbers...` way
return Arrays.stream(input)
.flatMap(x -> Arrays.stream(x).boxed())
.mapToInt(x -> x).average()
.getAsDouble();
}
with output
Enter rows number:
Enter rows number:
Enter Numbers :
Average of all numbers in the array : 4.833333333333333
Related
I'm making a program using Java that calculates the sum of the numbers entered; I figured this part out. However, I want to move the for loop into a different method called "Sum", but I keep getting errors and I don't know what to do.
Here is the code thats only in the Main method (it works perfectly fine):
import java.util.Scanner;
public class testing {
public static void main(String args[]){
System.out.println("Enter the size of the array: ");
Scanner in = new Scanner(System.in);
int size = in.nextInt();
int myArray[] = new int [size];
int sum = 0;
System.out.println("Enter the elements of the array one by one: ");
for(int i=0; i<size; i++){
myArray[i] = in.nextInt();
sum = sum + myArray[i];
}
System.out.println("Sum of the elements of the array: "+ sum);
}
}
However, when I move the for loop into the method known as print, I get a bunch of errors:
import java.util.Scanner;
public class MPA4 {
public static void main(String[] args) {
System.out.println("Enter the size of the array: ");
Scanner in = new Scanner(System.in);
int size = in.nextInt();
int myArray[] = new int [size];
int sum = 0;
System.out.println("Enter the elements of the array one by one: ");
}
print(sum);
}
public static void print (double []sum){
Scanner in = new Scanner(System.in);
int myArray[] = new int [size];
for(int i=0; i<size; i++){
myArray[i] = in.nextInt();
sum = sum + myArray[i];
}
System.out.println("Sum of the elements of the array: "+ sum);
}
}
Here are all the errors underlined in red:
I'm not sure what I'm doing wrong, any help would be much appreciated!
I changed it as below and it is working.
import java.util.Scanner;
public class MP4 {
public static void main(String[] args) {
System.out.println("Enter the size of the array: ");
Scanner in = new Scanner(System.in);
int size = in.nextInt();
int myArray[] = new int[size];
System.out.println("Enter the elements of the array one by one: ");
for (int i = 0; i < size; i++) {
myArray[i] = in.nextInt();
}
print(myArray, size);
}
public static void print(int[] myArray, int size) {
int sum = 0;
Scanner in = new Scanner(System.in);
for (int i = 0; i < size; i++) {
sum = sum + myArray[i];
}
System.out.println("Sum of the elements of the array: " + sum);
}
}
Currently trying to output the Min and Max of 25 numbers inputed from keyboard, although I am having trouble in the Scanner class to be able to input said numbers. I keep getting an error for cannot make Int[] to an Int.
Here is the question:
(MinMax.java) Read in 25 ints from the keyboard, and store them in an
array. Find the maximum and minimum values in the array, and display
them on the screen.
Here is my current Code:
import java.util.Scanner;
import java.util.Arrays;
public class MinMax{
public static void main (String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Please enter 25 numbers.");
int[] numbers = sc.nextInt();
System.out.println("Minimum Value = " + getMinValue(numbers));
System.out.println("Maximum Value = " + getMaxValue(numbers));
}
public static int getMaxValue(int[] numbers) {
int maxValue = numbers[0];
for(int i=1;i<numbers.length;i++){
if(numbers[i] > maxValue){
maxValue = numbers[i];
}
}
return maxValue;
}
//Find minimum (lowest) value in array using loop
public static int getMinValue(int[] numbers){
int minValue = numbers[0];
for(int i=1;i<numbers.length;i++){
if(numbers[i] < minValue){
minValue = numbers[i];
}
}
return minValue;
}
}
You can't do this:
int[] numbers = sc.nextInt();
That's because sc.nextInt() returns an int not an array of ints.
Instead, you need to create a loop that reads the 25 integers:
int[] numbers = new int[25];
for(int i = 0; i < 25; i++) {
numbers[i] = sc.nextInt();
}
The problem is your main funtion.
Just do this:
public static void main (String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter 25 numbers.");
int[] numbers = new int[25];
for (int i = 0; i < 25; i++) {
System.out.print("Number " + (i+1) + ": ");
numbers[i] = sc.nextInt();
}
System.out.println("Minimum Value = " + getMinValue(numbers));
System.out.println("Maximum Value = " + getMaxValue(numbers));
}
import java.util.Scanner;
public class Lab11d
{
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
double [] anArray; // declares an array of integers
anArray = new double [5];
int min=0;
//Initalizes the array values//
System.out.println ("Enter 5 numbers of your choosing");
double a = in.nextDouble();
for ( int count=0; count < 5; count++)
{
anArray[count] = a;
a = in.nextDouble();
}
//Prints array values//
for (double value : anArray)
System.out.println ("Element at index " + (min++) + ":"+ value + "" );
}
}
It runs, but I only want to input 5 numbers, not sure what I am doing wrong. It allows me to enter six with like a limit of 5, curious how to change it please
Because you get one double before your loop. Change it to something like
// double a = in.nextDouble();
for (int count=0; count < 5; count++)
{
double a = in.nextDouble();
anArray[count] = a;
}
or eliminate a altogether like
for (int count=0; count < 5; count++)
{
anArray[count] = in.nextDouble();
}
You are accepting a double first time and then iterating through a loop which accepts 5 doubles i.e. in total you are accepting 6 doubles.
You have to edit your for loop as,
for ( int count=0; count < 5; count++)
{
anArray[count] = in.nextDouble();
}
before you help me this is a homework assignment, i have most of all of it done but there is one thing that i cant figure out, 0 doesn't get detected at all. This means if i input 0-9 into the array it will tell me there is only 9 distinct numbers when really there should be 10 and it will print out all the numbers but 0. Can anyone see the problem and please explain it to me becuase i need to understand it.
package javaproject.pkg2;
import java.util.Scanner;
public class JavaProject2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numArray = new int[10];
int d = 0;
System.out.println("Enter Ten Numbers: ");
for(int i = 0; i < numArray.length; i++){
int num = input.nextInt();
if(inArray(numArray,num,numArray.length)){
numArray[i] = num;
d++;
}
}
System.out.println("The number of distinct numbers is " + d);
System.out.print("The distinct numbers are: ");
for(int i = 0; i < d; i++){
System.out.print(numArray[i] + " ");
}
}
public static boolean inArray(int[] array, int searchval, int numvals){
for (int i =0; i < numvals; i++){
if (searchval == array[i]) return false;
}
return true;
}
}
You can use a set to identify distinct values:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Set<Integer> distinctNumbers = new LinkedHashSet<>();
System.out.println("Enter ten Numbers: ");
for (int i = 0; i < 10; i++) {
int number = input.nextInt();
distinctNumbers.add(number);
}
System.out.println("The number of distinct numbers is " + distinctNumbers.size());
System.out.print("The distinct numbers are: ");
for (Integer number : distinctNumbers){
System.out.print(number + " ");
}
}
If a value already exists in a set, it can't be added again. Arrays are not the best fit for your problem, since they must be initialized with a fixed size and you don't know how many distinct values the user will inform.
Take a look at numArray after int[] numArray = new int[10]; - it is initialized with zeros.
How do I take in input from a user from a scanner, then put that input into a 2D Array. This is what I have but I dont think it is right:
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int [][] a = new int[row][col];
Scanner in = new Scanner(System.in);
System.out.println("Enter a sequence of integers: ");
while (in.hasNextInt())
{
int a[][] = in.nextInt();
a [row][col] = temp;
temp = scan.nextInt();
}
Square.check(temp);
}
What I am trying to do is create a 2D array and create a magic Square. I have the boolean part figured out, I just need help with inputting users sequence of numbers into the array so the boolean methods can test the numbers. All help greatly appreciated
I don't believe your code will work how you want it to. If I'm understanding your question correctly, here's what I would do:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int [][] a = new int[row][col];
for(int i = 0; i < row; i++) {
for(int j = 0; j < col; j++) {
System.out.print("Enter integer for row " + i + " col " + j + ": ");
a[i][j] = in.nextInt();
}
}
// Create your square here with the array
}
In the loops, i is the current row number and j is the current column number. It will ask the user for every row/column combination.
You can use that in order to enter all number at the same time :
int [][] a = new int[3][3];
Scanner in = new Scanner(System.in);
System.out.println("Enter a sequence of integers: ");
int row=0,col=0;
while (in.hasNextInt())
{
a [row][col++] = in.nextInt();
if(col>=3){
col=0;
row++;
}
if(row>=3)break;
}
Then you can enter :
1 2 3 4 5 6 7 8 9
to fill your array.