JAVA: Replacing number in array, with the numbers position and print out - java

I have a small problem here. I want to replace all negative numbers in an array with the numbers position. My problem is that the array gets printed out, before the numbers are replaced, and I want to print out the array after it gets replaced...
Here is my code:
public class oppgave33{
public static void main(String[] args) {
int[] heltall = {1, 4, 5, -2, -4, 6, 10, 3, -2};
int counter = 0;
int sumNeg = 0;
while(counter < heltall.length){
//array print out
System.out.println("array[" + counter + "] = " + heltall[counter]);
if(heltall[counter] < 0){
System.out.println(heltall[counter]);
}
//replacing negative numbers
if(heltall[counter] < 0 ){
heltall[counter]=counter;
}
if(heltall[counter] < 0){
sumNeg++;
}
//negative numbers position print out
if(heltall[counter] < 0 ){
System.out.println("Negative numbers position in array is : " + counter);
}
counter++;
}
//printing out how many negative numbers
System.out.println("There are : " + sumNeg + " negative numbers.");
}
}
Final note: if you remove the if setting, where the negative numbers are replaced by their position in array, you will get position to negative numbers printed out, and also how many negative numbers there are.
I hope you can help me! :) Thank you!

You have too many redundant conditions in your code. Your attempt is very close, you can simply do the following:
while (counter < heltall.length) {
// if the number is negative, replace it with its index
if (heltall[counter] < 0) {
heltall[counter] = counter;
}
counter++;
}
// outside the loop
System.out.println(Arrays.toString(heltall));
Important tip: In such cases, you should debug your code. This will help you better understanding the flow of your code, and discover problems that you're not aware of them. I highly recommend you debugging your current code, and only then try to fix it.

Here is the working version of your code:
Note: You must place the printing command after the replacement. Code runs step-by-step and in the line order. The statements at the top rows run first, then the lower rows, (sure in order).
public class oppgave33{
public static void main(String[] args) {
int[] heltall = {1, 4, 5, -2, -4, 6, 10, 3, -2};
int counter = 0;
int sumNeg = 0;
while(counter < heltall.length){
if(heltall[counter] < 0 ){
//replacing negative numbers
heltall[counter]=counter;
//counting negative number amount
sumNeg++;
//array print out after replace
System.out.println("array[" + counter + "] = " + heltall[counter]);
//negative numbers position print out
System.out.println("Negative numbers position in array is : " + counter);
}
counter++;
}
//printing out how many negative numbers
System.out.println("There are : " + sumNeg + " negative numbers.");
}
}

You don't need that much of conditions to replace negative numbers. Just replace one by one when you get a negative number in the loop.
Removing redundancy: One thing to remember: when you have some statements for same condition, you don't need to do them individually. Write all the statements in same if block.
For example, in your code:
if (heltall[counter] < 0) {
System.out.println(heltall[counter]);
}
if (heltall[counter] < 0) {
heltall[counter] = counter;
}
if (heltall[counter] < 0) {
sumNeg++;
}
if (heltall[counter] < 0) {
System.out.println("Negative numbers position in array is : " + counter);
}
Could be replaced by:
if(heltall[counter] < 0) { // do all in the same if condition block
System.out.println(heltall[counter]);
heltall[counter] = counter;
sumNeg++;
System.out.println("Negative numbers position in array is : " + counter);
}
Solution: Anyway, the whole code could look like this:
while (counter < heltall.length) {
// replacing negative numbers
if (heltall[counter] < 0) {
heltall[counter] = counter;
sumNeg++;
}
counter++;
}
System.out.println("There were : " + sumNeg + " negative numbers.");
System.out.println("Array after replacing negative numbers: "+Arrays.toString(heltall));

Related

How to write a code to find the mode of the ints in the array without using a personally created method ie just regular "raw code"

I'm writing a code to find the mean, median and mode of an array of randomly generated ints (user inputs a size for the array and a range between which random numbers are to be generated it generate numbers between 3-22 randomly. I have not had too much trouble writing code for a mean or median but I cannot seem to be able to write code to calculate the mode (most commonly occurring number). Can anyone help or show/put code for how to calculate the mode of a randomly generated array of ints without having to create a method for yourself in the code? Thanks. Here is what I have so far (code that finds the mean and median):
public class ArraysIntsMeanMedianAndMode {
public static void main(String[] args) {
int ArraySize;
int min;
int max;
double x;
// To get the Size and range of numbers for the randomly genereated ints in the array.
Scanner sc = new Scanner(System.in);
System.out.println("What size should the array be?");
ArraySize = sc.nextInt();
System.out.println("Please enter a minimum value for the range of ints.");
min = sc.nextInt();
System.out.println("Please enter a maximum value for the range of ints.");
max = sc.nextInt();
//Making the array and filling it based on the user inputs
int[] MMMarray = new int[ArraySize];
int total = 0;
for (int i = 0; i < ArraySize; i++) {
x = (int) (Math.random() * ((max - min) + 1)) + min;
System.out.println(x);
int RandoNums = (int) x;
total = total + RandoNums;
MMMarray[i] = RandoNums;
}
//Finding mean/average
double Mean = (total + 0.0) / ArraySize;
System.out.println("The mean is: " + Mean);
//Finding Median/Middle number
Arrays.sort(MMMarray);
System.out.println(Arrays.toString(MMMarray));
if (ArraySize % 2 == 0) {
System.out.println("The median is: " + ((MMMarray[(ArraySize / 2)] + 0.0) + MMMarray[(ArraySize / 2) - 1]) / 2 + ".");
} else System.out.println("The median is: " + MMMarray[ArraySize / 2] + ".");
//How to find mode????????
Finding mode of unsorted array of int:
int freq = 0;
int value = 0;
int length = MMMArray.length;
for (int outer = 0; outer < length; outer++)
{
int tempFreq = 0;
for (int inner = 0; inner < length; inner++)
{
if (MMMArray[outer] == MMMArray[inner])
{
tempFreq++;
}
}
if (tempFreq > freq)
{
freq = tempFreq;
value = MMMArray[outer];
}
}
System.out.println("Mode is " + value + ", which appears " + freq + " times.");
Because you have already sorted the array to calculate the median, the problem of finding the mode(s) becomes equivalent to finding the longest consecutive streak of the same number. So, for example, if you have [1, 1, 2, 2, 2, 3, 5, 5, 21], there are three consecutive 2's, which is longer than any other run, so 2 is the mode.
To find the longest run, you can pass over the data once more, not reading any element twice. I'm adapting the code of Litvin and Litvin ever so slightly to use your array name, to count a run of 1 as a run, and to report what number the mode is rather than where it is in the array. You can drop this code in right where you ask your question, after the median has been calculated.
// at this point MMMArray is a sorted, nonempty array of int, because it was already sorted to find the median
int maxRunStart = 0, maxRunLength = 1;
int runStart = 0, runLength = 1;
for (int i = 1; i <= MMMArray.length; i++) //what they do here by using <=
//rather than < is worth reflecting upon
//it handles the case of the biggest run being at the end within the loop body
{
if (i < MMMArray.length && MMMArray[i] == MMMArray[i - 1])//notice how the boolean short-circuit prevents reading beyond the end of the array
{
runLength++;
}
else
{
if (runLength > maxRunLength)
{
maxRunStart = runStart;
maxRunLength = runLength;
}
runStart = i;
runLength = 1;
}
}
System.out.println("The mode is: " + MMMArray[maxRunStart] + ".");
}
Now here is something new to ponder. Suppose MMMArray contains [1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3]. This code (or that of MarsAtomic) will report 1 is the only mode. But the data is bimodal, and 3 is the mode as much as 1 is. One way to adapt the code would be to store the mode(s) in an array list (or an array, because we know up front there cannot be more modes than numbers). I think it is simpler (not more efficient, just easier not to mess up and without introducing another non-simple type) to make one more pass over the data. If you want that, then after the first for loop, instead of the println of the one mode, insert the following:
runLength = 1;
runStart = 0;
for (int i = 1; i <= MMMArray.length; i++)
{
if (i < MMMArray.length && MMMArray[i] == MMMArray[i - 1])
{
runLength++;
}
else
{
if (runLength == maxRunLength)
{
System.out.println("The mode is: " + MMMArray[runStart] + ".");
}
runStart = i;
runLength = 1;
}
}

Counting integers in an array; How to eliminate duplicate output strings

I am writing a program that outputs how many times each integer is found in an array of integers. I have accomplished this, however, i have duplicate output strings.
This is the output:
>run:
>Please enter integers from 0 to 100:
1
2
3
4
4
5
0
// 1 occurs 1 time //
2 occurs 1 time //
3 occurs 1 time //
4 occurs 2 times //
4 occurs 2 times //
5 occurs 1 time //
BUILD SUCCESSFUL (total time: 14 seconds)
So as you can see, "4 occurs 2 times" prints twice since it is found twice in the array.
I just need some direction on how to eliminate the duplicates. Anything would be greatly appreciated.
import java.util.*;
public class WorkSpace3 {
public static void main(String[] args) {
int i = 0;
int count = 0;
int key = 0;
System.out.print("Please enter integers from 0 to 100: ");
int[] myList = new int[100];
Scanner s = new Scanner(System.in);
for (i = 0; i < myList.length; i++)
{
myList[i] = s.nextInt();
if (myList[i] == 0)
break;
}
while (key < myList.length && myList[key] != 0) {
for (i = 0; i < myList.length; i++)
{
{ if (myList[i] == myList[key])
{ count++; } }
}
if (count == 1)
System.out.println(myList[key] + " occurs " + count + " time ");
if (count > 1)
System.out.println(myList[key] + " occurs " + count + " times ");
key++;
count = 0;
}
}
}
A simple approach that is available to you is to mark the elements that you have counted with zeros. This approach is not universal; it is valid only because you use zero to mark the end of the input sequence by end-user.
You would have to slightly modify your code to use this approach: rather than looking for zero in the while loop, set up a variable to mark the length of the sequence. Set it to myList.length at the beginning, and then reset to i at the break. Now you can walk the list up to this max count, do the counting, and then set zeros into elements that you have already counted.
See the set element:
https://docs.oracle.com/javase/7/docs/api/java/util/Set.html
Making a set element from array You remove the duplicates.
try this using Map
Map<Integer,Integer> counts=new HashMap<Integer,Integer>();
for (i = 0; i < myList.length; i++) {
if(counts.contains(myList[i]){
counts.put(myList[i],++counts.get(myList[i]);
}else{
counts.put(myList[i],1);
}

Loop Counting in Java

What I have is a program that prints out 4000+ random digits in the range of 1 to 99999. After printing, it shows the range, and a couple of other things, and then asks user for 5 numbers to be input and tells how many times it had to run the loop, but I'm getting an exception in main upon print, it's coming from the main for loop. Screenshot is attached. Desired should look something like:
(Randomly generated numbers):
25
192
33
(User Enters) Please enter number: 33
(System Response) It took 3 times to find the number.
If the number is not listed, as it is over 4000 integers, it will say, not found.
Here is code and screenshot:
Screenshot
Exception in Main java.lang.ArrayIndexOutOfBoundsException:0
Thank You!
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int[] input = new int[0];
int[] arrayone = new int[4096];
int loop = 0;
for(int i = 0; i < arrayone.length; i++) {
arrayone[i] = (int)(Math.random() * 99999 + 1);
for(int in = 0; in<input.length; in++) {
if (arrayone[i] == input[in]) {
loop++;
}
}
}
for (int i = 0; i < 5; i++) {
System.out.println("Please enter a number between " + min + " and " + max);
input[0] = s.nextInt();
if (min <= input[0] && input[0] <= max) {
System.out.println("It took " + loop + " time(s) to find the number " + input);
}
}
}
The problem with your input array is that you initialize it with a size of 0, so when you try to access the first location [0], you run out of the bounds since your array has a size of 0. In your answer you were also trying to determine the loops before asking the question. While doing this you were also trying go past the bounds of your input array with a size 0. What you should do is initialize your array of numbers first then for each guess loop through and determine if it's within the bounds of your max and min. Also note that just because the numbers are within the max and min doesn't guarantee the number is contained in the array because the numbers are not going to be sequential from max to min. You should check where you end up after your for-loop check for the input.
public static void main(String random[])
{
Scanner s = new Scanner(System.in);
int input = new int[5];
int[] arrayone = new int[4096];
int loop = 0;
//don't do anything here except fill the array with values
for(int i = 0; i < arrayone.length; i++) {
arrayone[i] = (int)(Math.random() * 99999 + 1);
}
//ask the user for 5 inputs
for (int index = 0; index < input.length; index++) {
System.out.println("Please enter a number between " + min + " and " + max);
input[index] = s.nextInt();
//check to see if the number is valid
if (min <= input[index] && input[index] <= max) {
//loop through the arrayone to determine where it is
for(int i = 0; i < arrayone.length; i++) {
//if it is not in the current index at i increment the loop count
if (arrayone[i] != input[index]) {
loop++;
}
//we have found where it is and should break out of the loop
else {
break;
}
}
//check if we found it based on how much we incremented
if(i != arrayone.length)
{
//output how long it took to find the number
System.out.println("It took " + loop + " time(s) to find the number " + input[index]);
}
else
{
System.out.println(input[index] + " not found!");
}
//now reinitialize the loop to 0 for the next guess
loop = 0;
}
}
//always remember to close your scanners
s.close();
}
}
int[] input = new int[0];
This creates an array with size of 0, so when you try save value it throws an exception because you are exceeding array size.
Solution: set valid size of array or use list.
The ArrayList is (simplifying) resizeable version of array. Use it like this:
List<Integer> input = new ArrayList<>();
input.add(5); //Adds 5 to list
input.get(0); //Read object of index 0
for(int value : list) { //Loop: for each element in list ...
System.out.println(value);
}
//Checks whether list contains 5
System.out.println(list.contains(5));
Also, do you actually need input to be an array? Because right now it looks like you don't need it at all.

Finding how many times an item Appears in an Array

Given an array of integers ranging from 1 to 60, i'm attempting to find how many times the numbers 1-44 appear in the array. Here is my method
public static void mostPopular(int[] list, int count)
{
int[] numbers;
numbers = new int[44];
for (int i = 0; i<count;i++)
{
if (list[i]<45 )
{
numbers[i-1]=numbers[i-1]+1; //error here
}
}
for (int k=0; k<44;k++)
{
System.out.println("Number " + k + " occurs " + numbers[k-1]+ "times");
}
}
I'm trying to iterate through the array, list, that contains over 5000 numbers that are between 1-60, then test if that number is less than 45 making it a number of interest to me, then if the integer is 7 for example it would increment numbers[6] By 1. list is the array of numbers and count is how many total numbers there are in the array. I keep getting an ArrayIndexOutOfBoundsException. How do I go about fixing this?
Replace this line numbers[i-1]=numbers[i-1]+1;
with numbers[list[i] - 1] = numbers[list[i] - 1] + 1;
Now it will update the count of correct element.
You need to increment numbers[list[i]] because that's your value which is smaller than 45. i goes up to 5000 and your array numbers is too small.
You should really start using a debugger. All the modern IDE have support for it (Eclipse, IntelliJ, Netbeans, etc.). With the debugger you would have realized the mistake very quickly.
If your initial value is less than 45, it will add 1 to numbers[i-1]. However, since you start with i=0, it will try to add 1 to the value located at numbers[-1], which doesn't exist by law of arrays. Change i to start at 1 and you should be okay.
Very close, but a few indexing errors, remember 0-1 = -1, which isn't an available index. Also, this isn't c, so you can call list.length to get the size of the list.
Try this (you can ignore the stuff outside of the mostPopular method):
class Tester{
public static void main(String args[]){
int[] list = new int[1000];
Random random = new Random();
for(int i=0; i<list.length; i++){
list[i] = random.nextInt(60) + 1;
}
mostPopular(list);
}
public static void mostPopular(int[] list)
{
int[] numbers = new int[44];
for (int i = 0; i< list.length ;i++)
{
int currentInt = list[i];
if(currentInt<45 )
{
numbers[currentInt - 1] = (numbers[currentInt -1] + 1);
}
}
for (int k=0; k<numbers.length; k++)
{
System.out.println("Number " + (k+1) + " occurs " + numbers[k]+ "times");
}
}
}
When i is 0, i-1 is -1 -- an invalid index. I think that you want the value from list to be index into numbers. Additionally, valid indices run from 0 through 43 for an array of length 44. Try an array of length 45, so you have valid indices 0 through 44.
numbers = new int[45];
and
if (list[i] < 45)
{
// Use the value of `list` as an index into `numbers`.
numbers[list[i]] = numbers[list[i]] + 1;
}
numbers[i-1]=numbers[i-1]+1; //error here
change to
numbers[list[i]-1] += 1;
as list[i]-1 because your number[0] store the frequency of 1 and so on.
we increase the corresponding array element with index equal to the list value minus 1
public static void mostPopular(int[] list, int count)
{
int[] numbers = new int[44];
for (int i = 0; i<count;i++)
{
//in case your list value has value less than 1
if ( (list[i]<45) && (list[i]>0) )
{
//resolve error
numbers[list[i]-1] += 1;
}
}
//k should start from 1 but not 0 because we don't have index of -1
//k < 44 change to k <= 44 because now our index is 0 to 43 with [k-1]
for (int k=1; k <= 44;k++)
{
System.out.println("Number " + k + " occurs " + numbers[k-1]+ "times");
}
}

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1000000 at problem2.main(problem2.java:17)

I get the following error and I don't know why. I tried looking it up, but I didn't find a solution.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1000000 at problem2.main(problem2.java:17)
Here is my code:
//Each new term in the Fibonacci sequence is generated by adding the previous two terms.
//By starting with 1 and 2, the first 10 terms will be:
//1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
//By considering the terms in the Fibonacci sequence whose values do not exceed four million,
//find the sum of the even-valued terms.
public class problem2 {
public static void main(String[] args) {
int []a = new int[1000000];
a[0] = 1;
a[1] = 2;
int sum=0;
int i=2;
while(a[i]<=4000000){
a[i] = a[i-1] + a[i-2];
i++;
}
for(int j=0;j<i;j++){
sum = sum + a[j];
}
System.out.println("The sum is: " + sum);
System.out.println("\nThere are " + i + " numbers in the sequence.\n");
System.out.println("This are all the numbers in the sequence:");
for(int j=0;j<i;j++){
if(j+1==i){
System.out.print(a[j] + ".");
break;
}
System.out.print(a[j] + ", ");
}
}
}
The problem is not the size of the int[].
Your while loop is constantly checking if a[i] is less than 4000000 while the i variable is already one index ahead. Each loop will have a[i] == 0.
This change will fix the code for you:
int i=1;
while(a[i]<=4000000){
i++;
a[i] = a[i-1] + a[i-2];
}
This error is caused by the fact that i reaches 1000000 (the size of your array) before a[i] reaches the termination condition of your loop. Instead of testing the value of a[i] you should use a for loop like this:
for (i=2; i<a.length; i++){
a[i] = a[i-1] + a[i-2];
}
In addition, you should use the type long rather than int for the items of a because the values are getting so large that they overflow the int type and wrap around to negative values, eg:
1872856136
1063031469
-1359079691
-296048222
-1655127913
-1951176135
688663248
Edit: in fact, using an array with 1000000 elements even a long won't be big enough - if you really need values this big you would have to use BigInteger
Your array a contains 1,000,000 elements, starting from zero. When you loop through them here:
while(a[i]<=4000000)
you're exceeding the index capacity. The first index to exceed the capacity is 1,000,000, hence the error.
In your while loop, you increment i before checking if you're done. Whenever that condition gets evaluated, it gets evaluated on the element you're about to calculate - but there's nothing there yet.
This means your while loop never terminates - and eventually, i becomes 1,000,000, at which point a[i] can no longer be evaluated, causing this exception to be thrown - because the last element in a is a[999999].
You can fix this in a couple of ways; the clearest would be to start i at 1, and increment it before assigning to a[i].
As an aside, fixed-size arrays are generally a bad choice, and variable-sized lists like ArrayList<E> is a better choice - although in this particular case, that would eventually just lead to an OutOfMemoryException instead, due to the logic bug.
Add an extra condition
while(i < a.length && a[i]<=4000000)
Problem is at while loop,look into the condition
while(a[i]<=4000000)
As others have pointed out . You can do like this :
int i=2;
for(;i<a.length && a[i]<=4000000;i++)
{
a[i] = a[i-1] + a[i-2];
}
It checks that the value is less than 400000 and the index should be less than 100000.
The problem is here
while(a[i]<=4000000)
In your case you can do as
while(i < a.length && a[i]<=4000000 ){
a[i] = a[i-1] + a[i-2];
i++;
}
And your program will work perfectly..
import java.util.Scanner;
public class FibonacciSequence {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a = new int[40000000];
Scanner b = new Scanner(System.in);
System.out.println("Enter Two Numbers From Which You Want To Start Fibonacci Sequence.");
a[0] = b.nextInt();
a[1] = b.nextInt();
for(int i = 2; i <= 10; i++) {
a[i] = (a[i-2] + a[i-1]);
}
System.out.println("The fibonacci Sequence is: ");
int sum = 0;
for(int j = 0; j <= 10; j++) {
System.out.println(a[j] + ", ");
sum += a[j];
}
System.out.println("The Sum of the fibonacci sequence: " + sum);
}
}

Categories

Resources