Im very new to Java, and I'm trying to write a program using arrays and arraylists where you enter in however many values you want, and it outputs how many values are between two parameters using asterisks.
ex:
[5,14,23,43,54,15]
1-10: *
11-20: **
21-30:*
31-40:
41-50:*
51-60: *
And so on. Here's what I have so far, but I'm getting errors and out of bounds exceptions. Can anyone say whether or not I'm on the right track or not? Any help is appreciated!
package arraylists;
import java.util.ArrayList;
import java.util.Scanner;
public class numberslists {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner reader = new Scanner(System.in);
ArrayList numbers = new ArrayList();
int [] number = new int[10];
int x, count = 0;
System.out.println("how many numbers would you like?");
count = reader.nextInt();
System.out.println("enter in those numbers please");
for (x=0; x < count; x++){
number[x] = reader.nextInt();
numbers.add(number[x]);
}
System.out.println(numbers);
int x10 = numbers.indexOf(number[x] < 10);
numbers.remove(x10);
System.out.println(numbers);
}
}
In short, as Lahiru said, you need to change the line: int x10 = numbers.indexOf(number[x] < 10);
The main problem with your code is the expression number[x] < 10 which returns a boolean (true or false). Therefore the numbers.indexOf(number[x] < 10) is going to return 1 or -1.
Finally, when the code gets to numbers.remove(x10); and if is -1 (for false) then you will get java.lang.ArrayIndexOutOfBoundsException because there is no way to do a numbers.remove(-1);. See the documentation.
There is room for improvement in your code. Below is a suggestion to what you could do. But just look at this suggestion after you try fixing your own code (so you can have a better learning experience).
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CountOcurrancesInArray {
private static Scanner reader = new Scanner(System.in);
private static List<Integer> numbers = new ArrayList<Integer>(); // Use generics when possible: <Integer>
public static void main(String[] args) {
int x, count = 0;
System.out.println("how many numbers would you like?");
count = reader.nextInt();
System.out.println("enter in those numbers please");
for (x=0; x < count; x++){
// I don't see a need for this line. number[x] = reader.nextInt();
numbers.add(reader.nextInt());
}
System.out.println(numbers);
int[] comparingNumbers = requestComparingNubers();
System.out.println("You entered these numbers: " + numbers);
String matchingNumbers = checkForNumbersInTheList(comparingNumbers);
System.out.println("Numbers between " + comparingNumbers[0] + "-" + comparingNumbers[1] + ":" + matchingNumbers);
}
/**
* Counts how many entries are in the list between 'comparingNumbersInput'
* #param comparingNumbersInput
* #return number of entries as asterisks "*"
*/
private static String checkForNumbersInTheList(int[] comparingNumbersInput) {
String result = "";
for(Integer i : numbers) {
if (i >= comparingNumbersInput[0] && i <= comparingNumbersInput[1]) {
result += "*";
}
}
return result;
}
/**
* Asks the user to enter 2 numbers to be compared against the all the numbers in the list.
* #return returns a int[2] sorted ascendingly
*/
private static int[] requestComparingNubers() {
int [] result = new int[2];
System.out.println("Counting how many numbers there are in between x and y.");
System.out.println("What is the first number?");
result[0]=reader.nextInt();
System.out.println("What is the second number?");
result[1]=reader.nextInt();
// Sort comparingList
if (result[0] > result[1]) {
int temp = result[1];
result[1] = result[0];
result[0] = temp;
}
return result;
}
}
Declare Array after getting count from user.
int x, count = 0;
System.out.println("how many numbers would you like?");
count = reader.nextInt();
int [] number = new int[count];
Also have a look at the Line of code that caused the error.
To me, this makes more sense as a Map, where you store a counter for each range found in the array of inputs. Now that means you have to first figure out what the range if that each input fits within, then update your counter that matches the range. Since we have to calculate the range as a String for output and you want the counter to be represented as a String of asterisk anyway, Storing the range as a String for the Map.key and the counter as a String of asterisk as the Map.value works nicely.
Here is some example code that does just that, where numbers is the ArrayList of the original values input by a user.
//Declare a Map that stores the range as a String ( "01-10") as the key
//and a counter in astericks as the value
Map<String,String> counters = new HashMap<>();
//Loop over the array ov values
for(Integer value: numbers){
//For each value calculate the diviser by diving by 10
Integer lowRange = value / 10;
//To get the low range, multiply the diviser by 10 and add 1
lowRange = (10 * lowRange) + 1;
//The high range is 9 mor ethan the low range
Integer highRange = lowRange + 9;
//Finally calcualte what the range looks like as a String
//Note that it handles "1" as a special case by prepending a "0" to make the value "01"
String rangeString = ((lowRange < 10) ? "0" + lowRange : lowRange) + "-" + highRange;
//Now check the map to see if the rangeString exists as a key, meaning
//we have previously found a value in the same range
String count = "";
if(counters.containsKey(rangeString)){
//If we found the same range, get the previous count
count = counters.get(rangeString);
}
//Place the count back into the map keyed off of the range and add an asterick to the count String
counters.put(rangeString, count + "*");
}
//Finally iterate over all keys in the map, printing the results of the counters for each
for(String range: counters.keySet()){
System.out.println(range + " " + counters.get(range));
}
As an example of output, if the user inputs the values:
[5,14,23,43,54,15,41]
The output would be:
01-10 *
11-20 **
41-50 **
51-60 *
21-30 *
Java arrays are zero-based index. For example, if you declare an array with 10 elements, the index of these elements will be from 0 to 9.
In your code snippet below, when java finishes the "for" loop
for (x=0; x < count; x++){
number[x] = reader.nextInt();
numbers.add(number[x]);
}
The value of x variable will be equal to the number of elements you have inputted to the number array (x = count).
So, when you get the element at x position as below:
int x10 = numbers.indexOf(number[x] < 10);
If x < 10, you will get -1 for x10. Then an exception will occur at:
numbers.remove(x10);
If x >= 10, an ArrayIndexOutOfBoundsException will occur at number[x]
Yet another Homework question
import java.util.ArrayList;
import java.util.Scanner;
import java.util.*;
public class numberlists {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner reader = new Scanner(System.in);
LinkedList < Integer > numbers = new LinkedList < Integer > ();
//int [] number = new int[10]; no need, and the input is variable size
int x, count = 0;
System.out.println("how many numbers would you like?");
count = reader.nextInt();
System.out.println("enter in those numbers please");
Map < Integer, Integer > range_numbers = new HashMap < Integer, Integer > ();
for (x = 0; x < count; x++) {
//number[x] = reader.nextInt(); no need
numbers.add(reader.nextInt());
int rs = ((int) numbers.getLast() / 10) * 10 + 1; //range start for number i.e rs(15)=11
if (!range_numbers.containsKey(rs)) { //check if has number in that range
range_numbers.put(rs, 1);
} else { //gets the prev count, add 1 and stores back for range
range_numbers.put(rs, range_numbers.get(rs) + 1);
}
}
System.out.println(numbers);
Map < Integer, Integer > sortedpairs = new TreeMap < Integer, Integer > (range_numbers); // need to sort
for (Map.Entry < Integer, Integer > pair: sortedpairs.entrySet()) {
System.out.printf("\n%d-%d: %s", pair.getKey(), pair.getKey() + 9,
new String(new char[pair.getValue()]).replace("\0", "*"));
//little trick to repeat any string n times
}
}
}
Enjoy.
Related
Im trying to print out an array but only print out the distinct numbers in that array.
For example: if the array has {5,5,3,6,3,5,2,1}
then it would print {5,3,6,2,1}
each time i do it either i only print the non repeating numbers, in this example {6,2,1} or i print them all. then i didnt it the way the assignment suggested
the assignment wants me to check the array before i place a value into it to see if its there first. If not then add it but if so dont.
now i just keep getting out of bounds error or it just prints everything.
any ideas on what i should do
import java.util.Scanner;
public class DistinctNums {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int value;
int count = 0;
int[] distinct = new int[6];
System.out.println("Enter Six Random Numbers: ");
for (int i = 0; i < 6; i++)
{
value = input.nextInt(); //places users input into a variable
for (int j = 0; i < distinct.length; j++) {
if (value != distinct[j]) //check to see if its in the array by making sure its not equal to anything in the array
{
distinct[count] = value; // if its not equal then place it in array
count++; // increase counter for the array
}
}
}
// Displays the number of distinct numbers and the
// distinct numbers separated by exactly one space
System.out.println("The number of distinct numbers is " + count);
System.out.print("The distinct numbers are");
for (int i = 0; i < distinct.length; i++)
{
System.out.println(distinct[i] + " ");
}
System.out.println("\n");
}
}
Always remember - if you want a single copy of elements then you need to use set.
Set is a collection of distinct objects.
In Java, you have something called HashSet. And if you want the order to be maintained then use LinkedHashSet.
int [] intputArray = {5,5,3,6,3,5,2,1};
LinkedHashSet<Integer> set = new LinkedHashSet<Integer>();
//add all the elements into set
for(int number:intputArray) {
set.add(number);
}
for(int element:set) {
System.out.print(element+" ");
}
You can make this using help array with lenght of 10 if the order is not important.
int [] intputArray = {5,5,3,6,3,5,2,1};
int [] helpArray = new int[10];
for(int i = 0; i < intputArray.length ; i++){
helpArray[intputArray[i]]++;
}
for(int i = 0; i < helpArray.length ; i++){
if(helpArray[i] > 0){
System.out.print(i + " ");
}
}
I'm trying to make it so the random generator doesn't produce the same number in the array. I also don't know how to find the missing number. I tried the if statement, and it works, but it repeats.
The question problem "find the missing number in an array. The array consists of numbers from 1 to 10 in random sequence. One of the numbers in the array is absent and you must find it. Use one loop. An example {5,6,9,4,1,2,8,3,10} – the result will be: 7
import java.util.Random;
public class questionThree
{
public static void main(String[] args)
{
int [] numbers = new int [10];
Random rand = new Random();
int numArr = 1;
for (int i = 1; i < 9; i++)
{
int n = rand.nextInt(10) + 1;
numbers[i] = n;
if (numbers[i] == numArr)
numArr++;
else
System.out.println("The missing num is " +numArr);
}
for(int val : numbers)
{
System.out.println("The next value is " +
val);
}
}
}
Assumption:
Numbers are unique
Only one entry is missing
number ranges from [1, 10] inclusive.
Solution
return 55 - Arrays.stream(yourArr).sum();
This is with O(n) runtime and O(1) space complexity.
If we break assumptions.
You will need O(N) space to figure out which entries are missing. To hold the marker either you can use List or BitSet or 2 bytes and manage it by hand. N is here the random number generation width.
There seems to be no mention on using a temporary data structure.
You can either sort the array and find the missing number, OR use a temporary sorted data structure.
You are conflating two things: the generator algorithm for a problem case and the solution to the problem itself. You shouldn't be interested in how the "random array" is generated at all (unless you want to test your solution). What you certainly shouldn't do is try to write the code that solves the problem in the method that generates the sample array.
If you want a randomly sorted list, Collections.shuffle will handle that for you. If you want a list without a single element, just generate a list of all elements 1..n and then remove the randomly selected number (then shuffle). So much for the generator. As for the solution, there are many methods to do it, someone already suggested using the sum, that's a perfectly valid solution.
It seems you are looking for this code.
import java.util.Random;
public class questionThree
{
public static void main(String[] args)
{
int [] numbers = new int [9];
Random rand = new Random();
int numArr = 1;
numbers[0] = rand.nextInt(10) + 1;
for (int i = 1; i < 9; i++)
{
int n = rand.nextInt(10) + 1;
numbers[i] = n;
int x =0;
while(x<i){
if(numbers[x] == n){
i = i-1;
break;
}
x++;
}
}
int sum = 0;
for (int val : numbers) {
sum = sum + val;
System.out.println("The next value is " +
val);
}
System.out.println("Missing number is " + (55 - sum));
}
}
Output is -
The next value is 6
The next value is 2
The next value is 8
The next value is 1
The next value is 4
The next value is 3
The next value is 9
The next value is 10
The next value is 7
Missing number is 5
I am generating 9 Numbers between(1 to 10) randomly and then printing which number is missing among them.
You have two options:
The way I did it in the code below: setting the random array without repeating the same number. And then a for loop from 1 to 10 and check if that number exist in the array.
You know that 1 + 2 + 3 + 2 + 3 + 4 + 5 + 6 + 8 + 9 + 10 = 55. So if you get the sum of all ints in the array you will have 55 - (the missing number). So now the missing number = 55 - sum.
This is the code I did (first method):
import java.util.Random;
public class questionThree
{
public static void main(String[] args)
{
int [] numbers = new int [9];
Random rand = new Random();
for (int i = 0; i <9; i++)
{
//setting random numbers in array without repeating
numbers[i] = checkForANumber(rand, numbers, i);
}
//print all nums
for(int val: numbers) System.out.println("The next value is " +
val);
for (int i = 1; i <= 10; i++)
{
boolean exist = false;
for(int val : numbers)
{
if(val == i){
exist = true;
}
}
if (!exist) System.out.println("The missing number is " + i);
}
}
private static int checkForANumber(Random rand, int[] numbers, int i){
int n = rand.nextInt(10) + 1;
boolean NumAlreadyExist = false;
for(int j = 0; j < i; j++)
{
if(numbers[j] == n){
NumAlreadyExist = true;
}
}
if(NumAlreadyExist) return checkForANumber(rand, numbers, i);
else return n;
}
}
Output:
The next value is 9
The next value is 3
The next value is 8
The next value is 6
The next value is 7
The next value is 10
The next value is 4
The next value is 2
The next value is 1
The missing number is 5
I'm supposed to write a program using for loops that print out the even indexes of my array. For example, if I create an array that has 10 numbers, it will have indexes from 0-9 so in that case I would print out the numbers at index 2, 4, 6 and 8. This is what I wrote so far but it doesn't work. Please note that I am not trying to print out the even numbers of the array. All I want are the even indexes.
Example I enter the following array: 3,7,5,5,5,7,7,9,9,3
Program output:
5 // (the number at index 2)
5 // (the number at index 4)
7 // (the number at index 6)
9 // (the number at index 8)
My Code:
public class Arrayevenindex
{
public static void main(String[] args)
{
int number; // variable that will represent how many elements the user wants the array to have
Scanner key = new Scanner(System.in);
System.out.println(" How many elements would you like your array to have");
number = key.nextInt();
int [] array = new int [number];
// let the user enter the values of the array.
for (int index = 0; index < number; index ++)
{
System.out.print(" Value" + (index+1) + " :");
array[index] = key.nextInt();
}
// Print out the even indexes
System.out.println("/nI am now going to print out the even indexes");
for (int index = 0; index < array.length; index ++)
{
if (array[number+1]%2==0)
System.out.print(array[number]);
}
}
}
You can just change your for loop and get rid of the inner IF...
for( int index = 0; index < array.length; index += 2) {
System.out.println(array[index]);
}
Just absolutely same thing using java 8 Stream API
Integer[] ints = {0,1,2,3,4,5,6,7,8,9};
IntStream.range(0, ints.length).filter(i -> i % 2 == 0).forEach(i -> System.out.println(ints[i]));
I assume this would be sufficient
// For loop to search array
for (int i = 0; i < array.length; i++) {
// If to validate that the index is divisible by 2
if (i % 2 == 0) {
System.out.print(array[i]);
}
}
This is what I did and it works:also I am not printing out index[0] because technically its not even thats why I started the for loop at 2. Your post did help me a lot. I also thank everyone else as well that took the time to post an answer.
import java.util.Scanner;
public class Arrayevenindex
{
public static void main(String[] args)
{
int number; // variable that will represent how many elements the user wants the array to have
Scanner key = new Scanner(System.in);
System.out.println(" How many elements would you like your array to have");
number = key.nextInt();
int [] array = new int [number];
// let the user enter the values of the array.
for ( int index = 0; index < number; index ++)
{
System.out.print(" Value" + (index+1) + " :");
array[index] = key.nextInt();
}
// Print out the even indexes
System.out.println("/nI am now going to print out the even indexes");
for ( int index = 2; index < array.length; index +=2)
{
System.out.print(array[index] + " ");
}
}
}
Write a full Java program that does the following:
Creates an array of 100 double.
Reads in an unknown number of doubles from a file named values.txt .
There will be at least 2 distinct values, and no more than 100 distinct values in the file. The values will be in unsorted order. Values will be no smaller than 0, and no larger than 99.
Outputs the most frequently occurring value in the file.
Outputs the least frequently occurring value in the file. The value must occur at least once in order to be output.
Outputs the average of all array values.
You must create and use separate methods for each of the items #2-5.
This is what I have so far. I cannot for the life of me figure out how to get this right:
import java.util.*;
import java.io.*;
public class arrayProgram2 {
static Scanner console = new Scanner(System.in);
static final int ARRAY_SIZE = 100;
static int numOfElements = 0;
public static void main(String[] args) throws FileNotFoundException {
Scanner inFile = new Scanner(new FileReader("values.txt"));
double[] Arr1 = new double[ARRAY_SIZE];
while (inFile.hasNext()) {
Arr1[numOfElements] = inFile.nextDouble();
numOfElements++;
}
System.out.println("There are " + numOfElements + " values.");
System.out.printf("The average of the values is %.2f%n", avgArray(Arr1));
System.out.println("The sum is " + sumArray(Arr1));
inFile.close();
} //end main
//Method to calculate the sum
public static double sumArray(double[] list) {
double sum = 0;
for (int index = 0; index < numOfElements; index++) {
sum = sum + list[index];
}
return sum;
}
//Method to calculate the average
public static double avgArray(double[] list) {
double sum = 0;
double average = 0;
for (int index = 0; index < numOfElements; index++) {
sum = sum + list[index];
}
average = sum / numOfElements;
return average;
}
} //end program
Notice I am required to make an array of double even though it is not necessary.
If all values are int than you should use int array instead of double. As all values in range 0-99. So, you can increase input value frequency. Look at below logic:
int[] freqArr= new int[100];
while (inFile.hasNext()){
int value = inFile.nextInt();
freqArr[value]++; // count the frequency of selected value.
}
Now calculate the maximum frequency from freqArr
int maxFreq=0;
for(int freq : freqArr){
if(maxFreq < freq){
maxFreq = freq;
}
}
Note: If double array is mandatory than you can also use double array like:
double[] freqArr= new double[100];
while (inFile.hasNext()){
freqArr[(int)inFile.nextDouble()]++;
}
It's possible to find a most-occurring value without sorting like this:
static int countOccurrences(double[] list, double targetValue) {
int count = 0;
for (int i = 0; i < list.length; i++) {
if (list[i] == targetValue)
count++;
}
}
static double getMostFrequentValue(double[] list) {
int mostFrequentCount = 0;
double mostFrequentValue = 0;
for (int i = 0; i < list.length; i++) {
double value = list[i];
int count = countOccurrences(list, value);
if (count > mostFrequentCount) {
mostFrequentCount = count;
mostFrequentValue = value;
}
}
return mostFrequentValue;
}
Pham Thung is right : -
You read in integer inFile.nextInt(), why do you need to use double array to store them? – Pham Thung
You can achieve your first functionality in n time if its integer array.
you question says,
Values will be no smaller than 0, and no larger than 99.
So,
1. Make an array of size 100.(Counter[])
2. Iterate through values of your current array and add count to Counter array.
eg:
if double array contains
2 3 2 5 0 0 0
Our counter array will be like
location : 0 1 2 3 4 5 6 ...........100
values : 3 0 1 1 0 1 0 ..............
and so on.
You can use below algorithm for this
Sort the array (you only need to read unsorted array, but you can sort the array once read from the file)
Make double var : num, mostCommon, count = 0, currentCount = 1
Assign Arr1[0] to num
for i from 1 to length of Arr1
i. if(Arr1[i] == num)
a. Increment currentCount
ii. else
a. if(count > currentCount)
A. Assign currentCount to count
B. Assign num to mostCommon
C. Assign Arr1[i] to num
D. Assign 1 to currentCount
At the end of this loop, you will have most common number in mostCommon var and it's number of occurrence in count.
Note : I don't know how to format the algo
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I'm trying to initialize an array with 50 integer values and compute the frequency of numbers in the range of 10 .. 19. I think the problem is with the bottom part of the code.
import java.util.Scanner;
public class Ex1partA {
public static void main(String[] args) {
Scanner kbin = new Scanner(System.in);
int list[]=new int[50];
int i=0;
System.out.print("\n\tInput numbers from 10 to 19: \n");
while (i < 50) {
int value = kbin.nextInt();
if (value >= 10 & value <= 19) {
list[i] = value;
i++;
} else {
System.out.println("!! Bad number !!");
}
}
for (int value : list) {
System.out.println("" + value);
}
}
}
I'm trying to initialize an array with 50 integer values and compute
the frequency of numbers in the range of 10 .. 19.
To calculate frequency, it is better to put all numbers into List and count frequency using Collections.frequency
List<Integer> freqList=new ArrayList<Integer>();
// Add numebers to this list.
for (int i = 10; i <20; i++) {
int freq=Collections.frequency(freqList, i);
// This will return frequency of number
System.out.println(i+" "+freq);
}
You're suffering from some design issues. Specifically, you're conflating the task of getting your numbers with the task of counting frequency.
import java.util.Scanner;
public class Ex1partA {
public static void main(String[] args) {
Scanner kbin = new Scanner(System.in);
//Get all inputs
List<Integer> inputs = getInputs(10,19);
//Count the frequency
Map<Integer, Integer> freq = countFrequency(inputs);
for (int key : freq.keySet()) {
System.out.println(key + ": " + freq.get(key));
}
}
public static List<Integer> getInputs(int min, int max) {
List<Integer> list = new ArrayList<Integer>();
System.out.print("\n\tInput numbers from 10 to 19: \n");
int i=0;
while (i < 50) {
Integer newNumber = kbin.nextInt();
if (newNumber < max && newNumber > min) {
list.add(newNumber);
} else {
System.out.println("Bad number. Ignoring.");//Note this simply skips, does not ask for re-entry of bad numbers
}
i++;
}
return list;
}
// Finds the frequency of the input list and out puts it as
// a map of number => how many times that number appears
public static Map<Integer, Integer> countFrequency(List<Integer> input) {
Map<Integer,Integer> freq = new HashMap<Integer,Integer>();
for (Integer val : input) {
Integer currentCount = freq.get(val);
freq.put(val, currentCount + 1);
}
return freq;
}
}
Lets note a few key points:
Each function should do exactly ONE thing, if at all possible. So here we have a function that gets all the inputs (within a certain range) and another that counts the frequency of a list of numbers.
Using full objects rather than primitive arrays gives you a lot of flexibility and power without overhead of you having to manually massage data.
In particular, the concept of a Map is important here. You are 'mapping' a key (which in this case is the input value provided by the user of a number between 10 and 19) with a value (which in this case is the number of times that number appears in the list of numbers you have).
&& rather than & to apply the boolean AND to two other boolean operators.
Note that the Collections API provides frequency-counting methods that would allow you to avoid doing the mapping yourself.
You do not need an array of size 50. For your problem since you know numbers will be in the range [10,19], create an array of size 20. Using arrays you can implement something like this
Scanner kbin = new Scanner(System.in);
int i = 0;
int arr[] = new int[20];
// fill the array with -1, it will be used for counting
// can be done using a for loop as well
Arrays.fill(arr, -1);
System.out.print("\n\tInput numbers from 10 to 19: \n");
while (i < 50)
{
int value = kbin.nextInt();
// check the value is in the specified range
if (value >= 10 && value <= 19) {
// treat the array index as your repeated number
// if the number occurs again, just increment it by 1
arr[value] = arr[value] + 1;
// move to next input
i++;
} else {
System.out.println("!! Bad number !!");
}
}
//start with index 10 as we know the range
for (int j = 10; j < 20; j++) {
// check if value stored is greater than -1
// if it is greater than -1 then we have a number in the specified
// range
if (arr[j] > -1) {
// need to add +1 because the array was initially filled with -1
System.out.println(j + " Occurs " + (arr[j] + 1) + " times ");
}
}