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 ");
}
}
Related
i am writing a java program, i want the user to enter 5 numbers within the range 10 and 100 if the user enters any number less than 10 or greater than 100, or a repeated number, it should ask me for a number to replace it with, but my program just puts a zero (0).so if i put any repeated number my program just stores it in the array as zero, i want it to ask me what number i want to replace it with then store the new number.
here's a segment of my code:
while (wahala < thearray.length)
{
System.out.print("Enter the number you want: ");
for (int w=0; w<5; w++)
{
value=input.nextInt();
if (value>=10 && value<=100)
{
boolean containsNumber = false;
wahala++;
for(int j=0; j<thearray.length; j++)
{
if (array[j]==value)
{
containsNumber=true;
break;
}
}
if (!containsNumber)
{
array[w]=value;
count++;
}
else
System.out.printf("%d has already been entered\n", value);
}
else
System.out.println("Number must be between 10 and 100");
}
for (int element: array)
{
System.out.println(element +"");
}
}
Nowhere in your sample code do you prompt the user for a new number.
Also, if the array has to avoid duplicates, consider using a Set instead, so that you can quickly check if a duplicate has been entered.
Ex (Java 10):
private final int maxValues = 5;
private int input;
var intSet = new HashSet<Integer>();
while(intSet.size() < 5 && askedAndReceivedInput())
if(intSet.contains(..some input))
//ask again
else
intSet.put(someInput);
You can make the input-reading function however you wish..
Also please note that you're finding zeroes in your array because that's what java fills it with upon creation. It's the default value, this is guaranteed by the language spec.
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
So I've been tasked with creating a code that creates a predetermined array list for users to input up to over 100 integers with the option of using 0 to signify once their done with their inputs. However, when trying to call for say the minimum value, it just returns a value of 0. How would I properly format it so it compares it to all the value in the user inputted array list? Appreciate any help I can get! I added comments on the side to show which areas I have questions about or where I believe that the error lies.
public static void main(String[] args) {
Scanner TextIO = new Scanner(System.in);
String calc;
double[] numbers2; //An array for storing double values.
int[] numbers; // An array for storing the int values.
int count; // The number of numbers saved in the array.
int num; // One of the numbers input by the user.
int max;
int min;
/* Initialize the summation and counting variables. */
numbers2 = new double[100]; // Space for 100 doubles.
numbers = new int[100]; // Space for 100 ints.
count = 0; // No numbers have been saved
max = Integer.MIN_VALUE; //Properly initialized?
min = Integer.MAX_VALUE; //Properly initialized?
/*Start of min method. */
if (calc.equals("min")){
System.out.println("Enter up to 100 positive integers;
while (true) { // Get the numbers and put them in the array.
System.out.print("-> ");
num = TextIO.nextInt();
if (num <= 0) {
break; } /*Zero marks the end of the input. All
have been inputted. */
else {
numbers[count] = num; // Put num in position count.
count++;
}
for (int i=0; i<numbers.length;i++) { //"For" statement needed here?
if (numbers[i] < min) {
min = numbers[i];}
}
}
System.out.println("Your minimum is : " + min);
}
}
}
Your for loop that finds the minimum should be after the while loop that reads the input, not inside it (since currently it goes over un-initialized elements of the array, so it always finds a 0 as the minimum). If you do that, you should also change the for loop to only iterate over the elements you assigned to the array (indices 0 to count-1), and not the entire array.
Alternately, you can remove the for loop and just put the
if (numbers[count-1] < min) {
min = numbers[count-1];
}
condition inside the while loop.
This will find the minimum in the same loop that reads the input.
Of course, if you do that, you don't need to store the elements in an array at all, so you can further simplify the code.
Here's a possible solution the keeps the array and the for loop :
while (count < numbers.length) { // avoid too many inputs
System.out.print("-> ");
num = TextIO.nextInt();
if (num <= 0) {
break;
} else {
numbers[count] = num;
count++;
}
}
for (int i=0; i<count;i++) {
if (numbers[i] < min) {
min = numbers[i];
}
}
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.
This question already has answers here:
Maximum number that can be formed from the given digits
(2 answers)
Closed 7 years ago.
I have a number which I need to re-arrange to find the largest number. As an example input number is 355 so for this number I need to find the largest number which can be formed by re-arranging the digits. So for 355, various combination can be possible after re-arranging -
355, 535 and 553
So here 553 is the largest number and that's what I need to return. Basically given an input, I need to find the largest number which can be formed by re-arranging the numbers.
How should I go ahead and solve this problem?
So far I am able to do shuffle the numbers like this:
public static void main(String[] args) {
//generate random number
int number = 355;
//put each digit in an element of a list
List<Character> numberList = new ArrayList<Character>();
for (char c : String.valueOf(number).toCharArray()) {
numberList.add(c);
}
//shuffle
Collections.shuffle(numberList);
//output
String shuffledNumber = "";
for (Character c : numberList) {
shuffledNumber += c;
}
System.out.println(shuffledNumber);
}
But I am confuse how can I find the largest number given an input after rearranging the numbers.
If you need to rearrange the numbers so that, if we read it from left to write, it should be largest number among all the arrangements,
then it's simple, you just need to sort the number in descending order.
Try this code :
public static void main(String args[]) {
//generate random number
int number = 355;
String numStr = number + "";
char[] numCharArr = numStr.toCharArray();
int[] numArr = new int[numStr.length()];
for(int i = 0 ; i < numCharArr.length ; i ++) {
numArr[i] = Integer.parseInt(numCharArr[i] + "");
}
// Sort in descending order
for(int i = 0 ; i < numArr.length ; i ++) {
for(int j = 0 ; j < i ; j ++) {
if(numArr[i] > numArr[j]) {
// swap
int temp = numArr[i];
numArr[i] = numArr[j];
numArr[j] = temp;
}
}
}
String largestNumber = "";
for(int i : numArr) {
largestNumber += i;
}
System.out.println("The largest number is : " + largestNumber);
}
Unless you actually need to create all the combinations, I wouldn't bother.
You can actually do it using arithmetic, but in this case it's probably easier in terms of strings
naive algorithm:
source number = number.toString()
target number = ""
While source number is not empty
d = remove biggest number from source number
target number += d
You can then convert target number back to an int if required.
Another approach would be count the number of 9s and append that many 9s to the result. Repeat for 8s, then 7s, then 6s...