Cannot Set Ints From Constructor

Aug 10, 2014

Java Code:

package ZooZ;

import java.util.Random;
public class Animal {
int playerOne; <------- Remains 0
int playerTwo; <------- Remains 0
Random random = new Random();

[Code] ....

If you look at the code, I set "playerOne" and "playerTwo", to set them as what was passed in from another class..

In the Animal constructor.

in that constructor the value is 2. But when I use it in the "Bash()" method it is 0 in the console.

Why doesnt the playerOne and playerTwo stay the value it is assigned in the constructor.??

View Replies


ADVERTISEMENT

Changing Ints From Another Class

Jun 27, 2014

I am making a simple text based game and i have a monster, and I am tring to make its health go down whent he user input "s" but istead it doesnt change and the users health even goes up.

Main.java

package exodus.game.main;
import java.util.Scanner;
import exodus.game.monsters.Nirav;
public class Main {
static String name;
static String inputtemp;

[Code] .....

View Replies View Related

String To Ints Separated By Comma?

Feb 5, 2014

public Date(String s) {
???????
}

such that

Date("1250/345/759")

it will return

(1250,345,759)

in short Date("a/b/c")

return (a,b,c)

View Replies View Related

Array / List Of Ints Contains Specific Number

Jan 24, 2014

I've been trying to make a list of numbers/ints and later on check that list for a specific number.

View Replies View Related

Subtracting Strings - Parsing Two Values To Ints

Nov 5, 2014

I have started learning Java and have some across some difficulties. I'm trying to subtract two strings.

for example, with these strings;"032"&&"100". I want to be able to subtract each number individually so that the answer would be "032". 0-1;3-0;2-0;. if i get a negative number, the number would be zero. hence, the 0-1 staying zero in the answer.

I have tried using substring, and parsing the two values to ints, but don't know what to do next. I have also tries using a for loop, to go through each arrays of the strings. I am not allowed to use StringBuilder and I need to return "032".

Here's what i've done so far:
 
public static String appliquerCoup( String combination, String coup ) {
String nouveauCoup=""; 
if(combination!=null&&coup!=null){
for(int i=0;i>combinaison.length();i++){

[Code] ....

View Replies View Related

Calculating Average Of Two Ints And Converting To A Double

Oct 31, 2014

I have been asked to construct an application that will read in the exam mark and coursework mark and then print out to 1 decimal place the average of the coursework and exam mark. When I submit it it says it's incorrect.

class Main
{
public static void main( String args[] )
{
int ExamMark=71;
int CourseworkMark=40;
double mark = (double)(ExamMark + CourseworkMark) / 2;

[Code] ....

View Replies View Related

Calculating Average Of Two Ints And Converting To Double In Java?

Oct 31, 2014

how to use Java and for my coursework I have been asked to construct an application that will read in the exam mark and coursework mark and then print out to 1 decimal place the average of the coursework and exam mark. When I submit it to the coursework submission system it says it's incorrect.

The answer that it's asking for is the answer that my code produces (ex = 71 cw = 40 mark = 55.5) But for some reason it says this when I submit it:

-#### << Differences between expected (<) your answer (>) >> ------------
1c1
< ex= 91 cw = 80 mark = 85.5
---
> ex = 71 cw = 40 mark = 55.5
-------------------------------------------------------------------------

Check the above output for why this attempt failed And when I change the ex to 91 and cw to 80 it asks for > ex = 71 cw = 40 mark = 55.5 again.

class Main
{
public static void main( String args[] ) {
int ExamMark=71;
int CourseworkMark=40; 
double cost = (double)(ExamMark + CourseworkMark) / 2;
  System.out.printf("ex = " + ExamMark + " cw = " + CourseworkMark + " mark = " + cost);
System.out.println();
  }
 }

View Replies View Related

Creates Array Of 3 Consecutive Ints (0 - 7) User Has To Guess What Those Numbers Are

Aug 16, 2014

I have the following program. In a nutshell, I creates an array of 3 consecutive ints and the user has to guess what those numbers are, knowing that they are between 0 and 7, this is from Head First Java. In the book, the code has a bug that is made on purpose and they challenge you to fix it. As you can see bellow, every time a user's guess matches a int in the array, the NumOfHits is increased by one. When the NumOfHits is 3 (the length of the array) the game finishes.

The bug is that if you guess 1 and 1 is in the array, if you type in 1, 3 times, I will increase the NumOfHits 3 times and end the game as if you had won. To solve the bug, you need to find a way to tell the program that if the user already guessed that number, it should no longer be taken into account and we shouldn't increase the NumOfHits if the same number is provided.

I "fixed" this by searching for the index of the number that matches an int of the array, and changing that index's value to 100, since the user knows that the numbers are between 0 and 7, they will not submit 100.

The result? If the user submits 2 and 2 is in the array, the value of its indexed is replaced by 100, so that if the user submits 2 again it doesn't count as a match.

Please see the comments in the code

import java.io.*;
import java.util.Arrays;

class DotCom{
int NumOfHits = 0;
int[] LocationCells;
public void setLocationCells(int[] locs){
LocationCells = locs;

[Code] .....

The code works, but for some reason, some times I get a ArrayIndexOutOfBoundsException run time error and it appears to be somehow random. This is what I saw on the command line earlier

C:Userspablo.alvarez>java launchDotCom

Enter a number: 3
missed
Enter a number: 4
hit
Enter a number: 5
hit
Enter a number: 7
missed
Enter a number: 5
missed
Enter a number: 4
missed
Enter a number: 3
missed
Enter a number: 4
missed
Enter a number: 5
missed
Enter a number: 6

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at DotCom.checkYourSelf(launchDotCom.java:16)
at DotComGame.startGame(launchDotCom.java:59)
at launchDotCom.main(launchDotCom.java:72)

As you can see here, 3 returned 'missed' but 4 and 5 returned hit. Since the numbers are in sequence and are only 3, it makes sense that the last number is 6 (4,5,6). You will then notice that when I submitted 3 and 4 again it returned 'missed' as expected, because the numbers were already matched earlier, but then when I submitted 6, it returned the error seen above.

Sometimes this doesn't happen at all, sometimes it happens at the 2nd guess or third, it appears to be somehow random. I'm familiar with the error message, but I don't see where I'm using an index that doesn't exist in the array. The only time I'm referencing an array index is on

LocationCells[index] = 100;

but the index variable will only hold a value if the int submitted by the user matches on of the values in one of the indexes, so how is it that I'm going over the number of available indexes?

View Replies View Related

User Input 2 Ints - Output True If One Is In Range Otherwise False

May 14, 2014

How do I make it so that if both numbers are entered between 10 and 20 it will print false?

The assignment: Ask the user to enter 2 ints. Output "true" if one of them is in the range 10 - 20 inclusive, but not both. Otherwise output "false"

12 99 → true
21 20 → true
8 99 → false
15 17 → false

import java.util.Scanner;
 public class Practice {
 public static void main(String[] args) {
 //get user input
Scanner user_input = new Scanner(System.in);
System.out.print("Enter a number: " );

[Code] ....

View Replies View Related

Accept Array Of Ints And Squares Each Element Of Array

May 13, 2014

I need to write a method that accepts an array of ints and squares each element of the array. No creating new arrays and no returning any values.

public void squareInts(int[] ints) {
for(int i = 0; i < ints.length; i++) {
ints[i] = (ints[i] * ints[i]);
}
}

View Replies View Related

Non-Parameter Constructor Calls Two Parameter Constructor

Apr 19, 2014

I was practicing my java skills and came across an exercise in which a non parameter constructor calls a two parameter constructor. I tried a few searches online but they all came back unsuccessful. This is the part I am working on:

public PairOfDice(int val1, int val2) {
// Constructor. Creates a pair of dice that
// are initially showing the values val1 and val2.
die1 = val1; // Assign specified values
die2 = val2; // to the instance variables.
}
public PairOfDice() {
// Constructor that calls two parameter constructor
}

I tried calling the two constructor using the line "this(val1, val2)" but I get an error because val1 and val2 are local variables.

Then I tried to use the same signature: "this(int val1, int val2)" but that didn't work either.

View Replies View Related

Constructor For Arrays

Apr 23, 2015

I'm wonder about the issue of constructor for arrays. Let say I have a class tablica, and one component int[] tab. If I get it right until now tab is nothing more than empty reference to some unexisting array?

import java.util.Random;
class tablica{
int[] tab;
tablica (){ // i wish it was constructor

[code]....

Then, I'm trying to build the constructor for class tablica. What can be the parameter of such constructor? Is it fields of array? It is simple forf for basic variable

- I liken values defined in constructor with those global defined in class. But how to do it with array component tab.

If I create array object in main method then how can I use this constructor?

View Replies View Related

Constructor With Parameters

Jan 31, 2015

public class TestClass {
public TestClass(String k){System.out.println(k);}
public static void main(String[] args) {
try {
hello();
}
catch(Exception e){System.out.println(e);}

[Code] ....

Explain how to catch block act as constructor with parameter?

View Replies View Related

Why Constructor Cannot Be Final

Oct 27, 2014

"A constructor cannot be abstract, static, final, native, or synchronized."

I understand on why it can't be all of the above, except "final".

Why can't we have a final constructor, i understand constructors are not inherited, hence no chance/case of overriding etc. But why is it not allowed at all ?

View Replies View Related

No Such Constructor Error

Oct 27, 2014

So I am working on a school project and I have 2 classes, class FakeGravity contains all the properites and class BouncyBall is my driver class. For some reason when I try writing

FakeGravity gravity = new FakeGravity( );

I get an error. I am attaching an image of the error, and also attaching the program just in case you need more information. Also I was using blueJ to write the program

dcasarrubias, on 27 October 2014 - 02:44 PM, said:

So I am working on a school project and I have 2 classes, class FakeGravity contains all the properites and class BouncyBall is my driver class. For some reason when I try writing

FakeGravity gravity = new FakeGravity( );

I get an error. I am attaching an image of the error, and also attaching the program just in case you need more information.

View Replies View Related

No Default Constructor

Nov 2, 2014

The LocalStudent class inherits the Student class. The IDE states an error of "no default constructor in Student class".I understand that if a LocalStudent object is created, the default constructor of its superclass (aka Student class) will be called implicitly.there is no LocalStudent object being created, so why is the default constructor of Student being called ?

The default constructor of LocalStudent is also overloaded by the created no-arg constructor containining subjects = null; . So there is no call to the superclass default constructor from the default constructor of LocalStudent.

public class Student {
private char year1;
public Student(String name, char year){
year1 = year;
}
public char getYear(){
return year1;

[code]...

View Replies View Related

Radius Value Becoming Zero In Constructor

Jul 8, 2015

I am trying to create a user defined Exception. I am using a hard-coded value in the constructor of circle class at the time of object creation.But in the constructor this value becomes 0.

import java.lang.Exception;
import javax.swing.*;
class InvalidRadiusException extends Exception{
private double r;
public InvalidRadiusException(double radius){
r = radius;

[Code] ....
 
Due to this its always generating InvalidRadiusException even if i am supplying a non-zero non-negative value.

View Replies View Related

Adding Validation To A Constructor?

Nov 17, 2014

I want to add validation to some of the elements in my constructor.

Person(String idIn, String nameIn, ) {
this.id = idIn;
this.name = nameIn;
}

I want to be able to check that the data for the ID is limited to a certain collection of characters formatted in a certain. For example, I may wish to limit it to 5 lowercase letters or numbers, or a combination of both. How could I do this?

View Replies View Related

Constructor In Abstract Class?

Jun 23, 2014

Do we have constructor in abstract class? If we have then what is the use of it?

View Replies View Related

Overloaded Constructor Not Being Implemented?

Oct 21, 2014

For some reason, even though I am giving it the correct number of arguments for the constructor to be initalized it doesn't go through. I end up with a compile error:

PatientBuilder.java:17: error:

constructor Patient in class Patient cannot be applied to given types;
Patient aPatient = new Patient(bloodType, rhFactor, ID, age);
^
required: no arguments
found: String,String,int,int
reason: actual and formal argument lists differ in length

And I'm not understanding how that's possible when it calls for 2 strings and 2 ints and that's what I am passing.

I have this in my main method Scanner inputDevice = new Scanner(System.in);

System.out.println("What is the patients ID number?");
int ID = inputDevice.nextInt();
System.out.println("What is the patients age?");
int age = inputDevice.nextInt();

[Code] ....

And then here are my two constructors, one default and one overloaded.

public Patient() {
patientBlood = new BloodData();
ID = 0;
age = 0;
bloodType = "O";
rhFactor = "+";

[Code] .....

View Replies View Related

Stuck On Constructor With Parameters

Mar 19, 2014

How to use a constructor with parameters where the user inputs the information? I'm doing a problem where I create a Delivery class that accepts arguments for the year, delivery number within the year, distance code (1 for short distance, 2 for long), and weight of package. The constructor is supposed to also determine the eight digit delivery number (combining the year and delivery number, like 20140054 for this year, package #54).

I know I'm not close to being done but I'm struck on the application with the constructor parameters. If I'm asking the user to input the information, does that mean I have to create a no argument constructor so it will compile? Right now it won't compile because it's asking for the parameters but I can't put them.

This is the class:

public class Delivery {
int year;
int delNum;
double weight;
int code;

[Code] .....

And the error is:

CreateDelivery.java:22: error: constructor Delivery in class Delivery cannot be applied to given types;
Delivery firstDelivery = new Delivery();
^
required: int,int,int,double
found: no arguments
reason: actual and formal argument lists differ in length
1 error

View Replies View Related

Returning Data From A Constructor?

Sep 1, 2014

I'm having an issue returning data from a constructor. This is an assignment, and the specifications were that two classes are to be used, one for the variables and assigning methods, and one for the main method and the printing. This app compiles, but returns "0" for the isbn number, and I'm sure it's because I'm not doing something right with my constructors. My code is below

public class Book {
/* Declare Variables */
public static int isbn;
/* Constructor */
public Book (int isbn) {
isbn = 454545;

[code]....

There are other variables to add, but if I can get one working, I can get the rest working.

View Replies View Related

Sending Two Strings Into A Constructor

Jun 13, 2014

I did this using ArrayList<String> and my tests worked. Meaning I was able to read the strings in a different class through my constructor. However I want to use a string array because it will be easier to handle when I finish the program. I will send each players poker hand in and figure out who is the winner instead of putting it all onto a ArrayList and having to iterate through it. However whenever I did my check I am just printing null.

PokerFile class

void separateHands(String cards) {
//ArrayList<String>playerOne = new ArrayList<String>();
//ArrayList<String>playerTwo = new ArrayList<String>();
String[] playerOne = new String[10];
String[] playerTwo = new String[10];
 
[Code] .....

ignore the boolean methods I was just building the structure of the program. The print file is what is outputting this:

null
null
null
null
null
null

public class WinningHand extends PokerFile {
//ArrayList<String> p1 = new ArrayList<String>();
//ArrayList<String> p2 = new ArrayList<String>();
String[] p1 = new String[6];
String[] p2 = new String[6];
WinningHand(String[] p1,String[] p2)

[Code] ....

View Replies View Related

How To Scan Input And Use It In A Constructor

Oct 2, 2014

what weapon the user wants to use and set the element of the Player but I can't use defineWeapon() inside of the constructor so what can I do?here's the player class (where I need to set the element which is the second string in the constructor

package netHackDessart;
import java.util.Scanner;
public class Player extends Monster {
public Player()
{
super("player", "null", 18, 6, 150, 4, 1, 6, 1, 8, 1, true, false);

[code]....

View Replies View Related

Return Statement In A Constructor

Jan 8, 2014

What is the difference between two statements:

Class1 class1 = new Class();
class1 = Class2.method1();

and

Class1 class1 = Class2.method1();

I have one more query on the same lines ... I always need to call the method1 of Class2 whenever i create a object of class1. So I wanted to go with the constructor in Class1. But the method1 in Class2 has a return statement. so is there any better way to do this other than constructors.

Sample code:

public int class Class2{
public static method1(){
return 2;
}
}
public class Class1{
public Class1(){
Class2.method1();
}
}

View Replies View Related

How To Get A Variable From Constructor Into Another Method

Nov 11, 2014

I am having an issue with a small part of my project. i am supposed to make a hash table with a file containing words. The file is being passed into my constructor, where i basically just all it "filename" of type string. Im supposed to get the contents of the file and put it into the table. the problem I'm having is making the connection between my constructor and a method called "start" which basically does all the work. Im not sure how to go by doing this, how could i use the variable "filename" from my constructer in my start method?:

import java.io.*;
import java.util.*;
public class WordCount {
//private fields, including your HashMap variable
HashMap<String,Object> hmap =new HashMap<String,Object>();//(table size,load factor)
public WordCount( String infileName){
String filename =infileName;

[Code] .....

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved