I'm working on a program that creates a plotted line from a generated array list of real time numbers. The numbers aren't necessarily linear and can create a crooked pattern. The program counts the points of inversion and gives them to the user, however the clutter on the screen can be quite a problem when a large number of inversions exist. Is there a way to rewrite/modify the code as to make it so that only certain numbers are printed, for example if the person wants the numbers 80, 90, and 143 to only show. Code attached:
CustomCoordinate is a custom class that helps setup the list, included for clarity.
private int count;
private int num;
public CustomCoordinate(long time, double value, int number) {
super(time, value);
this.count = number;
}
public int getCount() {
return count;
}
For clarification, selDateInSec is a calendar object where the user inputs the date of when the first data point label will be located along the x-axis. Any inversion before this won't be labeled, any after will.
int x = 0;
if (inversions) {
for(CustomCoordinate c : points) {
if(c.getTime() > selDateInSec) {
Label lbl = new Label (instr.format(++x), f, txtColor, bgColor);
lbl.setLocation(c);
addFigure(lbl);
}
}
}
Thanks in advance
You can take input from the user about the points they are interested in and then use filter function on it to filter out the points of interest. Hence you'll be able to show only the points of interest without clutter.
Related
iam newbie in this so i will ask straightly and if smb can help me that would be appreciated. Iam trying to make a Sudoku Game in BlueJ and until now i havent got any help from google searches and staff so iam posting here.
I need my sudoku firstly to be a random puzzle when pressing a button to start new.
Then the main concept and correct me if iam wrong is to built one random table which will be the solution for the user and one table where user can see 3 numbers only from the table and pick the other. With Comparing of 2 tables, users and solution the programm can see if the user has it correct.
Until now i have this code.
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class MyFrame extends Frame
{
private double[] data;
private Button avgButton,minButton,maxButton,rndomButton;
private Button quit;
public MyFrame(String title)
{
super(title);
resize(200,200);
setResizable(false);
setLayout(new GridLayout(3,2));
quit=new Button("QUIT");
rndomButton=new Button("RANDOM");
add(rndomButton);
add(quit);
}
public int Array()
{
Random rand = new Random();
int n = rand.nextInt(3) + 1;
int y = rand.nextInt(2) + 1;
int i=0;
int j=0;
int value;
int[][] board = new int[3][3];
value=board[0][0];
int z=board[0][0];
for(i=0;i<3;i++)
{
do{
board[i][0]=n;
}while (board[i][0]!=board[i-1][0]&&board[i][0]!=board[i-2][0]);
}
for(j=0;j<3;j++)
{
do{
board[0][j]=n;
}while (board[0][j]!=board[0][j-1]&&board[0][j]!=board[0][j-2]);
}
for(i=1;i<3;i++)
{
for(j=1;j<3;j++)
{
do{
board[i][j]=n;
}while (board[i][j]!=board[i-1][j]&&board[i][j]!=board[i-2][j]&&board[i][j]!=board[i][j-1]&&board[i][j]!=board[i][j-2]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
z=board[i][j];
}
}
return z;
}
public boolean action(Event evt,Object arg)
{
if(evt.target.equals(rndomButton))
message("Array: "+Array());
else
if(evt.target.equals(quit))
System.exit(0);
return true;
}
}
I dont know if it is correct because when i try to return z value its just a window pops up with nothing in there.
Note if i get return z in lasts for i get an error on bluej.
Sorry for my programming skills.
I hope u can help me or at least recommend me some links to look at.
Thanks in advance.
It's possible you've jumped into your coding a little too soon. It appears that you need to better define your approach to the problem. First, think about how you would solve it by hand. Break that down into steps, and write those steps down. Then, make your code model your solution step by step.
For example, if you think about building your board one row at a time, then you would write down something like, "For the first row, take 1, 2, 3, and rearrange them in random order..." If you think. instead, about building your board one digit at a time, you might write, "Place a 1 in a random location in the first row. Place a 1 in a random location in the second row, but avoid a conflict with the first row. Place a 1 in the only remaining column in the third row.
With your second digit, you'll encounter more constraints-- instead of just selecting any column at random from the first row, you'll need to select randomly from an available column.
1 2 .
. 1 .
. . 1
In the example above, when placing a 2 in your second row, how do you determine which is available? (One choice leads to a solution, the other to a dead-end). Once you're able to articulate the steps you would take to solve the problem by hand, writing the code becomes much easier and the small pieces you may get stuck on become easier to address.
I am pretty new in Java. I am developing a Java console application which has a field and a frog jumping around in it, the user decides the size of the field through input in a 2d array, (kind of like a chess board but the difference is that the user decides how big the field should be). For instance the users enter height of field in feet and the width in feet. So far I have managed to do a bit of the class Field and class Position, which takes input from user and puts it on a array (int [][]fieldsize).
Class Controller:
package project;
public class Controller {
public static void main( String[] args ) {
Field field = new Field();
Position position = new Position();
}
}
Class Field:
package project;
import java.util.Scanner;
public class Field{
int y;
int x;
int[][] fieldsize;
public Field() {
Scanner scan = new Scanner(System.in);
System.out
.println("Enter the size of the field in feets(width
and length separated by space, x y):");
x = scan.nextInt();
y = scan.nextInt();
int[][] fieldsize = new int[y][x];
this.fieldsize= fieldsize;
}
public int[][] getFieldSize() {
return fieldsize;
}
}
I have managed to "collect" the fields size from user input into int [][] fieldsize array.
Now I want to ask the user about the starting position for the frog and the heading direction, S(south), N(north), E(east), W(west) and then add the frog to the field. For instance the user types 3 4 E. This should put the frog to position [3] [4] East(Heading). How do I resolve this?
Class Position:
package project;
import java.util.Scanner;
public class Position {
public Position() {
int x;
int y;
String heading;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the starting position and heading for the frog, X Y and N, S, W or E position");
x = scan.nextInt();
y = scan.nextInt();
heading = scan.next();
//How do I put this inputs in the Field(fieldsize)?? So they get into this position in the field??
}
}
It is a bit difficult to describe what I mean, but I hope you guys can help me!
Thanks in advance!
OK. First thing you should consider before starting to code - what is the design. And the question like this usually appears when the code comes before the design.
So the first question should be:
What classes do I need and what every class should do and how would they interact.
An object is a self-contained component that contains properties and
methods needed to make a certain type of data useful. An object’s
properties are what it knows and its methods are what it can do.
For example - What can the object of the class Field do? How would it interact with the Position? And what can I do with the Position?
Then you start to design the classes. You sure don't want to read the user input in a constructor. What if you want to get the input from the file tomorrow and get it from the cloud or by voice the next month? Or even worse - what if there is an input error? What would be the state of the object?
You usually need to provide all the data needed to create the object to the constructor. The constructor shouldn't care where you get it from. You can have a public Field(int x, int y) and call it in your main class after reading the user input (I'm not suggesting that you should have this exact constructor, just an example).
You may want to set the position as a method of the Field (field will contain the position)
field.setPosition(position);
or have a move method of the Position (you can have as much positions as you like on the field)
position.setField(field);
position.moveTo(x,y);
Or you can even get to the conclusion you don't need a Position at all, and it would merely be the Field's property:
field.setCurrentX(x);
field.setCurrentY(y);
The design is really up to you here. Just have the design before you code.
I have a 10x10 multiplication table. I need to code in so that when a user inputs a certain number, 50 for example, the numbers >50 are replaced by a character and the rest remain the same.
I know how to do this using strings but I have no clue how to do this in this situation. Any help will be appreciated.
public class task4{
public static void main(String args[]){
int Multiples = 10;
System.out.format(" Table");
for(int z = 1; z<=Multiples;z++ ) {
System.out.format("%5d",z);
}
System.out.println();
System.out.println("-------------------------------------------------------------------------------------------------------");
for(int i = 1 ;i<=Multiples;i++) {
System.out.format("%5d |",i);
for(int j=1;j<=Multiples;j++) {
System.out.format("%5d",i*j);
}
System.out.println();
}
}
}
That seems to be simple enough problem, basically you have table drawing code, your for loops, so we function that off into a nice little method public void drawTable(){} which we call to draw the table initially, but we also provide an overloaded version which takes a number public void drawTable(int maxDispNum){} and this method is the same except if i*j >maxDispNum we print a character instead. then in main we can simply while(true){ read val; drawTable(val);}
alternativley if you want to maintain a permanent record of what's been removed stored the table in an array, 10*10 in your case and use some marker, -1 works here to indicate removed, and simply check for that in your draw method,
Looks like this is the week for this type of question. And after reading through all of the new ones and several old ones, I'm no less confused!
I have a text file with 5 employees, each having 10 salary values listed beneath their name. I am to read in this file, find and display the employee Name, minimum salary, maximum salary and the average salary for each person. I must have 3 loops: One to control reading the file, one to lad the data into the array, and one to do the calculations. I have to print the information for each person on one line, and i must allow decimals rounded to 2 decimal places apparently using Math.round which I've never heard of!
I am embarrassed to show you the mess of code I have because it's not much, but I don't know after reading all that I have if I've even started correctly. I do not know if I have even the right idea of how to proceed. Your help is appreciated.
UPDATED CODE: AGAIN!
import javax.swing.*;
import java.io.*;
public class MinMaxSalary3
{
public static void main(String args[])throws Exception
{
// Declare input file to be opened.
FileReader fr = new FileReader ("salary.dat");
BufferedReader br = new BufferedReader (fr);
//General Declarations
final String TITLE = "Employee's Salary Report";
String employeeName, salaryString;
double avgSalary=0.0;
double totalSalary = 0.0;
double sum = 0.0;
// Declare Named Constant for Array.
final int MAX_SAL = 10;
// Declare array here.
int salary[] = new int[MAX_SAL];
System.out.println (TITLE);
while ((employeeName = br.readLine()) != null)
{
System.out.print ("" + employeeName);
// Use this integer variable as your loop index.
int loopIndex;
// Assign the first element in the array to be the minimum and the maximum.
double minSalary = salary[1];
double maxSalary = salary[1];
// Start out your total with the value of the first element in the array.
sum = salary[1];
// Write a loop here to access array values starting with number[1]
for (loopIndex = 1; loopIndex < MAX_SAL ;loopIndex++)
// Within the loop test for minimum and maximum salaries.
{
if (salary[loopIndex] < minSalary)
{
minSalary = salary[loopIndex];
if (salary[loopIndex] > maxSalary)
maxSalary = salary[loopIndex];
}
{
// Also accumulate a total of all salaries.
sum += sum;
// Calculate the average of the 10 salaries.
avgSalary = sum/MAX_SAL;
}
// I know I need to close the files, and end the while loop and any other loops. I just can't think that far right now.
}
{
// Print the maximum salary, minimum salary, and average salary.
System.out.println ("Max Salary" + maxSalary);
System.out.println ("Min Salary" + minSalary);
System.out.println ("Avg Salary" + avgSalary);
}
System.exit(0);
}
}
}
I must have 3 loops: One to control reading the file, one to lad the
data into the array, and one to do the calculations.
What I've written below might just be more gobbledygook to you now, but if you ever get past this class it might be useful to know.
Another way to look at this would be more object-oriented and better decomposition to boot: You need an object to hold the data, to perform the calculations, and render output. How you get that data is immaterial. It's files today; next time it might be HTTP requests.
Start with an Employee object. I deliberately left out a lot of detail that you'll have to fill in and figure out:
package model;
public class Employee {
private String name;
private double [] salaries;
public Employee(String name, int numSalaries) {
this.name = name;
this.salaries = new double[numSalaries];
}
public double getMinSalary() {
double minSalary = Double.MAX_VALUE;
// you fill this in.
return minSalary;
};
public double getMaxSalary() {
double maxSalary = Double.MIN_VALUE;
// you fill this in.
return maxSalary;
}
public double getAveSalary() {
public aveSalary = 0.0;
if (this.salaries.length > 0) {
// you fill this in.
}
return aveSalary;
}
}
The beauty of this approach is that you can test it separately, without worrying about all the nonsense about file I/O. Get this object right, put it aside, and then tackle the next piece. Eventually you'll have a clean solution when you assemble all these smaller pieces together.
Test it without file I/O using JUnit:
package model;
public class EmployeeTest {
#Test
public void testGetters() {
double [] salaries = { 10000.0, 20000.0, 30000.0, 40000.0 };
Employee testEmployee = new Employee("John Q. Test", salaries);
Assert.assertEquals("John Q. Test", testEmployee.getName());
Assert.assertEquals(10000.0, testEmployee.getMinSalary(), 1.0e-3);
Assert.assertEquals(40000.0, testEmployee.getMaxSalary(), 1.0e-3);
Assert.assertEquals(25000.0, testEmployee.getMinSalary(), 1.0e-3);
}
}
The approach you would want to espouse in this situation is an object-oriented approach. Bear in mind that objects are a representation of related data. Consider that an Employee may have information about their salary, name, and what department they work in (as an example).
But that's just one Employee. You may have hundreds.
Consider creating a model of an Employee. Define what is most pertinent to one of them. For example, they all have to have a name, and have to have a salary.
One would then elect to handle the logic of finding information about the collection of Employees - including min, max, and average salaries - outside of the scope of the generic Employee object.
The idea is this:
An Employee knows everything about itself.
The onus is on the developer to tie multiple Employees together.
It's possible that I don't know enough about what your problem is specifically looking for - I'm not even sure that you can use objects, which would really suck - but this is definitely a start.
As for your compilation errors:
salary is a double[]. An array holds many different values of type double inside of it, but a double[] isn't directly a double. Assigning a non-array type to an array type doesn't work, from both a technical stance, and a semantic stance - you're taking something that can hold many values and trying to assign it to a container that can hold one value.
From your code sample, you want to use a loop (with a loop variable i) to iterate over all elements in salary, and assign them some value. Using just salary[0] only modifies the first element.
I am generating my world (random, infinite and 2d) in sections that are x by y, when I reach the end of x a new section is formed. If in section one I have hills, how can I make it so that in section two those hills will continue? Is there some kind of way that I could make this happen?
So it would look something like this
1221
1 = generated land
2 = non generated land that will fill in the two ones
I get this now:
Is there any way to make this flow better?
This seems like just an algorithm issue. Your generation mechanism needs a start point. On the initial call it would be say 0, on subsequent calls it would be the finishing position of the previous "chunk".
If I was doing this, I'd probably make the height of the next point plus of minus say 0-3 from the previous, using some sort of distribution - e.g. 10% of the time it's +/1 3, 25% of the time it is +/- 2, 25% of the time it is 0 and 40% of the time it is +/- 1.
If I understood your problem correctly, here is a solution:
If you generated the delta (difference) between the hills and capped at a fixed value (so changes are never too big), then you can carry over the value of the last hill from the previous section when generating the new one and apply the first randomly genenarted delta (of the new section) to the carried-over hill size.
If you're generating these "hills" sequentially, I would create an accessor method that provides the continuation of said hill with a value to begin the next section. It seems that you are creating a random height for the hill to be constrained by some value already when drawing a hill in a single section. Extend that functionality with this new accessor method.
My take on a possible implementation of this.
public class DrawHillSection {
private int index;
private int x[50];
public void drawHillSection() {
for( int i = 0; i < 50; i++) {
if (i == 0) {
getPreviousHillSectionHeight(index - 1)
}
else {
...
// Your current implementation to create random
// height with some delta-y limit.
...
}
}
}
public void getPreviousHillSectionHeight(int index)
{
return (x[49].height);
}
}