Simple Function That Returns Array
Jun 1, 2014
Basically, it's to write a method that takes in, and then returns another array, whose first element is the average of the first two numbers, last element is the average of the last two, and then everything else is just the average of that index, the one before, and the one after. {1, 2, 4, 8} would return {1.5, 2.33333, 4.66666, 6}.I'm currently getting everything fine, except am not getting the last number (i.e. '6').
public class Arrays {
public static void main(String [] args){
double [] a1 = {1, 2, 4, 8};
for (int i = 0; i < a1.length; i++)
System.out.println(a1[i]);
[code]....
View Replies
ADVERTISEMENT
Jun 9, 2014
Before I created the data file are the points of x and y I created a model class that represents the graph. I have a problem with making a function that returns the panel of the graph.
Attached File(s)
data.cvs.txt (726bytes)
Number of downloads: 12
chart.txt (3.72K)
Number of downloads: 10
View Replies
View Related
Jun 15, 2014
Write a method that returns a new array by eliminating the duplicate values in the array using the following method header: public static int[] eliminateDuplicates(int[] list). The thing is that I found the working solution that is written below, but how it works. How to eliminateDuplicates method done with flag and flag2.
Here is the code:
Java Code:
import java.util.Scanner;
public class Exercise06_15 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
int[] numbers = new int[10];
System.out.println("Enter ten numbers: ");
[code]....
View Replies
View Related
Sep 11, 2014
I have to shuffle a deck of cards (supposed to be 52 but I started with 3) and I wrote this code but it returns all zeroes for the RandomDeck.
import java.util.Random;
public class shuffleDeck {
public static void main(String[] args) {
int[] Deck = new int[3];
for (int i=0; i<3; i++)
[code]...
View Replies
View Related
Mar 4, 2014
I need to create a method that returns a new array containing the componentwise sum of its arguments(if length is the same). For instance, if the input arrays are {0,1, 2} and {2, 2, 3} then the output is {0+2, 1+2, 2+3}, i.e. {2,3,5}.If the input arrays have different numbers of elements, the method should return null.
I came with something like this, however i dont know how to make a copy of an array from two arrays. My code obviously wont compile. package whatever;
import java.util.Arrays;
public class hhhh {
public static void main(String[] args) {
double [] a = {1,2,3};
double [] b = {2,3,4};
[code]...
View Replies
View Related
Jan 26, 2015
Write a Java method that returns the largest value of an array of doubles passed to the method as an argument.
Back into java wasn't sure how to do it for doubles did one in the main for integers and then added a method changed from int to double and now i'm lost as go why its not working.
package kickstarter9;
public class Kickstarter9 {
public static void main(String[] args){
double myList;
double[] myList = {6.0, 4.1, 2.4, 6.8, 1.9, 9.4, 2.8, 4.6, 9.3};
// find the largest value in the list
[Code]...
View Replies
View Related
Apr 4, 2015
This is what I have to create : Write a method that returns the largest object in an array of objects. The method signature is:
public static Object max(java.lang.Comparable[] a)
All the objects are instances of the java.lang.Comparable interface. The order of the objects in the array is determined using the compareTo method.
Write a test program in the main method that creates an array of ten Strings, an array of ten Integers, and an array of ten java.util.Dates, and finds the largest string (i.e. in the alphabetical order), Integer, and Date in the arrays.
Name your java class Max and your java file Max.java.
I am struggling a bit with this code as I am sure you can see, and am at loss. I have never used the compareTo method. Am I doing this right, or on the right track with my code?
public class Max implements Comparable {
public static Object max(java.lang.Comparable[] a) {
java.lang.Comparable tempObj = null;
for (int i = 0; i < a.length; i++) {
if (a[i].compareTo(tempObj) > 0)
[Code] ....
View Replies
View Related
Sep 18, 2014
Write a function that will add the contents of a String array.
1. This time the input array to your function will be an array of Strings.
2. Your function body will be similar except you'll have to convert each String to a double number.
public class SumVals2 {
String aryVals[];
double result;
[Code]....
View Replies
View Related
Mar 28, 2014
I am having difficulty with a sorting routine. I believe that the concept is valid (although not necessarily the most efficient), but I keep running into a problem. I am trying to use the compareTo function to identify the relationship between two values in an array, but it seems to have an issue with it being a comparison of two float values.
Java Code:
for (int x = 0; x < 430; x++) {
for (int y = 0; y < 430; y++) {
if (dataArray[y].compareTo(dataArray[y + 1]) > 0); {
tempOpen = dataArray[y];
[Code] ....
It gives the compile error as follows:
File: C:UsersBradDownloadsAssignment 3Calculations.java [line: 157]
Error: Cannot invoke compareTo(float[]) on the array type float[]
View Replies
View Related
Oct 26, 2014
I have to random shuffle an array of Card Objects which does the funcion of a deck. Heres the code:
Java Code:
public void barajear(){
int j;
for (int i=0;i<52;i++){
j=Baraja.random(51);
if (this.mazo[j]==null){
this.mazo[j]=this.arreglo[i];
}else{
--i;
}
}
} mh_sh_highlight_all('java');
so bassically theres an array called "arreglo" which has the cards in order and the function "random" its an rng of numbers from 0 to 51.what i'm trying to do it's to take the cards from the ordenated array and put them randomly in the other but only if it's empty.(the array "mazo" has alredy been initialized with null).it worked at first, but now, after compiling succesfully i tried to run it and the cmd just...
View Replies
View Related
Apr 8, 2014
How can I find out the simple moving average by just using the numbers stored in an array?
View Replies
View Related
Apr 26, 2015
I am making a very simple 2D array game where the player is asked what size they would like the game board to be. After entering, it displays the board and the player 'P' starts at index [0][0]. After that, they are asked for an action, which can be "up", "down", "left", "right", or "exit". I will be including some extra later (like a treasure at the end, or random obstacles), but for now this is what the game consists of.
I was instructed to "do nothing" when/if the player attempts to go out of bounds. I am trying to simply print an error, such as "Out of bounds! Try again.", then prompt the player again for an action. I even tried to make a boolean method to catch it, but to no avail.
I don't want the exception to occur at all. I just simply want the error message to print to the player and ask for another action. I would prefer not to use try/catch, or try/catch/finally since I already tried that and it still gave the exception error.This program consists of two classes. I will show the class containing the main first, then the client-server type class second.
import java.util.Scanner;
public class Driver {
public static void main(String[] args) {
World world = new World();
boolean keepPlaying;
keepPlaying = true;
boolean isOutOfBounds;
isOutOfBounds = false;
int height = 0;
int width = 0;
int x = 0;
int y = 0;
[code]....
View Replies
View Related
Apr 24, 2014
Having supplied an interface the question arises as to how it should be implemented. There are a number of possibilities including the use of an array list or a linked list; however it is perfectly possible, and in fact instructive, to begin by implementing PhoneDirectory using a simple array of DirectoryEntry objects. This approach is illustrated below:
public class ArrayPhoneDirectory implements PhoneDirectory
{
private static final int INIT_CAPACITY = 100;
private int capacity = INIT_CAPACITY;
// holds telno of directory entries
private int size = 0;
// Array to contain directory entries
[Code] ......
Develop a tester class called ArrayPhoneDirectoryTester . As usual all methods in the class being tested should be executed at least once by the test driver. Supply standard test documentation - Test Plan, Test Data and Test Log.
In addition to the methods described in the interface the class ArrayPhoneDirectory contains three private methods listed below:
// Searches the array of directory entries for a specific name
private int find(String name){}
// Adds a new entry with the given name and telno to the array of
// directory entries
private void add(String name, String telno){}
// Creates a new array of directory entries with twice the capacity
// of the previous one
private void reallocate(){}
These methods can be thought of as "helper" methods in that they assist the work of the public methods of the class. For example, the find() method is used by the lookUpEntry() method to locate the position of the a specific directory entry.
Pseudo-code algorithms for the methods of ArrayPhoneDirectory are listed below
Algorithm for load
create a Scanner to read file
while (not end of file)
use Scanner to read the name
use Scanner to read the telno
create a DirectoryEntry
add the new entry to theDirectory
close file
This method is a good place to start coding but note that load makes use of the add method in case the number of entries stored in the text file has exceeded the initial capacity of the directory. So to implement load fully you will need a working version of the "helper" method add. However you can do this in stages by first developing a basic version of add which does not increase the size of the directory. In reading data from the file you may assume that the file only contains matched pairs of names and numbers. There is no need to consider the case of a name not being associated with a telephone number.
Algorithm for addChangeEntry
call find to see whether name is in directory
if name is in theDirectory
change the telno using setNumber
return the old telno
else
add a new entry to theDirectory using method add
return null
[Code] ....
I don't know how to do any of this at all
View Replies
View Related
Jun 23, 2014
I would use the return value of a function how parameter of other function..In java is:
// the call produce "YES"
SecondClassController.funcSecondClass(FirstClassController.funcFirstClass());
In my web page I need to do something like this:
[...]
<h:outputText value="#{secondClassController.funcSecondClass(#{firstClassController.funcFirstClass()})}" />
[...]
obtain:
javax.servlet.ServletException JBWEB006007: Failed to parse the expression
@Named
@SessionScoped
public class FirstClassController implements Serializable{
[...]
[code]....
View Replies
View Related
May 28, 2014
this program works but returns zero for all the calculations. I checked everything there is no error but I dont know why is returning 0.
package mshproject3;
import java.util.StringTokenizer;
import javax.swing.JOptionPane;
public class HayloFactoryController {
public static void main(String[] args) {
String firstName = "";
String lastName = "";
String phoneNumber = "";
int aNbrOfVehicles = 0;
int aNbrOfFuelTanks = 0;
HayloFactory factory;
[code]....
View Replies
View Related
Oct 21, 2014
I have a routine that returns a boolean. If any of a series of tests fails, the routine returns false, otherwise it returns true. For example, the routine might test for whether or not an integer is both odd and greater than 99, thus:
public boolean oddAndOld(int x)
{
if (x % 2 == 0)
return false;
if (x < 100)
return false;
return true;
}
I like the above because it suggests that "true" is the condition that applies if the incoming parameter meets all the required criteria. But I've sometimes seen this style used:
public boolean oddAndOld(int x)
{
if (x % 2 == 0)
return false;
if (x < 100)
return false;
else
return true;
}
I like this less because, among other things, if that last criterion is removed, the "else/return true" must be moved up into the immediately preceding test (or else leave some funny whitespace, depending on how you go about removing the departing "if" statement), but it does avoid suggesting that "return true" is hard-coded (that is, it reinforces that "true" is a conditional return value, not inevitable).
View Replies
View Related
Jan 26, 2015
I've been trying to make a class that has a toString method that displays the board at the same time displays the value of each index of a 2d character array inside of the code. My professor has made the client print the method. I assumed since he was printing it on the client we had to return a string that gives us this.The number 2 is part of the 2d character array while the rest of the index values are just space characters.
___________
| | | |
|___|___|___|
| | | |
|___|___|___|
| | | |
|___|___|___|
| | | |
|___|___|___|
| 2 | | |
|___|___|___|
I had trouble figuring out how to return this so I started testing it out in another file.
public static void main(String[] args) {
// TODO Auto-generated method stub
char[][] myHidingPlaces;
myHidingPlaces = new char[5][3];
myHidingPlaces[0][0] = 'p';
char play = '1';
for (int i = myHidingPlaces.length-1; i >= 0 ; i--) {
[code]...
View Replies
View Related
Jun 13, 2014
The id variable is the problem Java Code: package com.cjburkey.games.boxee.objects;
import java.awt.Graphics;
import java.awt.Rectangle;
import com.cjburkey.games.boxee.GameState;
import com.cjburkey.games.boxee.resources.Images;
public class Block extends Rectangle {
[code]...
In the constructor, it returns corrent numbers, in the draw method, it returns 0. Why?
View Replies
View Related
Jun 21, 2014
I'm currently having trouble with a Breakout clone that I'm working on when I want to change the scenes of the game. When I start out with the main menu and I hit play, the main menu calls for the StateManager to remove the MainMenu and then to add the GameState to start playing through the levels. But, whenever this is done it just gives a NullPointerException and freezes the game. I know the code for initially starting a State is fine because that is the same way the MainMenu is loaded but there seems to be an issue with changing from one to another...
This is the StateManager class that adds and removes the States/Canvases to and from the JFrame/Main class:
public class StateManager
{
private ArrayList<State> states;
private int currentState;
private JFrame gameFrame;
public StateManager(JFrame gameFrame)
{
this.gameFrame = gameFrame;
states = new ArrayList<State>();
[Code] ....
I've tried messing around with the order of which things are added/loading from the StateManager but am just failing to see what I did wrong.
View Replies
View Related
Nov 23, 2014
Working on chapter 10 of my book which covers exceptions and file I/O. The only part that does not work is line 40 where it is supposed to print getMessage(). It print's null instead of the more verbose error message.
import java.io.*;
import java.util.*;
import java.text.DecimalFormat;
public class SalesReport2
{
public static void main(String[] args)
{
String filename = "SalesData.txt";
int months = 0;
[Code] ....
temp.txt
123.33
asdf
549.85
dsaf
8456.23
21588.22
652.00
My output when using my test file.
ERROR: SalesData.txt does not exist.
Enter another filename: temp.txt
Nonnumeric data found in file: null
The invalid record will be skipped.
Nonnumeric data found in file: null
The invalid record will be skipped.
Number of months: 5
Total Sales: 31,369.63
Average Sales: 6,273.93
I then removed the try catch so that I could get a stacktrace
import java.io.*;
import java.util.*;
import java.text.DecimalFormat;
public class SalesReport2a
{
public static void main(String[] args)
[Code] ...
This was the output.
ERROR: SalesData.txt does not exist.
Enter another filename: temp.txt
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
at SalesReport2a.main(SalesReport2a.java:32)
I also pulled the copy of the code from the CD that came with the book and it's output is the same as my code.
The image in the book shows that the error should be more informative though.
what I get
Nonnumeric data found in file: null
vs
what I should get
Nonnumeric data found in file: For input string: "asdf"
Not sure why it isn't working.
View Replies
View Related
Jun 22, 2014
I'm currently having trouble with a Breakout clone that I'm working on when I want to change the scenes of the game. When I start out with the main menu and I hit play, the main menu calls for the StateManager to remove the MainMenu and then to add the GameState to start playing through the levels. But, whenever this is done it just gives a NullPointerException and freezes the game. I know the code for initially starting a State is fine because that is the same way the MainMenu is loaded but there seems to be an issue with changing from one to another...
This is the StateManager class that adds and removes the States/Canvases to and from the JFrame/Main class:
package com.pathtocreating.Breakout_V2.state;
import java.awt.BorderLayout;
import java.util.ArrayList;
import javax.swing.JFrame;
public class StateManager {
private ArrayList<State> states;
[Code] ....
The code that calls the change of state in MainMenuState is called in the update method:
if(inputController.isMouseClicked("LeftClick")) {
if(playHover) {
soundManager.playSound("ButtonClick");
BreakoutMain.sm.changeStates("GameState");
[Code] ....
Here is the full stack trace when clicking the area to change states:
Exception in thread "Thread-2" java.lang.NullPointerException
at sun.java2d.SunGraphics2D.validateColor(Unknown Source)
at sun.java2d.SunGraphics2D.<init>(Unknown Source)
at sun.awt.image.SunVolatileImage.createGraphics(Unknown Source)
[Code] ...
It gives that same value both before and after clicking on the region.
Printing out b after the State is changed to GameState gives the following:
java.awt.Component$BltSubRegionBufferStrategy@66116674
I've tried messing around with the order of which things are added/loading from the StateManager but am just failing to see what I did wrong.
View Replies
View Related
Jan 30, 2014
I have doubts in string declaration. As I know we can declare string in two ways:
1. String a=new String("Hello");
2. String b="Hello";
What is exact difference between them? Another thing is when I check (a==b) it retuns me false, but when I check a.equals(b) it returns me with true. Why So?
View Replies
View Related
Jun 11, 2014
I have a requirement where I need to read a file with so many carriage return line feeds. Attached is the file I am reading.
I have written a sample application to read the file and and remove these new line feeds but when I execute it, I see the line feed.
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException{
[Code].....
Is there away to achieve this in attached output file?
This is just one record, but I have several records like these.
View Replies
View Related
May 1, 2014
I have to create a program that calculates the nth Fibonacci number and returns that to the user. Fibonacci said his number sequence would describe the ideal breeding patterns of immortal rabbits. So, you are going to make this vision a reality.
First, take in a numeric value from the user and calculate that value in the fibonacci series. Next, find an image of a rabbit and display the image on a GUI (put the image as an icon on a label!) the number of times returned by the algorithm (Put all the aforementioned labels on one panel with FlowLayout!).
You need to remove the old images from the Panel. Probably the easiest way to do this is to create a whole new panel and remove the old one (hint: the remove method of JPanel should come in handy)
You could use an array of JLabels
You will need to create a new JLabel and add each member of the array to the panel
I should be able to scroll to see any images that are off screen
I am having difficultly on to making the array list for JLabel, and getting the Fibonacci sequence to show the pictures of rabbits. Below is my current code.
import java.awt.FlowLayout;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Rabbit extends JFrame
[Code] ....
View Replies
View Related
Jan 29, 2015
My isEmpty method only returns false. Is something wrong? I printed the empty and not empty for testing purposes.
//determines if there are any items in the queue
public boolean isEmpty() {
if (front == -1 && rear == -1) {
System.out.println("empty");
return true;
} else {
System.out.println("not empty");
return false
}
}
View Replies
View Related
Sep 30, 2014
I am doing a homework assignment and I am clueless as to what I did wrong or supposed to do in terms of placement of coding. If someone could dumb down their response and tell me what I did wrong
This is what I supposed to do:
1.) Type the following shell for the class:
public class ParadiseInfo
{
}
2.) Between curly braces of the class, indent a few spaces and create the shell for the main() method:
public static void main(String[] args)
{
}
3.) Between the braces of the main()Method, insert a call to the displayInfo() method:
displayInfo();
4.) Place the displayInfo() method outside of the main() method, just before the closing curly brace for the ParadiseInfo class:
public static void displayInfo()
{
system.out.println ("Paradise Day Spa wants to pamper you.");
system.out.println ("We will make you look good.");
}
This is what I attempted to do: I know it is wrong I am just clueless on where to put the code and why
public class ParadiseInfo
{
displayInfo();
public static void main(String[] args)
{
public static void displayInfo();
}
system.out.println("Paradise Day Spa wants to pamper you.");
system.out.println("We will make you look good.");
}
--- Update ---
I have also tried this:
public class ParadiseInfo
{
displayInfo();
public static void main(String[] args)
{
}
public static void displayInfo();
{
[Code]...
The very last attempt I only ended up with one error which is:
G:ParadiseInfo.java:3: error: invalid method declaration; return type required
displayInfo();
^
1 error
Tool completed with exit code 1
Java is very new to me and I have no clue on what I am doing wrong.
View Replies
View Related