So my code is having a problem. Here's what I want to do: have one array have the original set of numbers (up to 10 numbers) and then copy and paste those numbers onto the second array. And then afterwards, the second area lists those numbers from the first array numerically (going from the lowest number to the highest).
The problem is... my second output is giving me a good output with the lowest numbers going to the highest numbers, however, at the same time, I'm getting a long list of repeated numbers and a ton of zeros if I stop my code with the -9000 input. Can anyone tell me what the problem is and how to fix it? I don't want to sort this second array with the Array.sort() option, by the way. No importing anything but the scanner:
public static void main(String[] args) {
System.out.println("Input up to '10' numbers for current array: ");
int[] array1 = new int[10];
int i;
Scanner scan = new Scanner(System.in);
for (i = 0; i < 10; i++) {
System.out.println("Input a number for " + (i + 1) + ": ");
int input = scan.nextInt();
if (input == -9000) {
break;
} else {
array1[i] = input;
}
}
System.out.println("\n" + "Original Array: ");
for (int j = 0; j < i; j++) {
System.out.println((j + 1) + ": " + array1[j]);
}
System.out.println("\n" + "Organized Array: ");
int[] array2 = new int[i];
for (i = 0; i < array1[i]; i++) {
System.out.println(+array1[i]);
for (int j = 0; j < i; j++) {
int temp;
boolean numerical = false;
while (numerical == false) {
numerical = true;
for (i = 0; i < array1.length - 1; i++) {
if (array2[i] > array2[i + 1]) {
temp = array2[i + 1];
array2[i + 1] = array2[i];
array2[i] = temp;
numerical = false;
}
}
}
}
for (i = 0; i < array2.length; i++) {
System.out.println(array2[i]);
}
}
}
You have several issues that you need to fix to make your program run:
You have forgotten to copy array1 into array2:
The output that you think is coming from sorting array2 is actually from the process of sorting.
int[] array2 = new int[i];
for (int j = 0; j < i; j++) {
array2[j] = array1[j];
}
You placed the output of sorted array inside the loop that does sorting:
Check the level of curly braces, and move the output loop to after the sorting loop
for (i = 0; i < array2.length; i++) {
System.out.println(array2[i]);
}
Your sorting algorithm has an extra loop:
Having the outermost loop makes no sense: your bubblesort algorithm works perfectly without it, so you should remove the loop, and move its body up by one level of nesting:
for (i = 0; i < array1[i]; i++) { // Remove the loop
... // <<== Keep the body
}
Your innermost loop reuses i incorrectly:
Replace loop variable i with another variable, e.g. m
for (int m = 0 ; m < array2.length - 1; m++) {
if (array2[m] > array2[m + 1]) {
temp = array2[m + 1];
array2[m + 1] = array2[m];
array2[m] = temp;
numerical = false;
}
}
Demo.
in your for loop you set i limit to array1[i] value not to array lenght, surely it is wrong.
you are reusing the same index i, inside the other loops of the outer big 'for' loop, so the i value will be messed up by inner loops
you never copied the array1 values to array2
Related
I'm trying to add all the elements together in an array that was decided through user input, Every time I run the code that I've constructed below I get a number that is obviously not the sum of the elements. What am I doing wrong?
import java.util.Scanner;
public class SumProduct
{
public static void main (String []args)
{
Scanner input = new Scanner (System.in);
int[] array1 = new int [input.nextInt()];
input = scan.nextInt();
for (int i = 0; i < array1.length; i++)
{
array1[i] = input.nextInt();
}
for (int i = 0; i < array1.length; i++)
{
int j = array1[i];
int k = array1[i]+1;
int sum = j + k;
System.out.print(sum);
}
}
}
You probably want to prompt the user to enter the size of the array if you're going to do this.This line of code is allowing whatever the user enters to be the size of your array.
int[] array1 = new int [input.nextInt()]; //this sets the size of the array through user input
scan doesn't exist in the currrent context:
input = scan.nextInt(); // this is invalid syntax as scan is not the Scanner you created
for (int i = 0; i < array1.length; i++)
{
array1[i] = input.nextInt();
}
I would do this to keep adding elements to the array:
// no need for this: input = scan.nextInt();
for (int i = 0; i < array1.length; i++)
{
System.out.println("Enter integer to add:");
array1[i] = input.nextInt();
}
This code will give you the sum of the elements if you just add one element at a time instead of two to the sum variable:
int sum = 0;
for (int i = 0; i < array1.length; i++)
{
sum += array1[i];
System.out.print(sum); // this will print out sum after each addition
}
System.out.print(sum); // this will print out sum after the entire array is summed
Adding some logic to only allow the user to enter so many numbers to the array would be helpful as well. You will need to move on from them entering data into the array at some point. Then also remember to close the scanner when you're finished getting data from the user:
input.close();
Your problem is in the following lines of code:
for (int i = 0; i < array1.length; i++)
{
int j = array1[i];
int k = array1[i]+1;
int sum = j + k;
System.out.print(sum);
}
it should look something like
int sum = 0;
for (int i = 0; i < array1.length; i++)
{
sum = sum + array1[i];
}
System.out.print(sum);
The first change is to declare the variable "sum" outside of the loop. The way it's written, it will get declared, then disappear, then declared, then disappear for every loop iteration. You also probably want to initialize it to 0
The second change is to your summation logic. Lets assume your array contains the three numbers [1, 2, 3] and walk through your logic.
j = array1[0] //(j == 1)
k = array1[0] + 1 //(k == 1 + 1 == 2)
sum = j + k //(sum == 1 + 2 == 3)
You then throw out the variable "sum" like I mentioned earlier, and start over with the same logic on the second array element, then again on the third.
i.e. j = 2, k = 2+1, sum = 2 + 2 + 1. followed by j = 3, k = 3 + 1, sum = 3 + 3 + 1.
You can probably see how this isn't the sum, and results in you logging the three digits 3, 5, and 7 for this example case.
In my updated logic, we simply loop through each element and add it to the current running total.
hope this helps
I am a newbie here. I wanted to print out the duplicate elements in an array.
This code will print out the duplicate elements.
Suppose I'm taking an array of size 5 with elements [1,2,5,5,5]
This code will print:
Duplicate elements: 5,5,5 //(since 5 is being repeated thrice.)
But I want the output something like this
Duplicate Elements: 5 //( instead of printing 5 thrice)
import java.util.*;
import java.util.Scanner;
public class duplicateArray{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int x =sc.nextInt();
int arr[]=new int[x];
int i,count=0;
for(i=0;i<x;i++){
arr[i]=sc.nextInt();
}
System.out.print("Array: ");
for(i=0;i<x;i++){
System.out.print(arr[i]+" ");
}
System.out.println(" ");
System.out.print("Duplicate elements: ");
for(i=0;i<arr.length;i++){
for(int j=i+1;j<arr.length;j++){
if(arr[i]==arr[j]){
System.out.print(arr[j]+" ");
}
}
}
}
}
The following code does it without creating any additional data structure. For each element, it counts the number of duplicates previously encountered and only prints the first duplicate.
If I were doing this in the real world, I would use a Set but I'm assuming you haven't learnt about them yet, so I'm only using the array that you've already created.
import java.util.Scanner;
public class DuplicateArray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int x = sc.nextInt();
int[] arr = new int[x];
System.out.print("Enter " + x + " values: ");
for (int i = 0; i < x; i++) {
arr[i] = sc.nextInt();
}
System.out.print("Array: ");
for (int i = 0; i < x; i++) {
System.out.print(arr[i]+" ");
}
System.out.println();
System.out.print("Duplicate elements:");
for (int i = 0; i < arr.length; i++) {
int numDups = 0;
for (int j = 0; j < i; j++) {
if (arr[i] == arr[j]) {
numDups++;
}
}
if (numDups == 1) {
System.out.print(" " + arr[i]);
}
}
System.out.println();
}
}
One solution is to create a separate List to store any duplicates found.
That, in addition to using the .contains() method of the List, you can ensure only one entry per int is made.
public static void main(String[] args) {
// Sample array of ints
int[] ints = {1, 1, 4, 5, 2, 34, 7, 5, 3};
// Create a separate List to hold duplicated values
List<Integer> duplicates = new ArrayList<>();
// Find duplicates
for (int i = 0; i < ints.length; i++) {
for (int j = 0; j < ints.length; j++) {
if (ints[i] == ints[j] && // Are the ints the same value?
i != j && // Ignore if we're looking at the same index
!duplicates.contains(ints[i])) { // Check if our List of duplicates already has this entry
duplicates.add(ints[i]); // Add to list of duplicates
}
}
}
System.out.println("Duplicates: " + duplicates);
}
Output:
Duplicates: [1, 5]
This is pretty simple however you need to sort array before. All you need to know if duplicate for an element exists or not and do the printing in the outside for loop. Rest is described in comments
Arrays.sort(arr); // Sort Array
for (int i = 0; i < arr.length; i++) {
boolean hasDuplicate = false; // Assume that arr[i] is not repeating
for (int j = i + 1; j < arr.length; j++) {
// Check if it is repeating
if (arr[i] == arr[j]) {
// If it repeats
hasDuplicate = true;
}
// Since array is sorted we know that there is no value of arr[i] after this
if (arr[i] != arr[j]) {
// Set i to the last occurrence of arr[i] value
i = j - 1;
break; // Since there no occurrence of arr[i] value there is no need to continue
}
}
// Print the element at i
if (hasDuplicate)
System.out.print(arr[i] + " ");
// In next iteration loop will start from the index next to the last occurrence of value of arr[i]
}
System.out.println("Duplicate Elements : ");
for(int i = 0; i<arr.length; i++){
boolean isDuplicate = false;
for(int k=0;k<i;k++){
if(arr[i]== arr[k]){
isDuplicate = true;
break;
}
}
if(isDuplicate){
continue;
}
int count = 0;
for(int j=0; j<arr.length; j++){
if(arr[i] == arr[j]){
count++;
}
if(count >1){
System.out.println(arr[i]);
break;
}
}
}
Without using Hashmaps, I think your best option would be to first sort the array and then count the duplicates. Since the array is now in order you can print the duplicates after each number switch!
If this is for an assignment go ahead and google bubble sort and implement it as a method.
So my task is to read a file line by line and store the integers into an array. Then to add the integers in spots 1-5, 2-6, 3-7 etc. and store those into a new array.
In array 1 there is 4 more values than array 2. I need to compare these Arrays and see if array1 is 0.999 bigger than array2.
If it is indeed larger, I need to print out the LOCATION of the number in the array 1.
Right now my problem is my code is outputting that every number is larger than the corresponding number in array 2.
Code:
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class Asgn7
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner file = new Scanner(new File("asgn7data.txt"));
double[] array = new double[file.nextInt()];
double[] newArray = new double[array.length - 4];
double tempVal = 0;
int j = 0;
int count = 0;
while(file.hasNext())
{
for(int i = 0; i < array.length ; i++)
{
array[i] = file.nextInt();
}
for(j = 0; j < array.length - 4; j++)
{
for(int k = 0; k < 5; k++)
{
newArray[j] += array[j+k] / 5;
}
}
for(int i = 2; i < array.length; i++)
{
if(array[i] > (newArray[i-2] + 0.999));
{
count++;
tempVal = count;
}
System.out.println(tempVal);
}
}
}
}
The values which should be compared are from 3-13.
Judging by the picture, you are not placing the values in the correct index in the second array, or you are not matching the correct ones.
If you want it to look exactly like in the picture, the second array should be declared:
double[] newArray = new double[array.length - 2];
And the loop to fill it should be changed to:
for(j = 2; j < array.length - 2; j++)
{
for(int k = -2; k <= 2; k++)
{
newArray[j] += array[j+k] / 5;
}
}
This will put the averages in the third, fourth, fifth... elements in newArray. And now you can compare them directly:
for(int i = 2; i < array.length - 2; i++)
{
if(array[i] > (newArray[i] + 0.999))
{
count++;
tempVal = count;
}
System.out.println(tempVal);
}
If you want to save the two unused spaces, as you originally did, rather than responding exactly to the picture, then you should calculate the values as you originally did. But remember to compare each element to the one two places before it and stop 2 places before the end.
Instead of
for(int i = 2; i < array.length; i++)
use
for(int i = 2; i < array.length - 2; i++)
To print the location, your construct with the count and tempVal is unnecessary. You just need to print i+1. Also note that you have a ; after your if. This means it's an empty if, and the block after it is always performed. Never have a ; after an if, for, while etc.
Not clear with what you are asking for in your question but without questioning what's the logic, by just looking at your code:
for(int i = 2; i < array.length; i++)
{
if(array[i] > (newArray[i-2] + 0.999));
{
count++;
tempVal = count;
}
System.out.println(tempVal);
}
}
if you relocate the system.out line as follows, I think you will get what you expect as follows:
for(int i = 2; i < array.length - 2; i++)
{
if(array[i] > (newArray[i-2] + 0.999));
{
System.out.println(tempVal);
// count++;
// tempVal = count;
}
}
}
PS: Please note that I have also changed the boundary for the loop to stop iteration on 13th member of the array, instead of 15.
Are you sure you're parsing the numbers correctly?
See Java: Reading integers from a file into an array
Why don't you print them out after parsing for verification?
btw, this will overflow the index of the 2nd array (since it is created using new double[array.length - 4]):
for(int i = 2; i < array.length; i++)
so does your code run?
I'm very close to completing this, all I need is help on finding the five lowest values from a text file by using arrays. I figured out how to find the five highest values, but my min array to find the lowest values always outputs five 0's.
Output: //obviously dependent on individual text file
Total amount of numbers in text file is 10
Sum is: 1832
1775 14 9 9 7 //max
0 0 0 0 0 //min
Any help is much appreciated!
import java.util.Scanner;
import java.io.*;
public class HW3
{
public static void main(String[] args) throws IOException
{
File f = new File("integers.txt");
Scanner fr = new Scanner(f);
int sum = 0;
int count = 0;
int[] max = new int[5];
int[] min = new int[5];
int temp;
while(fr.hasNextInt())
{
count++;
fr.nextInt();
}
Scanner fr2 = new Scanner(new File("integers.txt"));
int numbers[] = new int[count];
for(int i=0;i<count;i++)
{
numbers[i]=fr2.nextInt(); //fills array with the integers
}
for(int j:numbers)//get sum
{
sum+=j;
}
for (int j=0; j < 5; j++) //finds five highest
{
for (int i=0; i < numbers.length; i++)
{
if (numbers[i] > max[j])
{
temp = numbers[i];
numbers[i] = max[j];
max[j] = temp;
}
}
}
for (int j=0; j < 5; j++) //finds five lowest...array not assigned values
{
for (int i=0; i < numbers.length; i++)
{
if (numbers[i] < min[j])
{
temp = numbers[i];
numbers[i] = min[j];
min[j] = temp;
}
}
}
System.out.println("Total amount of numbers in text file is " + count);
System.out.println("Sum is: " + sum);
System.out.println(max[0] + " " + max[1] + " " + max[2] + " " + max[3] + " " + max[4]);
System.out.println(min[0] + " " + min[1] + " " + min[2] + " " + min[3] + " " + min[4]);
}
}
Your min array will be initialized with zero values. So the values in numbers will always be higher (assuming there are no negatives).
I'd suggest that you initialize min[j] with numbers[0] before the inner loop.
for (int j=0; j < 5; j++) //finds five highest
{
min[j] = numbers[0]; // Add this line
for (int i=0; i < numbers.length; i++)
{
Try debugging your code by entering inside your nested min loop the following line:
System.out.println("the value of numbers[i] is: " + numbers[i]);
so it looks like this:
for (int j=0; j < 5; j++) //finds five lowest...array not assigned values
{
for (int i=0; i < numbers.length; i++)
{
if (numbers[i] < min[j])
{
System.out.println("the value of numbers[i] is: " + numbers[i]);
temp = numbers[i];
numbers[i] = min[j];
min[j] = temp;
}
}
}
You'll notice something interesting. The innermost nested part doesn't even start.
Try putting that line into the nested max loop in its respective location instead... and it will run fine and show the max array values. You are getting zero values for the min array because (other than initial assigning) the innermost part of the nested min loop isn't being started somehow, so it fails to run and searched values do not get assigned to the min array.
The outer nested parts of the min loop run fine if you try debugging them with a similar line. It's this part that won't start and something's wrong with:
if (numbers[i] < min[j])
{
System.out.println("the value of numbers[i] is: " + numbers[i]);
temp = numbers[i];
numbers[i] = min[j];
min[j] = temp;
}
(Update)
In the min loop, numbers[i] from i=0 to i=4 have a value of 0 after completing the max loop.
You only need to add one line and use int i=5 instead of int i=0 inside your min loop:
for (int j=0; j < 5; j++) //finds five lowest...array not assigned values
{
min[j] = max[4]; // added line
for (int i=5; i < numbers.length; i++) // change to int i=5
{
if (numbers[i] < min[j])
{...
As the other answer states, your problem is that you did not take into account the arrays beginning at 0. In Java, it sets default values for that data structure. For primitives, this will normally be 0 or false. However, when you move into data structures, you will have problems with null pointer exceptions if you fail to initialize your objects. For this reason, I would urge you to get into the habit of setting the values in your data structures before you ever use them. This will save you A LOT of debugging time in the future.
If you know the values in advance, you can set them manually with {0,0,0,0,0} notation, or your can initialize using a for loop:
for(int i = 0; i < array.length; i++)
array[i] = init_value;
I would recommend that you also look into trying to consolidate as much as possible. For example, in your code you go through the same data 4 times:
1) read the integers from the file into an integer array
2) sum all of the numbers in the integer array
3) look for max
4) look for min
I'm not sure if you've covered functions yet, but one example of consolidating this might look like:
while(fr2.hasNextInt()){
int i = fr2.nextInt();
sum += i;
checkHighest(i);
checkLowest(i);
}
You then define these functions and put the meat elsewhere. This lets you only worry about the loops in one place.
You have 2 problems.
First was explained by Tom Elliott.
The second problem is that also the max[] array is initialized with 0, and when you search for max values you change the value from max array (which is 0) with the value from the numbers array, so the numbers array becomes filled with 0s.
A quick solve (though not the best) would be to copy the numbers array in a temp array and use that temp when searching for min values.
In case you didn't exactly understood what I said, try to make a print of the numbers array after you found the 5 max values.
Just curious , Cant you just sort it(using quick sort) select top five and bottom five ?
- if you can use sorting I think this should work then
int sum = 0;
int count = 0;
int[] max = {Integer.MIN_VALUE,Integer.MIN_VALUE,Integer.MIN_VALUE,Integer.MIN_VALUE,Integer.MIN_VALUE};
int[] min = {Integer.MAX_VALUE,Integer.MAX_VALUE,Integer.MAX_VALUE,Integer.MAX_VALUE,Integer.MAX_VALUE};
int temp;
int visited[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
for (int j : numbers)// get sum
{
sum += j;
}
int tempindex;
for (int j = 0; j < 5; j++) // finds five highest
{
for (int i = 0; i < numbers.length; i++) {
if (visited[i] != 1) {
if (numbers[i] > max[j]) {
max[j] = numbers[i];
tempindex = i;
}
}
}
visited[tempindex] = 1;
}
for (int j = 0; j < 5; j++) // finds five lowest...array not assigned
// values
{
for (int i = 0; i < numbers.length; i++) {
if (visited[i] != 1) {
if (numbers[i] < min[j]) {
min[j] = numbers[i];
tempindex = i;
}
}
}
visited[tempindex] = 1;
}
So the program is supposed to allow the user to input 10 scores and the print those scores in ascending order on the following line. For some reason it allows me to input the scores, but the following line is just filled with 0s instead of sorting the input in ascending order. I'm not sure why, but any input would be helpful.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out
.println("Enter up to 35 scores between 0 and 100, -1 to stop:");
int[] score = new int[35];
int count = 0;
int sum = 0;
String scores = "";
for (int i = 0; i < score.length; i++) {
score[i] = keyboard.nextInt();
if (score[i] >= 0) {
scores = scores + score[i] + " ";
count++;
sum = sum + score[i];
} else
i = score.length + 1;
}
for (int i = 1; i < score.length; i++) {
int x;
int temp;
x = score[i];
temp = score[i];
for (x = i - 1; x >= 0 && score[x] > temp; x--) {
score[x + 1] = score[x];
}
score[x + 1] = temp;
}
System.out.printf("The %d scores you entered are: \n%s", count, scores);
System.out.println();
System.out.printf("The %d scored sorted in nondecreasing order are:\n",
count);
int k=1;
for (k=1; k <= count; k++) {
if (k % 11 == 0) {
System.out.println();
} else {
System.out.printf("%5d", score[k]);
}
}
for (int i = 1; i <= count; i++) {
if (i % 11 == 0) {
System.out.println();
} else {
System.out.printf("%5d", score[i]);
}
for (int j = 1; j < count; j++) {
if (Integer.compare(score[i], score[j]) < 0) {
int temp = score[i];
score[i] = score[j];
score[j] = temp;
}
}
}
I agree with comment about learning to debug. The way you have written your code, it is apparent that you are very beginner so here is the answer to help you. To answer your question, you have several logical mistakes in your program.
You can simply use break to exit out of the first for loop. so in the else statement just write break; instead of i = score.length + 1;
Next... mistake is that you are sorting entire array... However as you may have entered only 5 or 6 elements before entering -1, your first 5 or 6 elements will have values and all other values in that score array as 0. If you sort the entire array, you will obviously be going to bring 0's to the front and actual scores to the back of the array. This is the answer for your question. Sort from i = 0 to i < count. This will fix some of your issues, but you have many more issues.
There are several other issues. I hope you will be able to debug and find out.