How to print only the last element of an array? - java

I am trying to print the last element of my array. The code can be seen below:
double [] results = new double[21];
double t = 9600;
for(int y = 0; y < 21; y++) {
results[y] = t;
t *= 1.04;
System.out.println(results[results.length - 1]);
}
However, when I attempt to run this, I get this result:
0.0 (printed 20 times in a row)
...
21034.782173120842
I do not know why it is printing out 20 zero's, and then the answer I want (21034.78). I thought that by doing results[results.length - 1], only the last element of the array would be printed. I have a suspicion that this has to do with the loop, but I do not know why or how to fix it.
Any help or advice would be greatly appreciated. Thank you!

You need to put the System.out.println outside the for loop, or else you will always print 0.0 because the last index of the array isn't filled yet.
double [] results = new double[21];
double t = 9600;
for(int y = 0; y < 21; y++) {
results[y] = t;
t *= 1.04;
}
System.out.println(results[results.length - 1]);
Output: 21034.782173120842

put your System.out.println , out of loop.
for(int y = 0; y < 21; y++) {
** YOUR LOGIC **
}
System.out.println(results[results.length - 1]);

You need to move the print statement outside the loop..
double [] results = new double[21]; double t = 9600;
for(int y = 0; y < 21; y++) {
results[y] = t;
t *= 1.04;
}
System.out.println(results[results.length - 1]);

You need to make a slight alteration. Here is one thing that you can do:
double [] results = new double[21];
double t = 9600;
for(int y = 0; y < results.length; y++) {
results[y] = t;
t *= 1.04;
System.out.println(results[y]);
}
You can print the current index [y] each time through the loop. Or else you're always printing index 21 which isn't filled yet and will repeatedly print 0 until it is filled. The current iteration of the loop [y] will always be the last index that actually has a value in it, but the last index won't actually be filled with a value until your last iteration through the loop which explains your error here.

Related

2D array of characters formatting

So i am writing a program where i have to read from a file that contains coordinate points and then display the plot. For instance, i have this as the first line, 20 10. What my program should do, is plot this using a 2D array of characters. An 'X' is to be used for the points.
This is how i calculated the slope and the formula for regression line.
float xMean = xSum / count;
float yMean = ySum / count;
float n = count;
float slope = (xySum - n* xMean * yMean) / (xSqSum - n * xMean * xMean);
I used below method to print '-' char if there is no 'X' char and if there is then an '*' char.
for (int i = 0; i < graph.length; i++) {
int yPred = Math.round(yMean + slope * (i - xMean)); // calculate regression value
graph[21-1-yPred][i + 1] = graph[21-1-yPred][i + 1 ] == 'X' ? '*' : '-';
}
Correct output that i am aiming for
However i am getting this output:
What i am trying to achieve is that my program would print "-"s as the regression line segments, and "*"s where a line segment and a point are located at the same spot
However i am getting less dashes in my program as compared to the correct output. Also the asterisk is not in the middle where it is supposed to be.
This is the text file which i am using. I was able to get the validation done with my program. ** x-coordinates in the range [0, 40] and y-coordinates in the range [1, 20].**
Alright so let's knock out this problem! First, after spending 15 minutes or so putting lines to your screen shot text file, here's the image I drew up (depicting the original of course):
Now, you mentioned having a line or entry of an 'X' you are to draw up. This is also a text file and you're reading it in from file, so here's what said file (let's call it 'coords.txt' for the sake of this example).
20 10
With 20 and 10 being the coordinates read, based off the line-overlay image I made, I think that (20 10) would correlate to x-axis=21, y-axis=10 (The off by one is likely to be a simple indexing off by one error - read more here I basically just treated the graph like a graph ).
This is one way to read that point/data in from file and prepare it to be plotted:
read 20 10 from file by
Scanner s = new Scanner(new File("coords.txt"));
int x = 0;
int y = 0;
if (s.hasNext())
x = s.nextInt();
if (s.hasNext())
y = s.nextInt();
s.close();
That code is easy enough, in that it makes a Scanner object to read the contents of our file. Then, declaring an x and y integer in order to store our coord values. Note: s.hasNext() is valuable logic in general to check to make sure there's something in the text file to read before trying to read it - you could also adapt s.hasNextInt() in order to only look ahead for an integer token next up to read from file.
However, I notice you have several X-marks-the-spot on your result graph. By going back to the image I drew up to visually see the coordinates you would likely have in your non-mentioned explicitly 'coords.txt' file, let's say in this example you would have a file with the following lines:
20 10
0 1
40 20
13 17
10 20
Now these numbers are based off that original image I drew lines over, however I respected the off-by-one error so that's why they don't directly correlate to coordinates on that image, because for the sake of correcting that off-by-one error.
Now with several coords, how to go about reading that input in a more efficient manner? Here's one way to go about it:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class App {
public static final int SIZE = 100;
public static void main(String[] args) throws IOException {
Scanner s = new Scanner(new File("C:\\Users\\Nick\\Desktop\\coords.txt"));
int x = 0;
int y = 0;
int[] xCoords = new int[SIZE];
int[] yCoords = new int[SIZE];
int index = 0;
while (s.hasNextLine()) {
if (s.hasNextInt()) {
x = s.nextInt();
} else {
System.out.println("had a next line, but no integers to read");
break;
}
if (s.hasNextInt()) {
y = s.nextInt();
} else {
System.out.println("had a next line, but no integers to read");
break;
}
xCoords[index] = x;
yCoords[index] = y;
index++;
}
s.close();
}
}
This code assumes several things, including;
we don't think we're going to read more than 100 coordinates to plot. (If you do know this number, simply edit the SIZE value to the pre-determined value. If you don't know the value, then look into growing/expanding an array or java.util.List and a tutorial on the java list interface).
the xCoords and yCoords integer arrays are matching/mirror in that they should both be filled at a given index in order to represent a plot-able coordinate (X-marks-the-spot).
likewise to the previous point, in the while loop, each line is thought to contain two integer values to read that resemble a coordinate.
the integer index value increases after each loop to help ready the next point to read in and also let us know how many points were read in while the while loop was looping.
Running the above code for reading the 'coords.txt' file, and adding a few simple System.out.println()'s after the while loop but before the s.close(); helps show what was read in.
Here's the second version of the input reading, along with the output to show what happened:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class App {
public static final int SIZE = 100;
public static void main(String[] args) throws IOException {
Scanner s = new Scanner(new File("C:\\Users\\Nick\\Desktop\\coords.txt"));
int x = 0;
int y = 0;
int[] xCoords = new int[SIZE];
int[] yCoords = new int[SIZE];
int index = 0;
while (s.hasNextLine()) {
if (s.hasNextInt()) {
x = s.nextInt();
} else {
System.out.println("had a next line, but no integers to read");
break;
}
if (s.hasNextInt()) {
y = s.nextInt();
} else {
System.out.println("had a next line, but no integers to read");
break;
}
xCoords[index] = x;
yCoords[index] = y;
index++;
}
System.out.println("Output from what was read in from file:");
for (int i = 0; i < index; ++i) {
System.out.print(xCoords[i] + ", ");
System.out.println(yCoords[i]);
}
s.close();
}
}
And the respective output:
had a next line, but no integers to read
Output from what was read in from file:
20, 10
0, 1
40, 20
13, 17
10, 20
The first two lines are just comments that can be removed. It's good to see we can read in our data effectively!
Moving onto the bread-and-butter part of the problem, the full output. In order to output the example image, we need to effectively print out a 2D array of characters (at least that's the idea I'll use to explain here).
We know (based on looking at the line-marked graph) that we need to have dimensions of 21 x 42 for complete replica output. This is because of the axis markings themselves. So, let's start off by declaring a 2D array like:
char[][] graph = new char[21][42];
That's great! We have an invisible graph! Let's get those crummy null characters out and put some good old spaces in! After all, this is the root cause of printing everything out all funky, you can't expect the char value of '\0' to behave the same as ' '.
for (int i = 0; i < graph.length; ++i)
for (int j = 0; j < graph[0].length; ++j)
graph[i][j] = ' ';
Now let's start marking it up with the bare axis. First the y-axis:
for (int i = 0; i < graph.length; ++i) {
graph[i][0] = '/';
}
graph[20][0] = '+';
Note: we can cheat with the + symbol since it comes at the very end. The for-loop could use and if statement and mark the last index with the + but lets try to be intuitive too.
Then, for the x-axis:
for (int i = 1; i < graph[0].length; ++i) {
graph[20][i] = '-';
}
Since we know where the very end is, we simply use the hard-coded value of 20 and loop over the index to input the x-axis symbols/char -.
Let's take a look at this newly created graph with the following code:
for (int i = 0; i < graph.length; ++i) {
for (int j = 0; j < graph[0].length; ++j) {
System.out.print(graph[i][j]);
}
System.out.println();
}
Which should produce the following output:
/
/
/
/
/
/
/
/
/
/
/
/
/
/
/
/
/
/
/
/
+-----------------------------------------
Let's plot the X-marks-the-spot now, based on what you used with the coordinates from the earlier code.
This can be done by looping over the mirror integer arrays (xCoords and yCoords) and using those coords to plot onto the 2D char[][] graph.
for (int i = 0; i < index; ++i) {
graph[21 - 1 - yCoords[i]][xCoords[i] + 1] = 'X';
}
Breaking down the information here (above), the [21 - 1 - yCoords[i]] is meant to translate the y-coordinate to the respective spot represented in the 2D array by using a offset from the top value of the graph portrayed backwards (hence using 21 to start from the top) and also another minus one offset because of the axis itself (e.g. the '/' and '-' and '+' characters respectively). For the xCoords, a simply plus one is used for the axis itself offset.
Here is that output:
/ X X
/
/
/ X
/
/
/
/
/
/
/ X
/
/
/
/
/
/
/
/
/X
+-----------------------------------------
Looks very like an early stage of those pictures of what the output is suppose to be!
All in all, this is what my final code looked like:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class App {
public static final int SIZE = 100;
public static void main(String[] args) throws IOException {
Scanner s = new Scanner(new File("C:\\Users\\Nick\\Desktop\\coords.txt"));
int x = 0;
int y = 0;
int[] xCoords = new int[SIZE];
int[] yCoords = new int[SIZE];
int index = 0;
while (s.hasNextLine()) {
if (s.hasNextInt()) {
x = s.nextInt();
} else {
System.out.println("had a next line, but no integers to read");
break;
}
if (s.hasNextInt()) {
y = s.nextInt();
} else {
System.out.println("had a next line, but no integers to read");
break;
}
xCoords[index] = x;
yCoords[index] = y;
index++;
}
System.out.println("Output from what was read in from file:");
for (int i = 0; i < index; ++i) {
System.out.print(xCoords[i] + ", ");
System.out.println(yCoords[i]);
}
s.close();
char[][] graph = new char[21][42];
for (int i = 0; i < graph.length; ++i)
for (int j = 0; j < graph[0].length; ++j)
graph[i][j] = ' ';
for (int i = 0; i < graph.length; ++i)
graph[i][0] = '/';
graph[20][0] = '+';
for (int i = 1; i < graph[0].length; ++i)
graph[20][i] = '-';
for (int i = 0; i < index; ++i)
graph[21 - 1 - yCoords[i]][xCoords[i] + 1] = 'X';
for (int i = 0; i < graph.length; ++i) {
for (int j = 0; j < graph[0].length; ++j)
System.out.print(graph[i][j]);
System.out.println();
}
}
}
If you want to include more detail, e.g. multiple '-' for regression and '*' for point, I'd encourage using this information to learn and adapt to reading those coordinates for that additional information and applying it to this example. There's no supplied information on that however, so I won't venture off topic with alleged text files and coords for that, either edit it into the question or try it yourself and learn something. :) Cheers
Why not just array[x][y] = 'X'; ?
Also, what are you putting into the rest of the array? If you don't put anything there, it defaults to 0 which displays as nothing on the terminal. I'm guessing you wanted to fill the unused entries with spaces and newlines

Handling ArrayList out of bounds exception Java

My program will be creating a two dimensional grid / ArrayList. It will search for all boxes around a specific box and return their elements. However if the box is at an edge it may not have any surrounding boxes in the grid. So we will try to access an empty slot in an arrayList, possibly slot -1.
Is there anyway I can write some code like this in Java:
ArrayList arr = new ArrayList();
//add 5 elements to arr
for(int i = 0; i<10; i++){
if(arr.get(i) is out of bounds){
System.out.println("No elements here");
else{
System.out.println(arr.get(i));
}
You can check to see if i is outside the array bounds.
if i >= arr.size();
Though a better solution would be to loop over the contents of the array with a for each loop like so:
for (Object i : arr){
// Do something
}
You need boundary control check. For instance, if you need to loop around the neighbors of a point x, y, you could do
// assuming that you're checking around point x and y
// here you set minI, maxI
int minI = Math.max(0, x - 1);
int maxI = Math.min(listMax - 1, x + 1);
for (int i = minI; i <= maxI; i++) {
// here you set minJ and maxJ
int minJ = Math.max(0, y - 1);
int maxJ = Math.min(innerListMax - 1, y + 1);
for (int j = minJ; j <= maxJ; j++) {
// do your stuff here
}
}

I'm having a compare issue

I am having a really stupid problem that has been bugging me for a couple of hours now. I have made a program to compare slope of an Array of points and draw a line through four points with the same slope. My problem is I take the initial slope as a comparator to each slope. Then compare the inital value to each other point in the array and if the slope of the initial comparator is the same as the next slope the counter increments. my problem is I done want the initial slope to change during the for loops but I cant get it to work. The code is below, I know im being kind of vague so if you need any more information just ask.
for(int initial = 0; initial < counter/2 ; initial ++)
{
int comparator = 1;
for(int next = 1 ; next < counter/2 ; initial ++)
{
Point finalCompare = points[initial];
Point initialCompare = points[comparator];
Point initialPoint = points[initial];
int counter_2 = 0;
Point nextPoint = points[next];
double initialSlope = (initialCompare.y - initialPoint.y/ initialCompare.x-initialPoint.x);
double nextSlope = (nextPoint.y - initialPoint.y/ nextPoint.x - initialPoint.x);
if(initialSlope == nextSlope)
{
counter_2++;
StdOut.println("Counter: " + counter_2);
finalCompare = points[next];
}
if(counter_2 >= 3)
{
StdOut.println("got here");
initialPoint.drawTo(finalCompare);
break;
}
StdOut.println(counter_2);
}
StdOut.println("comparator");
comparator++;
}
}
You're never changing next. I assume you want
for(int next = 1 ; next < counter/2 ; next++)
instead of
for(int next = 1 ; next < counter/2 ; initial ++)
Additionally, this condition seems to never be true: if(counter_2 >= 3)
You set counter_2 to 0 and increment it at most once before this statement:
int counter_2 = 0;
...
if(initialSlope == nextSlope)
{
counter_2++;
...
}
//counter_2 can either be 0 or 1 here
if(counter_2 >= 3)
{
...
}
I assume you want to move the initialization out of the inner loop:
int counter_2 = 0;
for(int next = 1 ; next < counter/2 ; next++)
Besides that, please step through your code with a debugger and see what is done at each step. This will help you find typing errors (if you understand the algorithm you're implementing, otherwise try and understand that first).
these lines
double initialSlope = (initialCompare.y - initialPoint.y/ initialCompare.x-initialPoint.x);
double nextSlope = (nextPoint.y - initialPoint.y/ nextPoint.x - initialPoint.x);
I think they are not doing what you want, remember that / has precedence , so first is going to divide initialPoint.y/ initialCompare.x , and then the rest of the operations, I think you want to do :
double initialSlope = ((initialCompare.y - initialPoint.y)/ (initialCompare.x-initialPoint.x));
double nextSlope = ((nextPoint.y - initialPoint.y)/ (nextPoint.x - initialPoint.x));

Removing duplicates scale up error

I am trying to remove duplicates from an array. What I have works on an array size of 10([11]). Then i had to scale it up to 5000([5001]). I thought this would be very simple. It compiles but when I run it it runs an infinite loop. I'm not sure if it's just taking a long time or something doesn't work.
The sort.sorting works.
public class work_on_it5
{
public static void main(String [] args)
{
int array [] = new int [5001];
int LB = 1;//declare the lower bound
int UB = 5000;//declare the upper bound
for(int x = 0; x < 4999; x++)
{
if(array[x]==array[x+1])
{
array[x+1] = (int)(Math.random()*50) + 1;
sort.sorting(array);
x=0;
}
}
sort.sorting(array);
for(int x = 0; x < 4999; x++)
{
System.out.println(array[x]);
}
//median(LB, UB, array);
//mean(array);
}
The reason for infinite loop is because you are setting x=0;
for(int x = 0; x < 4999; x++)
{
if(array[x]==array[x+1])
{
array[x+1] = (int)(Math.random()*50) + 1;
sort.sorting(array);
x=0; //Here you are setting the value of x which is never changed resulting in infinite loop
}
}
in your for loop
So every time when it enters in the for loop the value of the x is equal to 0.
Also the declaration
int array [] = new int [5001];
so all the elements of the array will have the default value as 0 so the condition if(array[x]==array[x+1]) will always be true and then the above scenario that x is always 0 will cause the problem. Change the logic!
On a side note:-
It is better to use array.length instead of hard coding the length of array in for loop.
Why infinite loop happens:
1 You declare an int array as follows:
int array [] = new int [5001];
each element has a defalut value of 0.
2 in the for-loop, if(array[x]==array[x+1]) will always TRUE. and then x = 0
for(int x = 0; x < 4999; x++)
{
if(array[x]==array[x+1])
{
array[x+1] = (int)(Math.random()*50) + 1;
Arrays.sort(array);
x=0;
}
}
As a result, the program always compare the first 2 elements only.
Compare array[0] and array[1], they are equal.
Reset x = 0
Compare array[0] and array[1], they are equal.
Reset x = 0
Compare array[0] and array[1], they are equal.
Reset x = 0
... ...
This causes infinite loop. Make some change and go ahead. :)

Checking if two sets of numbers are equal error

I'm getting this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
which is referring to this line in the code if(x[k]==y[j])
Scanner sc1 = new Scanner(System.in);
int [] x;
int [] y;
int size;
System.out.println("Numbers in launch code sequence should be entered on ");
System.out.println("single line, separated by blanks.");
System.out.println("");
System.out.println("Enter length of launch code sequence: ");
size = sc1.nextInt();
x = new int[size];
y = new int[size];
int k = 0;
int j = 0;
System.out.println("Mr. President, Enter the launch code sequence: ");
for(;k<x.length; k++){
x[k] = sc1.nextInt();}
System.out.println("Mr. Vice President, Enter the launch code sequence");
for(;j<y.length; j++){
y[j] = sc1.nextInt();
if(x[k]==y[j]){
System.out.println("All equal: Missile system cleared for launch.");
if(x[k]!=y[j]){
System.out.println("Codes do not check out. Abort missile launch.");
}
}
}
}
Your code
iterates through the x Array; afterwards, k == x.length
iterates through the y Array; inside this iteration, you compare with x[k], which is out of bounds for x
I guess what you really want to do is two nested loops - in that case, change
for(;k<x.length; k++){
x[k] = sc1.nextInt();}
to
for(;k<x.length; k++){
x[k] = sc1.nextInt();
and add the closing } after the y loop.
At this stage
if(x[k]==y[j]){
k has finished iterating through its array and will be set to x.length
and therefore out of bounds
You should reset the value of k back to 0 after you've done loading the code. Or you can just define it in the loop header.
for(int k = 0; k < x.length; k++)
{
// Your code here.
}
After this for loop finishes :
for(;k<x.length; k++){
x[k] = sc1.nextInt();}
value of k will be x.length
k == x.length //will be true. because the k will be incremented and the condition k<x.length will be checked. this is how the for loop functions
and in the next for loop you are accessing
x[k] // equivlent of x[x.length] which is out of abounds
The maximum index that you are allowed to access is x[x.length-1] because in java arrays the indexing starts from 0
Hence the Exception ArrayIndexOutofBounds, x[k] will be out of bounds

Categories