Input inside Arrays (java)? - java

So, I have a very messy code. The purpose of the code is to find the minimum and maximum values of a set of numbers that the user entered using arrays. The problem is I don't know how to put the Array elements (Elements) into my array (numbersArray). Here's what I have so far :
package com.company;
import java.util.*;
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Main {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner elements = new Scanner(System.in);
System.out.println("Enter in number of numbers:");
String num = elements.nextLine();
int numArrayElements = Integer.parseInt(num);
System.out.println("Enter in numbers please: ");
Scanner console = new Scanner(System.in);
String userInput = console.nextLine();
int Elements = Integer.parseInt(userInput);
int [] numbersArray = new int[numArrayElements];
int sum = 0;
for (int i = 0 ; i < numbersArray.length ; i++) {
int temp = numArrayElements.nextInt();
numbersArray[i] = temp;
sum += temp;
}
Arrays.sort(numbersArray);
System.out.println((sum - numbersArray[numbersArray.length-1])
+ " " + (sum - numbersArray[0]));
}
}
How can I make it so that I can put Elements into numbersArray?

Your major problem is the part where you try to read values entered by the user:
for (int i = 0 ; i < numbersArray.length ; i++) {
int temp = numArrayElements.nextInt();
...
}
The variable numArrayElements is of type int, you can't call a method nextInt on it, it does not exist.
The method, however, exists for objects of type Scanner, like your elements variable.
After that your code probably compiles and does something useful. At least you set the array items correctly by using
numbersArray[i] = temp;
I'm not that sure about the min/max part though. I don't get why you need the sum if you sort the array. After sorting you can just take the first (min) and last element (max) given by numbersArray[0] and numbersArray[numbersArray.length - 1].
And I'm not sure why you do the parsing stuff in between, does not seem necessary. Same holds for the second scanner, not needed since you already have one.
Let me show you a cleaner approach.
Scanner scanner = new Scanner(System.in);
// Amount of values
System.out.println("Enter amount of values:");
int amount = scanner.nextInt();
// Read values
System.out.println("Enter " + amount + " values:");
int[] values = new int[amount];
for (int i = 0; i < values.length; i++) {
values[i] = scanner.nextInt();
}
// Compute max and min
...
For the last part you have several options. The most efficient would probably be to remember it already at the moment where you read the values. Your sorting approach works too, but is much more work than needed since you don't need the order of all elements, you only need the min and max element.
Let's first do a manual approach
// Compute max and min
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int value : values) {
if (value > max) {
max = value;
}
if (value < min) {
min = value;
}
}
The second approach uses a built-in method which essentially does the same. However, it is less efficient since we will first need to built a Collection on top of the array and then do two iterations instead of only one (one for max, one for min). Also, due to the conversion we need wrapper objects Integer instead of primitive values int.
// Compute max and min
Collection<Integer> valuesAsColl = Arrays.asList(values);
int max = Collections.max(valuesAsColl);
int min = Collections.min(valuesAsColl);
The third approach uses the Java Stream API (since Java 8), looks elegant and does not need to convert stuff to Integer or Collection. But the two iterations instead of one remain.
// Compute max and min
int max = Arrays.stream(values).max();
int min = Arrays.stream(values).min();

I not understand your ask .. however this code for set array size from user and numbers of array by user..
public class JavaApplication2 {
public static int[] numbers() {
Scanner element = new Scanner(System.in);
System.out.print("please insert array long : ");
int count = element.nextInt();
System.out.print("enter numers : ");
element.nextLine(); // throw away the newline.
int [] numbers = new int[count];
Scanner numScanner = new Scanner(element.nextLine());
for (int i = 0; i < count; i++) {
if (numScanner.hasNextInt()) {
numbers[i] = numScanner.nextInt();
} else {
System.out.println("You didn't provide enough numbers");
break;
}
}
return numbers;
}
public static void main(String[] args) {
int[] numbersa = numbers();
System.out.println(Arrays.toString(numbersa));
}
}

Related

Getting 0 for minimum value but the maximum value is okay

I am trying to input an array using a scanner. That part is already done. Now, I am tasked to get the maximum and minimum numbers from my input. I was able to get the maximum but with the minimum, it is returning 0.
Is there a misplacement of syntax perhaps?
import java.util.Scanner;
public class App {
public static void main(String[] args) {
int in;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements you want to store: ");
in=sc.nextInt();
int array[] = new int[in];
int min = array[0];
int max = array[0];
for (int i=0; i < in; i++){
System.out.print("Input number "+(i+1)+" :");
array[i]=sc.nextInt();
if(array[i]>max){
max=array[i];
}
else if (array[i]<min){
min=array[i];
}
}
sc.close();
System.out.print(" The inputed array is ");
for (int i=0; i < in; i++){
System.out.print(array[i]+" ");
}
System.out.println("\n --------------------");
System.out.println("The highest number is: "+max);
System.out.println("The lowest number is: "+ min);
}
}
(also if you can, can y'all tell me how to get the index of the minimun and maximum value and print it?)
I tried different if and else if methods. I also tried nesting but I am getting the same outcome.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class App {
public static void main(String[] args) {
int in;
List<Integer> elements = new ArrayList<>();
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements you want to store: ");
in=sc.nextInt();
for (int i=0; i < in; i++){
System.out.print("Input number "+(i+1)+" :");
elements.add(sc.nextInt());
}
sc.close();
List<Integer> unsorted = new ArrayList<>(elements);
Collections.sort(elements);
int max = elements.get(elements.size()-1);
int min = elements.get(0);
System.out.println("\n --------------------");
System.out.println("The highest number is: "+max);
System.out.println("The lowest number is: "+ min);
System.out.println("Index of Min Value is : "+unsorted.indexOf(min));
System.out.println("Index of Max Value is : "+unsorted.indexOf(max));
}
}
When you declare an initialize your int array[]:
int array[] = new int[in];
you essentially are filling each array element with 0 by default. Then, when you declare and initialize the min and max variables with array[0] it would be the same as declaring:
int min = 0;
int max = 0;
The max variable is at a relatively low value which is good unless the User enters all signed (negative) integer values to make up the array elements in which case none of those entry values will ever max over 0 which means at the end, max will be 0 which is also wrong.
The same theory applies to the min variable. Since the min variable already holds a low value of 0 (initialized as such), the only way an element value within the array[] Array will be lower is if the array actually contained a signed (negative) value. If it doesn't the the already held value in min will remain to be the lowest value...which as you know will be in most cases wrong.
The thing to do in this particular use-case would be to initialize the min variable with a value which would be the largest a int data type can hold:
int min = Integer.MAX_VALUE;
You would be pretty much guaranteed that a value within the int[] array will never exceed Integer.MAX_VALUE and that if there is a element within the array that is lower, min will end up getting updated to that value.
The same should be applied to the initialization of the max variable except with the lowest possible int data type value:
int max = Integer.MIN_VALUE;
I think at this point you can understand why. ;)
So, all in all, simply change:
int min = array[0];
int max = array[0];
to this instead:
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
and all should be fine.
On A Side:
In a real world application where a User is expected to fill in values for an Array, there is no way of knowing what the User (like your instructor) may be entering to fill the elements of that array unless you code specifically to ensure a particular value range. By doing what is described above eliminates any worry of that unless the User supplies a value greater than what an int data type can accept in which case an exception would occur and the application will crash.
You are initializing min even before taking inputs. That's why the min value is always 0 because the default initial value of int array is 0. So, the else if (array[i]<min) condition is never met because no non-negative integer can be smaller than 0.
You can try adding this in your for loop AFTER you take inputs:
if(i==0){
min = array[0];
max = array[0];
}
You can also use type Integer (instead of int), as they can be initialized by null
Integer max = null;
Integer min = null;
In your loop:
if(max == null || max < array[i]) {
max = array[i];
}
if(min == null || min > array[i]) {
min = array[i];
}

Moving Average Using User-Input Array

I need to write a program that calculates a moving average by a user inputted array. The first element of the array is the window size, and the input is terminated by a 0. The output values are printed with two digits after the decimal point.
Example input: 3 2 4 7 7 8 11 12 0
Corresponding Output: 4.33 6.00 7.33 8.67 10.33
(4.33 is average of 2,4,7 and 6 is average of 4,7,7 etc.)
Here's my code so far:
package movingaverage;
import java.util.Scanner;
public class MovingAverage {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
avg[0] = sum / 5;
int j = 1;
for (int i = 5; i < arr.length; i++) {
sum = sum + arr[i] - arr[i - 5];
avg[j++] = sum / 5;
}
}
}
I think I have the loop right, but I'm not sure how to get the array to end at 0.
This is a possible solution.
public class Test
{
private static final Scanner SCANNER;
static {
SCANNER = new Scanner(System.in);
}
public static final void main(final String... args) {
final String[] numbers = SCANNER.nextLine().trim().split(" ");
final int consideredElements = Integer.parseInt(numbers[0]);
float sum = 0;
int value = 0;
for (int i = 1; i < numbers.length; i++) {
sum = 0;
for (int k = 0; k < consideredElements; k++) {
value = Integer.parseInt(numbers[i + k]);
if (value == 0) {
return;
}
sum += value;
}
System.out.println(new BigDecimal(sum / consideredElements).setScale(2, RoundingMode.HALF_EVEN));
}
}
}
First, you are using 5 in a couple of places in your program, I see no justification for that. Could it be that your expectation of user input lead you to put 5 where the number you really should use, depends on user input? Maybe you should use the window size instead? I’m guessing a bit here.
Next, as #lppEdd pointed out, you are not reading the numbers from your input — only the window size.
Next, you are declaring your array of size n, which I believe was your window size, not your array size. I believe the real solution to this problem is using better and more explanatory variable names.
Your code does not compile since you have not declared the array avg that you try to store your moving average into.
Fifth, when you want your average as a double, you need to convert to double before dividing (this is a classic pitfall that has already generated many questions on Stack Overflow).
I hope this gets you a couple of steps further.

Java Random Utility Generating Too Many 0's And Static Numbers

The line birthdays[j] = rnd.nextInt(365); seems to generate extra 0's in the int[] birthdays array. It also seems to add an EXTRA 0 into the array and generate static values depending on how many simulations I run and how many birthdays I generate. For instance, if I do 5 simulations and enter a 3 for the number of people in each simulation's "birthday pool" I always get an array of [0, 0, 289, 362].
Any help understanding the problem would be greatly appreciated.
public static void main(String[] args) {
System.out.println("Welcome to the birthday problem Simulator\n");
String userAnswer="";
Scanner stdIn = new Scanner(System.in);
do {
int [] userInput = promptAndRead(stdIn);
double probability = compute(userInput[0], userInput[1]);
// Print results
System.out.println("For a group of " + userInput[1] + " people, the probability");
System.out.print("that two people have the same birthday is\n");
System.out.println(probability);
System.out.print("\nDo you want to run another set of simulations(y/n)? :");
//eat or skip empty line
stdIn.nextLine();
userAnswer = stdIn.nextLine();
} while (userAnswer.equals("y"));
System.out.println("Goodbye!");
stdIn.close();
}
// Prompt user to provide the number of simulations and number of people and return them as an array
public static int[] promptAndRead(Scanner stdIn) {
int numberOfSimulations = 0;
while(numberOfSimulations < 1 || numberOfSimulations > 50000) {
System.out.println("Please Enter the number of simulations to do. (1 - 50000) ");
numberOfSimulations = stdIn.nextInt();
}
int sizeOfGroup = 0;
while(sizeOfGroup < 2 || sizeOfGroup > 365) {
System.out.println("Please Enter the size of the group of people. (2 - 365) ");
sizeOfGroup = stdIn.nextInt();
}
int[] simulationVariables = {numberOfSimulations, sizeOfGroup};
return simulationVariables;
}
// This is the method that actually does the calculations.
public static double compute(int numOfSims, int numOfPeeps) {
double numberOfSims = 0.0;
double simsWithCollisions = 0.0;
int matchingBirthdays = 0;
int[] birthdays = new int[numOfPeeps + 1];
int randomSeed = 0;
for(int i = 0; i < numOfSims; i++)
{
randomSeed++;
Random rnd = new Random(randomSeed);
birthdays = new int[numOfPeeps + 1];
matchingBirthdays = 0;
for(int j = 0; j < numOfPeeps; j++) {
birthdays[j] = rnd.nextInt(365);
Arrays.sort(birthdays);
}
for(int k = 0; k < numOfPeeps; k++) {
if(birthdays[k] == birthdays[k+1]) {
matchingBirthdays++;
}
}
if(matchingBirthdays > 0) {
simsWithCollisions = simsWithCollisions + 1;
}
}
numberOfSims = numOfSims;
double chance = (simsWithCollisions / numberOfSims);
return chance;
}
}
The line "birthdays[j] = rnd.nextInt(365);" seems to generate extra 0's in the int[] birthdays array.
Well, it doesn't. The array elements where zero to start with.
What that statement actually does is to generate a single random number (from 0 to 364) and assign it to one element of the array; i.e. the jth element. That is not what is required for your problem.
Now, we could fix your code for you, but that defeats the purpose of your homework. Instead I will give you a HINT:
The birthdays array is supposed to contain a COUNT of the number of people with a birthday on each day of the year. You have to COUNT them. One at a time.
Think about it ...
int arrays are by default initialized to 0 unless explicitly specified. Please see this Oracle tutorial about Arrays.
I found the problem myself. The issue was that having the "Arrays.sort(birthdays);" statement inside of a loop. That generated extra 0's.

Finding out the frequency of unique numbers

I am trying to solve a problem in Java as part of my assignment. The problem is as below:
The user enters ten numbers one by one upon prompting by the screen. The screen then assigns all the distinct value to an array and a similar array to hold the frequency of how many times those numbers have appeared.
I have done the below work, but seems I am stuck somewhere in assigning the frequencies and distinct values to the arrays:
import java.util.*;
public class JavaApplication10
{
public static void main(String[] args)
{
int [] numbers = new int [10];
int [] count = new int[10];
int [] distinct = new int[10];
for (int k=0;k<10;k++)
{
count[k]=0;
distinct[k]=0;
}
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter number 0: ");
numbers[0]=input.nextInt();
count[0]=1;
distinct[0]=numbers[0];
int j=0;
for (int i = 1;i<10;i++)
{
System.out.print("Enter number "+i+": ");
numbers[i]=input.nextInt();
while(j<i)
{
if (distinct[j]==numbers[i])
count[j]=count[j]+1;
else
distinct[j+1]=numbers[i];
j++;
}
}
for (int k=0;k<10;k++)
{
System.out.println(distinct[k]+ " "+count[k]);
}
}
}
I know that it is not fair to ask someone to help me solve the problem. But any kind of hint will be helpful.
Thank you
are the numbers limited to 0-9? If so, I would simple do the assignment.
(please note you will assign the input to a variable called "input"):
numbers[0]=input;
count[input]++;
Also you can start your for loop in "0" to avoid the assignment prior to the for loop.
Just a hint.
Hope this helps!
the ideal data structure would be a HashMap
Steps:
1) initialize an array to store the numbers and for each input
2) check if a hashmap entry with key as the entered number already exists
3) if exists simply increase its count
4) else create new entry with key as the number and count as 1
so at the end your frequencies would be calculated
if you are forced to use 2 arrays
1) initialize two arrays
2) for each input loop the number array and check whether that number is already in the array
3) if so take the array index and increment the value of the frequency array with the same index
4) if not freq[index] = 1
A proper way of doing that would be:
public Map<Integer, Integer> getFrequencies(Iterable<Integer> numbers) {
Map<Integer, Integer> frequencies = new HashMap<Integer, Integer>();
for(Integer number : numbers) {
if (frequencies.get(number) == null) {
frequencies.put(number, 0);
}
frequencies.put(number, frequencies.get(number) + 1);
}
return frequencies;
}
It returns a map number -> frequency.
Arrays are not a way to go in Java, they should be avoided whenever possible. See Effective Java, Item 25: Prefer lists to arrays.
I removed the Scanner object to write the code faster, just replace it with your code above and it should work.
int[] numbers = { 1, 2, 2, 2, 3, 3, 3, 1, 1, 2 };
int[] count = new int[10];
int[] distinct = new int[10];
count[0] = 1;
distinct[0] = numbers[0];
int disPos = 1; //Current possition in the distinct array
boolean valueInarray = false;
for (int i = 1; i < 10; i++) {
valueInarray = false;
for (int d = 0; d < i; d++) {
if (numbers[i] == distinct[d]) {
count[d] = count[d] + 1;
valueInarray = true;
break;
}
}
if (!valueInarray) {
distinct[disPos] = numbers[i];
count[disPos] = 1;
disPos++;
}
}
If you ABSOLUTELY HAVE TO use arrays.. here is a way to do it…
import java.util.Scanner;
import java.util.Arrays;
public class JavaApplication10
{
public static void main(String[] args)
{
int [] numbers = new int [10];
int [] count = new int[10];
int [] distinct = new int[10];
int [] distinct1 = new int[1];
int distinctCount = 0;
boolean found = false;
Scanner input = new Scanner(System.in);
for (int i=0; i<10; i++) {
found = false;
System.out.print("Enter number " + i);
numbers[i]=input.nextInt(); //Add input to numbers array
for (int j=0; j<=distinctCount; j++)
{
if (distinct1[j] == numbers[i]){ // check to see if the number is already in the distinct array
count[j] = count[j] + 1; // Increase count by 1
found = true;
break;
}
}
if (!found) {
distinct[distinctCount] = numbers[i];
count[distinctCount] = 1;
distinctCount++;
distinct1 = Arrays.copyOf(distinct, distinctCount+1);
}
}
for (int j=0; j<distinctCount; j++)
System.out.println("The number " + distinct1[j] + " occurs " + count[j] + " times" );
}
}
I think this is what you need, correct me if I'm wrong...
import java.util.HashMap;
import java.util.Scanner;
public class JavaApplication10 {
public static void main(String[] args) {
// Initializing variables
int[] numbers = new int[10];
HashMap<Integer, Integer> table = new HashMap<Integer, Integer>();
Scanner input = new Scanner(System.in);
// Getting the 10 inputs
for(int x=0; x<10; x++) {
// Asking for input
System.out.println("Enter number "+x+":");
numbers[x]=input.nextInt();
// If the table contains the number, add 1
// Otherwise: set value to 1
if(table.containsKey(numbers[x]))
table.put(numbers[x], table.get(numbers[x])+1);
else
table.put(numbers[x],1);
}
// Closing the reader
input.close();
// Get the highest and smallest number
int highest=0;
int smallest=0;
for(int i:table.keySet()) {
if(i>highest)
highest=i;
if(i<smallest)
smallest=i;
}
// For every value between the smallest and the highest
for (int x=smallest; x<=highest; x++) {
// Check if the frequency > 0, else continue
if(table.get(x)==null)
continue;
// Output
System.out.println(x+" is "+table.get(x)+" times in \'frequence\'");
}
}
}
This also handles with negative numbers, unlike the other's codes. If you don't want to use HashMaps let me know so I can create something with arrays.
Let me know if it (doesn't) works!
Happy coding (and good luck with your assignment) ;) -Charlie

How to find greatest number

How to compute the greatest number and display it?
import java.util.Scanner;
public class GreatestNumber {
public static void main(String[] args) {
int [] num = new int [10];
int counter;
int max = 0;
Scanner read = new Scanner(System.in);
for (int i=0; i<num.length; i++)
{
System.out.print("Enter StaffID to be edited:");
num[i]=read.nextInt();
}
}
}
You probably want to compare the numbers as you're reading them. Also, using 0 as a starting value for max will not print out the results you want if all input values are negative. Use Integer.MIN_VALUE instead:
int [] num = new int [10];
int counter;
int max = Integer.MIN_VALUE; // <-- initial value
Scanner read = new Scanner(System.in);
for (int i = 0; i < num.length; i++)
{
System.out.print("Enter StaffID to be edited:");
num[i] = read.nextInt();
if (num[i] > max)
{
max = num[i];
}
}
System.out.print("Max number is:");
System.out.print(max);
Beside the solution provided by other users, you can make a List from the Array and then use an already existing method that finds the maximum value in the list.
List list = Arrays.asList(ArrayUtils.toObject(num));
System.out.println(Collections.max(list)); //Will print the maximum value
This is how you can do it:
Since you are after the largest number, create an integer which has a very small value.
Iterate over the elements of your array. If the element you are currently looking at is larger than the current largest element (initialized in step 1), then update the value of the largest element.
keep track of the current max and update it if you find a higher number, ie
if (num[i] > max)
max = num[i];
Set a running variable max to Integer.MIN_VALUE. Compare it in a loop with every element in the array, and if the array element is bigger, copy its value to max. In the end you have the biggest element in max.

Categories

Resources