For my project I have a question that says newGenerationNumber an integer. If the argument passed as the parameter is less than zero, set the generationNumber instance variable to zero. Otherwise assign newGenerationNumber to the generationNumber instance variable. I'm confused on how to start this. My code I out is
Private int generationNumber
Then I made a if
If (generationNumber >0)
generationNumber = generationNumber
I'm confused if this is right and if I need to make a else
generationNumber = newGenerationNumber;
if (generationNumber < 0) {
generationNumber = 0;
}
else it stays the way it is
An if...else is a good choice here, but not the only one.
int generationNumber;
public Guppy (int newGenerationNumber) {
if (newGenerationNumber > 0) {
generationNumber = newGenerationNumber;
} else {
generationNumber = 0;
}
}
Instance int primitives have the value of 0 by default. This means that you could leave the else part and only check if it's positive.
It says if the newGenerationInstance parameter (argument) is less than 0.
So I'd probably use the conditional operator (x ? y : z):
public Guppy(int newGenerationInstance) {
this.generationInstance = newGenerationInstance < 0 ? 0 : newGenerationInstance;
}
or alternately you can use if/else if you prefer:
public Guppy(int newGenerationInstance) {
if (newGenerationInstance < 0) {
this.generationInstance = 0;
} else {
this.generationInstance = newGenerationInstance;
}
}
for the simple solution, i would write the code like below
public class NewNumberGenerationClass {
//instance variable because you can access this with the instance of the class
private int NewGenerationNumber;
public NewNumberGenerationClass(int i){
setNewGenerationNumber(i);
}
//setting value before getting it
public void setNewGenerationNumber(int i)
{
if(i < 0)
{
this.NewGenerationNumber = 0;
}
else
{
this.NewGenerationNumber = i;
}
}
//access vaule using get method
public int getNewGenerationNumber()
{
return this.NewGenerationNumber;
}
public static void main(String[] args){
NewNumberGenerationClass s = new NewNumberGenerationClass(-5);
NewNumberGenerationClass s1 = new NewNumberGenerationClass(5);
System.out.println(s.getNewGenerationNumber());
System.out.println(s1.getNewGenerationNumber());
}
}
Related
I've got array. I've got an isFull method, which checks if the array is full, but I don't know how to use this to check if it's full, then if it's not full add to the array, otherwise disregard the add call.
The array should take 10 elements and then not accept any more. After 10 elements, it should 'be full' and disregard any addSpy calls.
How would you implement this?
public class ConcreteSubject extends AbstractSubject {
public int arySize;
private int i = 0;
private static AbstractSpy[] spies;
public ConcreteSubject(int a) {
arySize = a;
spies = new AbstractSpy[a];
}
#Override
public void addSpy(AbstractSpy spy) {
if (spies.length < 10) {
spies[i] = spy;
System.out.println("spy added at index " + i);
i++;
}
}
public void isFull() {
//1
boolean b = false;
for (int i = 0; i < spies.length; i++) {
if (spies[i] == null) {
b = true;
}
}
if (!b) {
System.out.println("Array is full");
} else {
System.out.println("Array not full");
}
}
public class TestSpies {
public static void main(String[] args) {
ConcreteSubject cs = new ConcreteSubject(10);
AbstractSpy spy = new ConcreteSpy();
AbstractSpy[] spies = new AbstractSpy[10];
cs.addSpy(spy);
cs.addSpy(spy);
cs.addSpy(spy);
cs.isFull();
}
}
spies.length < 10 isn't correct. It should be spies.length > 0 && i < spies.length to make sure that the following assignment spies[i] = spy; is always valid.
void isFull() should be boolean isFull(). Your implementation looks OK, just return b. full is a tricky word because technically an array is always "full". A better adjective would be populated, filled.
Since addSpy isn't filling null gaps but simply adds a spy to the end, isFull could be rewritten to return spies.length == i;.
The simplest way of doing it would be like that:
#Override
public void addSpy(AbstractSpy spy) {
if (!isFull())
{
spies[i] = spy;
System.out.println("spy added at index " + i);
i++;
}
}
To use that, you should change your isFull method to:
public boolean isFull() {
for (int i = 0; i < spies.length; i++) {
if (spies[i] == null) {
return false;
}
}
return true;
}
Keep a track of the number of filled cells of the array using a variable. And before inserting anything into it, check if the filled cells count strictly less than the size of the array (obviously you want to keep track of the array total size as well).
getting compile errors and just cannot get this code to work the way I need it to, it's beginning to drive me mad! Basically I am trying to get my boolean array in my method to iterate through the array, find out if False is listed more consecutively or if True is and return either true or false. In my program the array i have listed should return false. Any ideas? thanks in advance.
public class trueOrfalse
{
public static void main(String [] args)
{
boolean[] guess = {false,true,false,false,false,true,true};
boolean result = longerTF(guess);
}
public static boolean longerTF(boolean[] guess)
{
int variable = 0;
for(int x = 0; x < guess.length; x++)
{
if(guess[x] > true)
{
return true;
}
else
{
return false;
}
}
}
i don't know where to start
first of all this is wrong
if(guess[x] > true)
it should be
if(guess[x]==true)
since an if statement expects a boolean result and you have boolean values in your array this will have the same effect
if(guess[x])
you also missed a case. when the array is empty you would never run into the for loop, but your method still needs to return a boolean value. you could throw a runtime-exception or a default value like return false; at the end of your method
your for-loop does not make sense, since your method will return a result within the first iteration (if the array is not empty). your longerTF method could be also looking like this
public static boolean longerTF(boolean[] guess) {
if(guess.length>0)
return guess[0];
throw new IllegalArgumentException("The array must not be empty");
}
i'd suggest a general book like "programming: Learn the Fundamentals of Computer Programming Languages". you need to understand first the basics of programming before you try to implement anything.
The comparison​ operators >, etc., are neither legal nor meaningful for boolean operands. What did you intend guess[x] > true to accomplish?
Since guess is a boolean[] you are allowed to test
if (guess[x])
or
if (! guess[x])
and to
return guess[x];
EDIT
You want the loop to count consecutive values. This loop does not, but it shows how such a structure works for a simpler problem.
public boolean dominant(boolean[] guess) {
int tCount = 0;
for (int ix = 0; ix < guess.length; ++ix) {
if (guess[ix]) {
++tCount;
}
}
return tCount >= guess.length / 2;
}
Here is a "corrected" version:
public class trueOrfalse {
public static void main(String[] args) {
boolean[] guess = { false, true, false, false, false, true, true };
boolean result = longerTF(guess);
}
public static boolean longerTF(boolean[] guess) {
int variable = 0;
for (int x = 0; x < guess.length; x++) {
if (guess[x]) {
variable++;
}
}
return (variable > (guess.length-variable));
}
}
You forgot one closing braket }, a return statement and boolean compare cannot be with < or >.
As mentioned by everyone above. You can't use > to compare two booleans.
For your purpose to count the number of consecutive true/false, you need two different counters. You can run a loop and keep incrementing the counter as you encounter repeated item of true/false, if not you can just reset the counter to 1. I have put on a hasty solution below to give you an idea. I haven't tested it well it seems to work. Hope this helps.
public class trueOrfalse {
public static void main(String[] args) {
boolean[] guess = { false,true,false,false,false,true,true };
boolean result = longerTF(guess);
System.out.println("result: " +result);
}
public static boolean longerTF(boolean[] guess) {
int consecutiveFalseCount = 1;
int consecutiveTrueCount = 1;
for (int x = 0; x < guess.length; x++) {
if (guess[x] == true) {
if(x!=0 && x<guess.length){
if(guess[x-1] == true){
consecutiveTrueCount = consecutiveTrueCount + 1;
} else {
consecutiveTrueCount = 1;
}
}
} else {
if(x!=0 && x<guess.length-1){
if(guess[x-1] == false){
consecutiveFalseCount = consecutiveFalseCount + 1;
} else {
consecutiveFalseCount = 1;
}
}
}
}
System.out.println("Consecutive True count: " +consecutiveTrueCount);
System.out.println("Consecutive False count: " +consecutiveFalseCount);
if(consecutiveTrueCount>consecutiveFalseCount){
return true;
} else {
return false;
}
}
}
I'm still a little confused with regards to the difference between static and dynamic. From what I know dynamic uses object while static use type and that dynamic is resolved during runtime while static is during compile time. so shouldn't this.lastName.compareTo(s1.lastName) use dynamic binding instead?
key.compareTo(list[position-1]) use dynamic binding
public static void insertionSort (Comparable[] list)
{
for (int index = 1; index < list.length; index++)
{
Comparable key = list[index];
int position = index;
while (position > 0 && key.compareTo(list[position-1]) < 0) // using dynamic binding
{
list[position] = list[position-1];
position--;
}
list[position] = key;
}
}
Why does (this.lastName.compareTo(s1.lastName)) use static binding?
private String firstName;
private String lastName;
private int totalSales;
#Override
public int compareTo(Object o) {
SalePerson s1 = (SalePerson)o;
if (this.totalSales > s1.getTotalSales())
{
return 1;
}
else if (this.totalSales < s1.getTotalSales())
{
return -1;
}
else //if they are equal
{
return (this.lastName.compareTo(s1.lastName)); //why is this static binding??
}
}
Your question isn't complete and doesn't include all relevant the code. However this is the basic difference between the different bindings
Java has both static and dynamic binding. Binding refers to when variable is bound to a particular data type.
Static/Early binding is done at compile time for: private, final and static methods and variables. And also for overloaded methods
Dynamic/late binding is done at runtime for: methods which can be overriden methods. This is what enables polymorphic behaviour at runtime.
To further demonstrate this point have a look at this code and see if you can determine when it would be early and late binding:
/* What is the output of the following program? */
public class EarlyLateBinding {
public boolean equals(EarlyLateBinding other) {
System.out.println("Inside of overloaded Test.equals");
return false;
}
public static void main(String[] args) {
Object t1 = new EarlyLateBinding(); //1
Object t2 = new EarlyLateBinding(); //2
EarlyLateBinding t3 = new EarlyLateBinding(); //3
Object o1 = new Object();
Thread.currentThread().getStackTrace();
int count = 0;
System.out.println(count++);
t1.equals(t2);//n
System.out.println(count++);
t1.equals(t3);//n
System.out.println(count++);
t3.equals(o1);
System.out.println(count++);
t3.equals(t3);
System.out.println(count++);
t3.equals(t2);
}
}
Answer:
++ is after the count and hence the result returned is the 0 before incrementing it. Hence starts with 0 and proceeds as you expect.
The only scenario where the equals methods of EarlyLateBinding object
is actually invoked is is statement 3.
This is because the equals method is overloaded (Note: the different
method signature as compared to the object class equals)
Hence the type EarlyLateBinding is bound to the variable t3 at
compile time.
.
in this code
public static void insertionSort (Comparable[] list)
{
for (int index = 1; index < list.length; index++)
{
Comparable key = list[index];
int position = index;
while (position > 0 && key.compareTo(list[position-1]) < 0)
{
list[position] = list[position-1];
position--;
}
list[position] = key;
}
}
key can be anything that implements the Comparable interface so in the compile time compiler doesn't know the exact type so type is resolved in the runtime by using the object that key referring to.
But in this code,
#Override
public int compareTo(Object o) {
SalePerson s1 = (SalePerson)o;
if (this.totalSales > s1.getTotalSales())
{
return 1;
}
else if (this.totalSales < s1.getTotalSales())
{
return -1;
}
else //if they are equal
{
return (this.lastName.compareTo(s1.lastName));
}
}
compiler knows the type of the s1 so it use the static binding
This may be a very simple question, but I can't seem to find a suitable answer on Google. I have a class called Player, which has a String array called playerInv with a size of 10.
In my Main Activity Class, I want to run a for loop to determine the first index in the array that is empty (""). I then want to populate that with a new string, and then terminate the loop. How do I do this?
Sorry for the nooby question. Like I said, I've tried Google to no avail!
For Loop:
String playerInvTemp[] = thePlayer.getPlayerInv; ERROR -- cannot resolve getPlayerInv
for (int i=0; i < playerInvTemp.length; i++)
{
if ((!playerInvTemp[i].isEmpty()) || playerInvTemp[i] == null)
{
setPlayerInv("Blood Essence", i); ERROR cannot resolve setPlayerInv
//invText.setText();
Blood = true;
break;
}
}
Player Class:
public class Player {
private int playerPos;
private int playerHP;
private String playerInv[];
Player(int startPos, int startHP, String[] newInventory)
{
playerPos = startPos;
playerHP = startHP;
playerInv = newInventory;
}
public int getPlayerPos() {
return playerPos;
}
public void setPlayerPos(int playerPos) {
this.playerPos = playerPos;
}
public int getPlayerHP(){
return playerHP;
}
public void setPlayerHP(int playerHP){
this.playerHP = playerHP;
}
public String getPlayerInv(int pos)
{
return playerInv[pos];
}
public void setPlayerInv(String playerInv[]) {
for (int i=0; i<10; i++)
{
this.playerInv[i] = playerInv[i];
}
}
public void setPlayerInv(String val, int index)
{
this.playerInv[index] = val;
}
public String getPlayerInv()
{
return this.playerInv; *//this gives error "Incompatible types. Required java.lang.string, found java.lang.string[]"*
}
}
Do this
Add these two method in Player class
public void setPlayerInv(String val, int index)
{
this.playerInv[index] = val;
}
public String[] getPlayerInv()
{
return this.playerInv;
}
then change your for loop like this
String playerInvTemp[] = thePlayer.getPlayerInv();
for (int i=0; i < playerInvTemp.length; i++)
{
if (!playerInvTemp[i].isEmpty()) || playerInvTemp[i] == null)
{
setPlayerInv("Blood Essence", i);
//invText.setText();
Blood = true;
break;
}
}
Bunch of problems here, .length() is not valid for an array, it should be .length.
`for (int i=0; i<thePlayer.getPlayerInv(i).length(); i++)`
You most likely mean null or at least need to check for it, here and you need [] not ():
if (thePlayer.getPlayerInv[i] == "" or theplayer.getPlayerInv[i] == null)
This is all wrong, and as a matter of fact you need to post your code and errors, you have many problems and should start with learning some basics about Java.
Try some beginners tutorials (https://www.google.com/search?q=java+tutorials&ie=utf-8&oe=utf-8). You have a lot of both syntax and logic errors.
Do you run an instance of constructor player()??
I did
Player a=new Player();
a.getPlayerInv(0)
and works fine.
First my call back to increment I know is not correct. I am not sure what to do. I need increment to use temp when it hits that case that requires that call back. I can't change increment to pass a parameter into it because the graders test script wont allow for it. The second problem is that it wont increment any input. For instance if you just call increment on the number 23 it just returns 23. The test script for the grader looks something like this:
public class TestBigNaturalSimple {
public static void main(String[] args) {
BigNatural b1 = new BigNatural(); // default constructor
BigNatural b2 = new BigNatural(23); // one-argument int constructor
BigNatural b3 = new BigNatural("346"); // one-argument String constructor
BigNatural b4 = new BigNatural(b2); // one-argument BigNatural
// constructor
b1.increment();
b3.decrement();
System.out.println(b1.toString()); // should print out 1
System.out.println(b4.toString()); // should print out 23
}
}
My code is:
public class BigNatural {
private String num;
public BigNatural(String input) {
num = input;
}
public BigNatural(BigNatural input) {
num = input.toString();
}
public BigNatural(Integer input) {
num = input.toString();
}
public BigNatural() {
Integer i = 0;
num = i.toString();
}
public void increment() {
Integer first = 0;
Character ch = num.charAt(num.length()-1);
Integer last = Character.digit(ch, 10);
if (num.length() > 1)
{
if (last < 9) {
last++;
}
else
{
if (num.length() >= 2)
{
last = 0;
String temp = new String(num.substring(0, num.length()-2));
increment();
}
else
{
last++;
}
}
}
else
{
if (last < 9)
{
last++;
}
else
{
last = 0;
first = 1;
}
}
String t = last.toString();
if (first > 0)
{
String x = first.toString();
num.concat(x);
}
num.concat(t);
}
public void decrement() {
Character ch = num.charAt(num.length()-1);
Integer last = Character.digit(ch, 10);
if(num.length() > 1)
{
if(last == 0)
{
String temp = new String(num.substring(0, num.length()-2));
decrement();
}
else
{
last--;
}
}
else
{
if(last > 0)
{
last--;
}
else
{
last = 0;
}
}
String t = last.toString();
num.concat(t);
}
public String toString() {
return num;
}
}
That has to be the most complicated way to increment a number I have ever seen. ;) I assume you have to do it that way.
From what I can see you don't change num anywhere. I would expect this to be obvious if you used a debugger. ;)
Try using num = num.concat(t) if you expect num to change.
Note: String is immutable so you cannot change it, you can only replace it.
EDIT: Here is a version provided for your own interest. Your professor will know you didn't write this, so don't copy it. ;)
public void increment() {
num = increment(num);
}
private static String increment(String s) {
if (s.length() <= 0) return "1";
char ch = s.charAt(s.length() - 1);
String top = s.substring(0, s.length() - 1);
return ch < '9' ? top + ++ch : increment(top) + '0';
}
Strings are immutable in Java. Hence, the code
num.concat(t);
in your increment method will not do what you expect.
First, apply the rule don't repeat yourself:
to increment is to add 1
to decrement is to add -1
Thus you simply need to write on function that takes a number as input and add it to your BigNatural:
public void increment() {
add(1);
}
public void decrement() {
add(-1);
}
private void add(int i) {
// Your homework here ...
// You will have only one function to debug and correct, not 2
}
Second: as pointed in other answers, num.concat(t); does not do what you expect, you'll need num = num.concat(t);. Always refer to the Java documentation when you use a function you don't know. If you don't have an editor that allows you to debug your programs, I strongly suggest you get one: Eclipse for instance but other editors might be better as learning tool. The added benefit is that the tools will format the code for you, warn you about lots of mistakes, ...