first time posting here, I have this problem:
Write a static method named mostBowlsFull, to be added to the Bowl class, which is passed an array of Bowl objects, and returns true if a strict majority of the Bowls in the array are not empty. Thus if the array consists of 11 bowls and 6 are not empty, your method should return true, but if the array consists of 12 bowls and 6 (or fewer) are not empty, your method should return false.
we are given the class here:
https://cesd12.cs.umass.edu/owlj/servlet/ContentFileServer?ID=10778&ManuallyGraded=0&SecureID=2084635103&Server=owl-ijava31haverhillhs&TsActn=1422069785&datasrc=OwliJava31HaverhillHS&fileRequestID=4147
Not sure if it is accessible or if you must be logged on to the service :/
Anyways, this is the code I have
`public static boolean mostBowlsFull(Bowl bowls[]){
int count = 0;
for(int j = 0; j < bowls[].length(), j++){
if(bowls[j].getEmpty == true){
count++;
}
}
if(count > (bowls[].length()/2)){
return true;
}
}`
I am getting for feedback:
The system has detected compilation errors. This could be caused by:
Missing semicolon ; at the end of a statement.
Unclosed braces {}.
Unclosed parentheses ().
Unterminated string literals "".
Invalid method signature.
Missing return statement.
Redeclared variable or data member.
etc.
Any noticeable errors?
EDIT: Alright, so after review I have
public static boolean mostBowlsFull(Bowl bowls[]){
int count = 0;
for(int j = 0; j < bowls.length; j++){
if(bowls[j].getEmpty() == true){
count++;
}
}
if(count > (bowl.length/2)){
return true;
}
}
Still receiving the same message, although I do understand everything that was pointed out, thank you.
It will be easier and less time taking for you to use an IDE and resolve compilation errors.
I see two errors in your for loop:
for(int j = 0; j < bowls[].length(), j++){
use of comma instead of semicolon. for loop syntax is
for (initialization; termination; increment) {
statement(s)
}
Also length is a property for arrays and not a method. So use bowls.length instead of bowls[].length. Also not that you don't need [] while using length.
If you're trying to get the length of bowls, use bowls.length, not bowls[].length().
Also, in your for loop you need a semi-colon in between all three statements:
for(int j = 0; j < bowls.length; j++){ ... }
public static boolean mostBowlsFull(Bowl bowls[]){
int count = 0;
boolean ret=false;
for(int j = 0; j < bowls.length; j++){
if(bowls[j].getEmpty() == false){
count++;
}
}
if(count > (bowls.length/2)){
ret=true;
}
return ret;
}
Related
I was wondering what would be a real difference between setting up code like this
public boolean stringE(String str) {
int count = 0;
for (int i =0; i < str.length(); i++) {
if (str.charAt(i) == 'e') {
count += 1;
}
}
return (count >=1 && count<=3 );
}
and this
public boolean stringE(String str) {
for (int i =0; i < str.length(); i++) {
int count = 0;
if (str.charAt(i) == 'e') {
count += 1;
}
}
return (count >=1 && count<=3 );
}
I know the first one is right but what would make it difference by setting "int count =0" inside "for loop". Wouldn't it still add 1 to the count =0 ?
The second case won't compile, since count won't be recognized in the return statement, since the scope of the count variable is only inside the for loop in that case.
That's why you have to declare count outside the for loop.
Another problem with the second case, as mentioned by Dici, is that you reset count to 0 in each iteration of the loop, which means the loop wouldn't count what it is supposed to count.
In second case, the variable count is not visible outside for loop so that will create error at return statement. Also the logic is wrong since it will get reset everytime.
You can always try - and in this case, you might notice that the second one won't compile. It's syntactically incorrect.
In Java, when you define a variable, it only exists in the scope of the braces {} it's defined in. If you define a variable inside a loop, it only exists inside the loop. You can't use count outside the braces it's defined in.
Also, I doubt even the first program is semantically correct - you always return during the first iteration, which is unlikely to be what you want.
I'm putting together a code for a hailstone sequence I found in an online tutorial, but in doing so I ran into an unreachable statement error. I don't know if my code is correct and I don't want advice in correcting it if I'm wrong(regarding the hailstone sequence, I want to do that myself..:) ). I just want help in resolving the "unreachable statement" error at line 19.
class HailstoneSequence {
public static void main(String[] args) {
int[][] a = new int[10][];
a[0][0] = 125;
int number = 125;
for (int i = 0;; i++) {
for (int j = 1; j < 10; j++) {
if (number % 2 == 0) {
a[i][j] = number / 2;
number = number / 2;
} else {
a[i][j] = (number * 3) + 1;
number = (number * 3) + 1;
}
}
}
for (int i = 0;; i++) {
for (int j = 0; j < 10; j++) {
System.out.println(a[i][j]);
}
}
}
}
This is an infinite loop:
for(int i=0;;i++){
Whatever comes after it never get executed (i.e. is unreachable).
In your first for loop:
for(int i=0;;i++){
....
}
You do not define the ending condition. e.g.
for(int i=0; i<10; i++){
....
}
Therefore the loop never exits.
Your first infinite loop of for(int i=0;;i++) stops any other code from being reached.
There is an infinite loop # line 7
You forgot to set an exit condition
for(int i=0;here;i++){
This might create unexpected behaviour.
Your first for statement (in the 6'th line) is an infinite loop therefore it stops further code to be reached.
for(int i=0;;i++)
You have problem at line number 6 in your first for loop.
for(int i=0;;i++) {
Here since your don't have any exit conditions, code is going in the infinite loop and the loop never exits. Whatever outside the scope of this for loop will be unreachable since your first loop is never existing.
Consider adding the exit condition (such as break or return etc.) inside your for loop to prevent this behavior.
So basically, I've created a contains method and it prints out the correct output I need but after it does this it gives me an error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at MethodTesting.main(MethodTesting.java:90)
Not sure why when it displays the output no worries? If anyone can give me an idea of what i'm doing wrong?? My code is below, i've tried adjusting the length to just length and length-1 as seen below. I've written the code in strings as opposed to char arrays however it wouldn't give me the right result. Hoping someone can shed some light perhaps?
//contains method
char[] st = "Hello World".toCharArray();
char[] substr = "llo".toCharArray();
for(int contains=0; contains<st.length-1; contains++){
if(substr[contains] == st[contains]){
for(int j=contains; j<st.length-1; j++){
if(st[j] == substr[j]){
}
else{
contains = -1;
}
}
}
System.out.println("CONTAINS");
System.out.println(contains);
}
Thanks, in advance!
Assuming that you are trying to search a substring of a string, this can be done in String.contains() method. If you are trying to implement the method yourself, then you have to change your code like this:
public static void main (String[] args)
{
char[] st = "Hello World".toCharArray();
char[] substr = "llo".toCharArray();
for(int contains = 0; contains < st.length - substr.length; contains++) {
int j;
for(j = 0; j < substr.length; j++) {
if(st[contains + j] != substr[j]) { // mismatch
break;
}
}
if (j == substr.length) // Every character in substr has been matched
System.out.println("Contains");
}
}
Your arrays aren't of equal length, yet in your second loop, you make an assumption that they are. contains can be a value higher than substr.length, and consequently, j will be, too.
To ensure that you don't step off the array while iterating, fix your bounds in your second loop.
Change for(int j=contains; j<st.length-1; j++) to for(int j=contains; j<substr.length; j++). This will ensure that your second loop is never executed if contains > substr.length, whereas it was executing as long as j < st.length()-1.
st array length and substr lengths are different.So the line
j<st.length-1; should be j<substr.length-1;
I've a slight problem. I'm taking every element in a sparse matrix and putting it into a 1d array named 'b[]'. For example:
00070
00400
02000
00050
10000
Becomes: 0007000400020000005010000
The code below works in that at a given point within the inner-most loop b[] has the correct value as shown below. My problem is that outside of the inner-most loop b[] has a value of:
b[] = 0000000000000000000000000
I cannot understand what I'm missing. It should also be noted that b[] is globally defined, and instantiated within the constructor of this class. The problem is that I'm trying to use this 1d array in another function, and every element within the array is set to 0.
public void return1dSequence() {
// Create paired objects (Pair class).
for (int i = 0; i < a.length; i++) {
for(int j = 0; j < a[i].length; j++) {
this.b[i] = a[i][j];
// System.out.print(b[i]);
if (this.b[i] == 0) {
pos += 1;
} else {
value = this.b[i];
ml.add(new Pair(pos, value));
pos += 1;
}
}
}
}
Thanks in advance for any replies,
Andre.
You're filling in b[i] for indexes i of your outer loop...
Each time in the inner loop, you overwrite b[i] with value a[i][j].
Last value of a[i] array is always zero.
That's why your b array is zero.
What you want is probably:
int counter = 0;
for (int i = 0; i < a.length; i++) {
for(int j = 0; j < a[i].length; j++) {
b[counter] = a[i][j];
counter++;
}
}
The first thing i want to mention is that u shouldn't declare your variables (a, b....) static. Maybe u got hit by a mean side effect after creating two instances of Sparse. Try to define them as non static and report if it still wont work.
Best regards
Thomas
Try removing this from each call to b[] if you want to access b[] as static.
Also, are you sure you are not overwritting b[] anywhere else in the code? This is most likely the issue because of the public static declaration. Try making it private and removing static and see if you still have the issue.
I'm currently working on a project for a class to create a TextLine class that represents the a line of text that must be represented as an array of characters. I am not allowed to represent the TextLine object by using the string class indirectly or directly in any way, however, I can use it to work with the parameters.
For one of the methods, I am supposed to take in a string as an argument of a parameter, which is also a fragment to the TextLine object, and then return the index position of the first occurrence of the fragment in this TextLine, or -1, if the fragment is not found.
Right now, I'm trying to figure out the indexOf method, but my problem is that my method only checks for a starting point once. So if the letter of the TextLine object doesn't match the letter of the fragment the first time, but there is another match somewhere else in the object, the method doesn't check for that starting point.
For example, lets say I enter penplay as the TextLine, then I enter play as the fragment. Clearly, there is an occurrence of play in the TextLine, but what my indexOf method does, is that it checks the first p from penplay at index 0, then continues to see if the following letters match for the length of play, and if it doesn't, it returns -1. Any idea how I could allow the algorithm to keep searching for another starting point?
This is what I have for my code:
public int indexOf(String fragment){
char[] temp = fragment.toCharArray();
int j = 0;
for(int i = 0; i < someText.length; i++){
while(someText[i] == temp[j]){
for(j = 1; j < temp.length; j++){
if(temp[j] != someText[i+j]){
return -1;
}
}
return i;
}
}
return -1;
}
You're special-casing the first character, when there's no need to. Basically you need to say:
For each potential starting character...
Does the whole of fragment match, starting at that candidate position?
So something like:
// Only deal with *viable* starting points
for (int i = 0; i < someText.length - temp.length; i++) {
boolean found = true;
for (int j = 0; j < temp.length && found; j++) {
if (temp[j] != someText[i + j]) {
found = false;
}
}
if (found) {
return i;
}
}
return -1;
This can be refactored by extracting the inner loop:
for (int i = 0; i < someText.length - temp.length; i++) {
if (textMatches(temp, i)) {
return i;
}
}
return -1;
...
// TODO: Javadoc to explain parameters :)
private boolean textMatches(char[] chars, int startingIndex) {
for (int i = 0; i < chars.length; i++) {
if (chars[i] != someText[i + startingIndex]) {
return false;
}
}
return true;
}
The way you have it set up seems suitable as a kind of doesStringExistAtIndex(j, fragment) function. Since that returns -1 if the string doesn't exist at the first index, you could do something like this:
//assuming that "this" is the subject that you are searching in
public int indexOf(String fragment){
for(int i=0; i<this.length; ++i){
if(doesStringExistAtIndex(i, fragment))
return i;
}
return -1;
}
Not sure if this is what you wanted, but I basically wrote up an indexOf method. I did some testing and it seemed to work just fine in some tests I did. Of course, its going to look different because I wanted to make testing easier, but it should be 30 seconds or less of converting if you decide to use it.
public int indexOf(String fragment, String source)
{
char[] temp = fragment.toCharArray();
char[] someText = source.toCharArray();
outer : for(int i = 0; i <= someText.length - temp.length;i++) //stops looping because why loop after the fragment is longer than the source we have left when its impossible to find
{
if(someText[i] == temp[0]) //if the first characters are the same
{
int q = 0;
while(q < temp.length) //loop through the fragment
{
if(someText[i+q] != temp[q]) //if the characters are not the same, stop, and go to the next character of the source. Don't return anything
{
continue outer; //continues the loop labeled 'outer' (e.g. outer : for(...) )
}
q++; //increment index since they both match
}
return i; //fragment and some part of the source matched since it reached here. Return the index of the first character
}
}
return -1; //reached here because nothing was found :( return -1
}
EDIT 0 Added line comments