If an array is not full add a value to the end - java

So i'm working on some code that is suppose to check if all my array slots are full and if there not add my new grade to the next slot in the array and return true and if it is full return false.
I'm confused on how to check if my array(grades) is full or not.. I have something like this but not quite sure if its correct.
The probelm is for some reason it seems to be only adding one grade. This is also effecting my score which is producing ? as a number which is something i have never seen before.
public boolean addGrade(int newGrade) {
for (int i = 0; i < grades.length; i++) {
if (grades[i] == -1)//or should i use 0 {
grades[i] = newGrade;
numGrades++;
return true;
}
}
return false;
}
score method (all its suppose to do is compute and return the score: score total / totalGrades)
public double computeScore() {
double total = 0;
for (int i = 0; i < grades.length; i++) {
total += grades[i];
}
return total / totalGrades;
}

You could even tighten up a tad by incrementing inside of the array brackets:
public boolean addGrade(int newGrade) {
if (numGrades < grades.length) {
grades[numGrades++] = newGrade;
return true;
}
return false;
}

since you are maintaining a counter variable numGrades hence use it directly to insert a new item at desired location.
public boolean addGrade(int newGrade) {
if(newGrades<grades.length){
grades[numGrades] = newGrade;
numGrades++;
return true;
}
return false;
}
Note: Each value in an array is by default zero.

No. You shouldn't do what you're doing. You have numGrades, I think you are should use it to track the correct position in addGrade()!
if (numGrades < grades.length) {
grades[numGrades] = newGrade;
numGrades++;
return true;
}
return false;
Also then
public double computeScore() {
double total = 0;
if (numGrades == 0) {
return total;
}
if (numGrades > grades.length) {
numGrades = grades.length;
}
for (int i = 0; i < numGrades; i++) {
total += grades[i];
}
return total / numGrades;
}

Related

How can I return true or false after for loop [duplicate]

This question already has answers here:
The method must return a type int
(2 answers)
Closed 6 years ago.
I've written a code and the code sorts array values. My code has to return boolean but it did not go well as I imagined or I did.
The console says; "This method must return a result of type boolean".
Here is my code
double array[] ={3.2,9.4,7.1,1,2,4.1,8.88};
// i j1
isItSort(array);
wrtOut(array);
}
public static boolean isItSort(double[] numbers)
{
int j=0;
int i;
for(i = 0; i<numbers.length; i++)
{
for(j =i+1; j<numbers.length; j++)
{
for(int j1 = j; j1<numbers.length; j1++)
{
boolean check = numbers[i]<numbers[j1];
if(check)
{
double temp = numbers[j1];
numbers[j1]= numbers[i];
numbers[i] = temp;
return true;
}
}
}
}
}
public static void wrtOut(double[] numbers){
for(int i=0; i<=numbers.length-1;i++ )
{
System.out.println(numbers[i]);
}
}
}
This because you don't have a returned value for all the possible cases in your method, indeed for example if check is never true you don't return any value with your current code, you should return a default value at the end of your method as next:
public static boolean isItSort(double[] numbers) {
...
return false;
}
isItSort() - only for loop is having return statement. Compiler is not sure that method will return successfully or not so its giving error. What will happen if
boolean check = numbers[i]
does not give true. The method will not be able to return any value if for loop ends without executing below block
if(check)
{
double temp = numbers[j1];
numbers[j1]= numbers[i];
numbers[i] = temp;
return true;
}
So, ideally you should return false, if no condition satisfies. So, write a return false at the end of the method. the program will run.
Your method 'isItSort' have a boolean return and you declare to return true if your if statement was true, but not always the condition will be satisfied, for this reason the compiler say to you add boolean return in the end of method for example:
public static boolean isItSort(double[] numbers)
{
int j=0;
int i;
for(i = 0; i<numbers.length; i++)
{
for(j =i+1; j<numbers.length; j++)
{
for(int j1 = j; j1<numbers.length; j1++)
{
boolean check = numbers[i]<numbers[j1];
if(check)
{
double temp = numbers[j1];
numbers[j1]= numbers[i];
numbers[i] = temp;
return true;
}
}
}
}
return true; <!-- you need to put appropriate return here -->
}

Finding Uniqueness (duplicates)

Im having trouble with my isUnique method. Either I'm making a logical error or a syntax error, or both. I have to make sure that every user input I get is Unique. Everything else I have done is correct but that method. I was using the debugger and I've noticed that the "number" doesn't change as the user input changes but I am new and kinda lost. Assigment: Enter 5 numbers and test for validity and uniqueness. If not valid do not count towards 5 numbers. If not unique count towards 5 numbers but count number of unique and print "not unique" if not unique.
import java.util.Scanner;
public class Assignment4Part2 {
public static void main(String[] args) {
int[] numbers = new int[5];
System.out.println("Enter an integer (50-100): ");
Scanner input = new Scanner(System.in);
int uniqueCount = 0;
for (int i = 0; i < numbers.length;) {
{
numbers[i] = input.nextInt();
if (isValid(numbers[i]) == true) {
i++;
if (isUnique(numbers, numbers[i]) == true) {
uniqueCount++;
System.out.printf("Unique so far: %d ", uniqueCount);
}
if (isUnique(numbers, numbers[i]) == false) {
System.out.println("That's not unique.\n");
}
}
}
}
for (int i = 0; i < numbers.length; i++)
{
System.out.print(numbers[i] + " ");
}
}
public static boolean isValid(int array) {
if (array <= 100 & array >= 50) {
return true;
} else {
System.out.println(" ***Invalid Number\n");
return false;
}
}
public static boolean isUnique(int[] array, int numbers) {
for (int i = 0; i < array.length; i++) {
if (array[i] == numbers) {
return false;
} else {
return true;
}
}
return false;
}
}
some things i notice:
for (int i = 0; i < numbers.length;) {
{
numbers[i] = input.nextInt();
if (isValid(numbers[i]) == true) {
//i++; // in case you increment here, you do it before is unqique is true... so next isUnique is of an emtpy (null) numbers[i]
if (isUnique(numbers, numbers[i]) == true) {
uniqueCount++;
System.out.printf("Unique so far: %d ", uniqueCount);
//continue here
i++;
}// why not an else?
//if (isUnique(numbers, numbers[i]) == false) {
else {
System.out.println("That's not unique.\n");
}
}
}
}
and the is unique....
public static boolean isUnique(int[] array, int numbers) {
// here the given number is already in the array, so never unique....
// this will always return false, because the input is already in the array
for (int i = 0; i < array.length; i++) {
if (array[i] == numbers) {
return false;
} else {
return true;
}
}
return false;
}
so use:
for (int i = 0; i < numbers.length;) {
{
// use a temp value before putting it in the array
int input = input.nextInt();
if (isValid(input) == true) {
//i++; // in case you increment here, you do it before is unqique is true... so next isUnique is of an emtpy (null) numbers[i]
if (isUnique(numbers, input) == true) {
uniqueCount++;
numbers[i] = input
System.out.printf("Unique so far: %d ", uniqueCount);
//continue here
i++;
}// why not an else?
//if (isUnique(numbers, numbers[i]) == false) {
else {
System.out.println("That's not unique.\n");
}
}
}
}
and in the is unique function....
if (array[i] == numbers) {
while not all numbers are filled in... this compares:
if(null == numbers){
so will be shorter to add in front:
if(array[i]==null){
break;
}
because the rest is still empty
The error is in the for in your method isUnique, during the first iteration you compare your the given number with the first value and if they dont match you already return true so the loop can't check any of the remaining numbers.
Just remove the else parte in that if and change the last return out of the loop to a true instead of false.
This way only until you checked the the whole array you will be sure the number is unique.
I would also sugest you send to that methis uniqueCount so you dont check the whole array, but just the amount of numbers already registered.

Can't access the full array

I have a method which calculates total distance covered by a particular member which returns as a double array, like so:
public double[] getTotalDistances(){
double[] distance;
distance = new double[3];
for(Activity r: diary ){
if(r instanceof Run){
distance[0] += r.getDistance();
}
}
for(Activity c: diary ){
if(c instanceof Cycle){
distance[1] += c.getDistance();
}
}
for(Activity s: diary ){
if(s instanceof Swim){
distance[2] += s.getDistance();
}
}
return distance;
}
now the objects (members) are stored in another array called members, like so:
public boolean addMember(Member m){
boolean result = false;
for(int i = 0; i < members.length; i++){
if(members[i] == null){
members[i] = m;
result = true;
break;
}
}
return result; //this is returned to have an indication if the member was added successfully or not
}
now I need a method that would print out all of the total distances of the members, I have tried this:
public void displayDistances() {
for(int i = 0; i < members[i].getTotalDistances().length; i++){
System.out.println(members[i].getTotalDistances()[i]);
}
}
however, this only prints the first element of the first member, then a 0, and gives a null pointer exception on top of it all. Any Help would be really appreciated!
So a couple things here. First I refactored your getTotalDistances() method.
public double[] getTotalDistances(){
double[] distance = new double[3];
for(Activity activity: diary) {
if (activity instanceof Run) {
distance[0] += activity.getDistance();
} else if (activity instanceof Cycle) {
distance[1] += activity.getDistance();
} else {
distance[2] += activity.getDistance();
}
}
return distance;
}
Then your displayDistances() should be changed to this:
public void displayDistances(){
for(int i = 0; i < members.length; i++){
double total = 0;
double[] distances = members[i].getTotalDistances();
for(int j = 0; j < ditances.length; j++){
total += distances[j];
}
System.out.println(total);
}
}
This will print the total distance traveled by each member. Good luck!

Checking an array for descending order

I am writing code to check if my array is in ascending or descending order. If the boolean 'ascending' is true, then I check if it is ascending. If it is false, then I check for descending. I need help checking whether the array is descending or not... I have the code to check ascending which is written below:
protected boolean isSorted(boolean ascending) {
boolean result = false;
if (ascending) {
for (int i=0;i<data.length-1;i++) {
if(data[i] < data[i+1]) {
result = true;
} else if(data[i] > data[i+1]) {
result = false;
}
}
} else {
//code to check for descending order
}
}
The first part of the if (the "ascending" check) is wrong, it should be:
for (int i = 0; i < data.length-1; i++) {
if (data[i] > data[i+1]) {
return false;
}
}
return true;
Conversely, the descending check should be (and notice that it's enough to change the direction of the comparison operator):
for (int i = 0; i < data.length-1; i++) {
if (data[i] < data[i+1]) {
return false;
}
}
return true;
In both cases, you have to break out of the loop as soon as you find a single pair of numbers that do not hold the ascending-or-descending property, and only return true after the loop exits.
You can cheat and do it in one loop if you like and remove one addition:
protected boolean isSorted(boolean ascending) {
for (int i = 1; i < data.length; i++) {
if (data[i-1] == data[i]) {
continue;
}
if ((data[i-1] > data[i]) == ascending) {
return false;
}
}
return true;
}
NOTE: I am building on the code by #OscarLopez so upvote his if you upvote mine.
To check if ArrayList<Integer> is in descending order try this:
boolean isSorted(ArrayList<Integer> list){
boolean sorted = true;
for (int i = 1; i < list.size(); i++) {
if (list.get(i-1) >= (list.get(i)) ) {
sorted = true;
} else {
return false;
} // if else ends
} // for "i" ends
return sorted;
}

Ordering Strings in java [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have an assignment where i am supposed to create an object that initializes an array of strings to have "size" elements and the amount of used elements equal to 0.
my issue is when im trying to compare strings to put them in alphabetical order.
int compare = storage[index].compareTo(value);
if (compare < 0)
thats where i am getting the runtime error of a nullpointerexception
here is my full code.
class main
package assignment2;
public class Main {
public static void main(String[] args) {
OrderedStringList myList = new OrderedStringList(5);
System.out.println("adding 10, 5, & 7");
myList.Insert("10");
myList.Insert("5");
myList.Insert("7");
myList.Display();
System.out.println("Value 4 find = "+ myList.Find("4"));
System.out.println("Value 7 find = "+ myList.Find("7"));
System.out.println("Adding 24 & 3");
myList.Insert("24");
myList.Insert("3");
myList.Display();
System.out.println("myList size: "+ myList.Size());
if (!myList.Insert("12"))
System.out.println("Could not add 12, full");
System.out.println("Removing 10, adding 12.");
myList.Delete("10");
myList.Insert("12");
myList.Display();
}
}
class OrderedStringList
package assignment2;
public class OrderedStringList {
int length;
int numUsed;
String[] storage;
boolean ordered;
public OrderedStringList(int size){
length = size;
storage = new String[length];
numUsed = 0;
}
public boolean Insert(String value){
boolean result = false;
int index = 0;
if (numUsed < length) {
while (index <= numUsed) {
int compare = storage[index].compareTo(value);
if (compare < 0)
index++;
}
moveItemsDown(index);
storage[index] = value;
numUsed++;
result = true;
}
return result;
}
private void moveItemsDown(int start){
int index;
for (index = numUsed-1; index >=start; index--){
storage[index+1] = storage[index];
}
}
private void moveItemsUp(int start){
int index;
for (index = start; index < numUsed-1; index++){
storage[index] = storage[index+1];
}
}
public boolean Find(String value){
return (FindIndex(value) >= 0);
}
private int FindIndex(String value) {
int result = -1;
int index = 0;
boolean found = false;
while ((index < numUsed) && (!found)) {
found = (value.equals(storage[index]));
if (!found)
index++;
}
if (found)
result = index;
return result;
}
public boolean Delete(String value){
boolean result = false;
int location;
location = FindIndex(value);
if (location >= 0) {
moveItemsUp(location);
numUsed--;
result = true;
}
return result;
}
public void Display() {
int index;
System.out.println("list Contents: ");
for (index = 0; index < numUsed; index++) {
System.out.println(index+" "+storage[index]);
}
System.out.println("-------------");
System.out.println();
}
public void DisplayNoLF() {
int index;
System.out.println("list Contents: ");
for (index = 0; index < numUsed; index++) {
System.out.print(storage[index]+" ");
}
System.out.println("-------------");
System.out.println();
}
public int Size(){
return numUsed;
}
}
thanks guys
It should be
while(index < numUsed)
If you use <=, you'll always access index 0 in an empty list, which will be null. Then when you try to call compareTo on it it will throw an NPE.
ALso, if null is a legal value to add to your list, you'll need to put a null check around the compareTo call and decide if null is alphabetically first or last.
You can use Arrays#sort to maintain order, its already available in library.
public boolean Insert(String value){
boolean result = false;
if (numUsed < length) {
storage[index] = value;
numUsed++;
result = true;
Arrays.sort(storage);
}
return result;
}
Here's why:
public boolean Insert(String value){
boolean result = false;
int index = 0;
if (numUsed < length) {
while (index <= numUsed) { // Here the first time numUsed = 0, index = 0, index <= numUsed;
int compare = storage[index].compareTo(value); // The first time, storage[0] == null; NullPointException is thrown
if (compare < 0)
index++;
}
moveItemsDown(index);
storage[index] = value;
numUsed++;
result = true;
}
return result;
}
Maybe change <= to < will do?
At the first run this line
int compare = storage[index].compareTo(value);
your are comparing storage[index] which value is null with value which is not null or empty
to enable a smooth running
replace
while(index =< numUsed) {
int compare = storage[index].compareTo(value);
if(compare < 0)
index++;
}
with
while(index < numUsed) {
int compare = storage[index].compareTo(value);
if(compare < 0)
index++;
}

Categories

Resources