How to display numbers less than 3 from an Array - java

I am supposed to write a program that accepts 6 user inputs and display numbers less than 3. I don't know what the problem is and I can't find help anywhere.
public class Apples {
public static void main(String [] args{
double [] numList = new double [6];
Scanner scan = new Scanner(System. in);
for (int i = 0; i<6; i++){
numList[i]=scan.nextDouble(); //user input
}
Arrays.sort(numList[i]); //sort user input
for (numList < 3)
System.out.println(numList);
}
}
}

I would to something like this:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
for(int i=0; i<6; i++) {
double number = scan.nextDouble();
if(number < 3.0) {
System.out.println(number);
}
}
}
So:
If it's just about printing, you don't need to store in an array the numbers, that you get from input.
You don't need sorting, you can just check if the number that you have currently scanned is smaller than 3 (or double 3.0).
The for(numList < 3) is not a correct Java syntax. You probably meant if(number < 3)

This may be due to copy/paste but there where quite some problems, let me show you one solution:
public static void main(String [] args){
double [] numList = new double [6];
Scanner scan = new Scanner(System. in);
// until here everything is fine
for (int i = 0; i<numList.length; i++){ // just a hint: use the array's length. Maybe you want to change the array one day and add 20 numbers to it..
numList[i]=scan.nextDouble(); // you forgot the . and it is called nextDouble() (capital D)
}
Arrays.sort(numList); // sorting is fine, just make sure you sort the whole array (not just one element)
for (int i = 0; i<numList.length; i++){ // here I assume you want to print every element smaller than 3, so you still need to iterate over the whole array (maybe the user inputs only twos
if(numList[i]<3){ // test if the number is smaller than 3
System.out.println(numList[i]); // and print it
}
}
}
if however you want to print only the 3 smallest elements of the array, then your approach was correct (though you still need to write out the whole for conditions:
for(int i=0; i<3;i++){
System.out.println(numList[i]);
}

The last for doesn't work like that. With a for you can iterate trough numbers like you did in the first one or through lists/arrays.
I didn't understood if you wanted the smallest 3 or the ones smaller than 3.
If you want the smallest 3 you can do this:
double smallList[] = new double[3]
for (int i=0;i<3;i++) {
smallList[i] = numList[i];
}
or if you want to print it one by one:
for (int i=0;i<3;i++) {
System.out.println(numList[i]);
}
if you want the ones that are smaller than 3 you'll have to do:
for (int i=0;i<numList.length;i++) {
if (numList[i]<3) {
System.out.println(numList[i]);
}
}

Two ways of printing them out.
double[] numList = new double[6];
Scanner scan = new Scanner(System.in);
for (int i = 0; i < 6; i++) {
numList[i] = scan.nextDouble(); // user input
}
// then do
Arrays.stream(numList).filter(a -> a < 3).forEach(System.out::println);
// or
for (double n : numList) {
if (n < 3) {
System.out.println(n);
}
}

Related

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.

How do I count the number of items an Integer occur in an ArrayList?

My idea is to build a list having the user writing in 5 different ints (doesnt have to be even numbers) and then write a number to see how many time that number occurs in the list. How do I do this? This is my example code im having problems with:
package Listor;
import java.util.ArrayList;
import java.util.Scanner;
public class Tal {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
ArrayList<Integer> evenNumbersList = new ArrayList<>();
System.out.print("Write 5 even numbers: ");
int evenNumber = 0;
for (int i = 0; i < 5; i++) {
evenNumber = s.nextInt();
evenNumbersList.add(evenNumber);
}
System.out.println(evenNumbersList);
System.out.println("Write a number and see how many times it occurs: ");
int intHappens = s.nextInt();
int sum = 0;
for (int i = 1; i < evenNumbersList.size(); i++) {
if (i == intHappens) {
sum += 1;
}
}
System.out.println(sum);
}
}
Two errors I see:
1) Your for loop needs to start from 0, not 1.
2) Your if statement should be if (evenNumbersList.get(i) == intHappens).
You probably want to iterate over the evenNumberList list and compare the values in the list with intHappens. Use a for(Variabletype varname : List list) for-loop. Read up on Enhanced For-Loops

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 do I reverse the integers in one array using another array?

I have gotten 10 values from the user, and I am suppose to put that into an array and call it into a method, and then call another method which contains an array that reverses the integers of the first array without using global variables. For example, the user gives me values 1,2,3, etc.. and I store that in the first array, then in the second array I output 3,2,1.
I have part of the code that gets the integers from the user, but I don't know how to reverse the array without using global variables. The code doesn't run when it gets to the second method at values[i];
Here is what I have so far:
public static void main(String[] args) {
getInput();
reverseInput();
System.exit(0);
}
public static void getInput() {
Scanner keyboard = new Scanner(System.in);
int[] values;
values = new int[10];
//Ask the user to enter 10 integers
System.out.println("Please enter ten numbers.");
for (int i = 0; i<values.length; i++) {//for loop to display the values entered
values[i] = keyboard.nextInt();
System.out.println("Value" + (i +1) + " is " + values[i]);
}
}
public static void reverseInput() {
System.out.println("Now we are going to reverse the numbers.");
Scanner keyboard = new Scanner(System.in);
int [] values;
values = new int[10];
for (int i = (values.length -1); i>= 0; i--) {//for loop to display integers in reversed order
values[i];
System.out.println(values[i]);
}
}
First, if you are not going to be using global variables, then you will need to pass the array from the get input method to the reverseInput method. Something like this:
int[] values = getInput();
reverseInput(values);
Then to output the array in your reverseInput method, it would have to look like this:
public static void reverseInput(int[] values) {
for(int i = (values.length - 1); i >= 0; i--){
System.out.println(values[i]);
}
}
You can use the ArrayUtils.reverse from Commons Lang:
ArrayUtils.reverse(values);
Ok, you understand how to display the elements in reference order. As you wrote:
for (int i = (values.length - 1); i >= 0; i--) {
System.out.println(values[i]);
}
So given that, how would you put the elements of values (say it has 5 elements) in another array (call it reversedValues) such that values[4] was put into reversedValues[0] and so on up to values[0] being put into reversedValues[4]?
use the "getInput" as basis to get the 10 numbers, then after the "for" loop, just do another for loop in reverse
public static void reverseInput()
{
Scanner keyboard = new Scanner(System.in);
int[] values;
values = new int[10];
//Ask the user to enter 10 integers
System.out.println("Please enter ten numbers, we are going to reverse the numbers");
for (int i = 0; i<values.length; i++) //for loop to display the values entered
{
values[i] = keyboard.nextInt();
};
int[] revValues;
revValues = new int[10];
for (int i = (values.length -1); i>= 0; i--) //for loop to display integers in reversed order
{
revValues[ revValues.length -1 -i ] = values[ i ];
System.out.println( revValues[ i ] );
}
}

Categories

Resources