Can't access the full array - java

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!

Related

HugeInteger Class adding and subtracting taking into account negative values

I'm currently writing a HugeInteger class that can take in 40 digits, and I have a few comparison tests that are already written. The thing I'm having most trouble with is adding and subtraction methods. I was able to get two values to add, but don't know how to implement a negate function if one of the values are negative. My subtraction method doesn't seem to work either.
public void add(HugeInteger hi) {
if (digits[NUM_DIGITS] < 0) {
negate();
this.subtract(hi);
}
int carry = 0;
for(int i = digits.length-1; i >=0 ;i--) {
int cur = this.digits[i] + hi.digits[i] + carry;
if (cur >= 10){
cur= cur-10;
resultAdd[i] = cur;
carry = 1;
} else{
resultAdd[i] = cur;
carry = 0;
}
}
StringBuilder builder = new StringBuilder();
int j=0;
for (int i : resultAdd) {
builder.append(i);
this.digits[j] = i;
j++;
}
this.hi = builder.toString().replace("0", "");
}
public void subtract(HugeInteger hi) {
for(int i = digits.length-1; i >=0 ;i--) {
if (this.digits[i] - hi.digits[i] < 0){
this.digits[i-1]--;
this.digits[i]+=10;
}
int cur = this.digits[i] - hi.digits[i];
this.digits[i] = cur;
}
StringBuilder builder = new StringBuilder();
int j=0;
for (int i : resultAdd) {
builder.append(i);
this.digits[j] = i;
j++;
}
this.hi = builder.toString().replace("0", "");
}
public void negate() {
if(this.positive){
this.positive = false;
} else{
this.positive = true;
this.hi = this.hi.replace("-", "");
}
}

How do I return a value when ArrayList.isEmpty()?

It all prints correctly except the "isEmpty" return statement. How do I get it to properly return "-1" in order for the last 2 statements in the main function to do their job.
Note: I can not edit the main function
My code is as follows:
import java.util.*;
public class task7{
public static int find_minimum_length(ArrayList<String> A)
{
int position = 0;
int smallest = A.get(0).length();
for(int i = 0; i<A.size(); i++)
{
if(A.isEmpty())
{
return -1;
}
if(A.get(i).length()<smallest)
{
smallest = A.get(i).length();
int shortt = A.indexOf(A.get(i));
position = shortt;
}
}
return position;
}
public static ArrayList<String> remove_minimum_length(ArrayList<String> A)
{
if(A.isEmpty())
{
}
else
{
A.remove(find_minimum_length(A));
}
return A;
}
public static void main(String[] args)
{
ArrayList<String> a = new ArrayList<String>();
a.add("whale");
a.add("cat");
a.add("elephant");
a.add("donkey");
a.add("goat");
System.out.println(a);
int position = find_minimum_length(a);
System.out.printf("minimum position = %d\n\n", position);
remove_minimum_length(a);
System.out.println(a);
position = find_minimum_length(a);
System.out.printf("minimum position = %d\n\n", position);
remove_minimum_length(a);
System.out.println(a);
position = find_minimum_length(a);
System.out.printf("minimum position = %d\n\n", position);
remove_minimum_length(a);
System.out.println(a);
position = find_minimum_length(a);
System.out.printf("minimum position = %d\n\n", position);
remove_minimum_length(a);
System.out.println(a);
position = find_minimum_length(a);
System.out.printf("minimum position = %d\n\n", position);
remove_minimum_length(a);
System.out.println(a);
position = find_minimum_length(a);
System.out.printf("minimum position = %d\n\n", position);
}
}
Move this:
if(A.isEmpty())
{
return -1;
}
out of your for-block. The for block will only be executed if there are elements to iterate over, meaning, if the list is not empty.
I would make a few changes to your method. First, you should check for a null input, and return -1 if you find it. You can also return -1 in the event of an empty input ArrayList.
public static int find_minimum_length(List<String> a) {
if (a == null || a.size() == 0) {
return -1;
}
int position = 0;
int smallest = a.get(0).length();
// start iterating your for loop at 1, not 0
for (int i=1; i < a.size(); i++) {
if (a.get(i).length() < smallest) {
smallest = a.get(i).length();
position = i;
}
}
return position;
}
public static List<String> remove_minimum_length(List<String> a) {
int index = find_minimum_length(a);
if (index != -1) {
a.remove(index);
}
return a;
}
Your Problem is that the for block will be executed as often as the array is big. So if your array is empty the size is 0. So the for isn't executed.
To fix your Problem you have to move your if-clause out of the for.
Applied to your code it should look like this:
public static int find_minimum_length(ArrayList<String> A)
{
int position = 0;
int smallest = A.get(0).length();
if(!A.isEmpty())
{
for(int i = 0; i<A.size(); i++)
{
if(A.get(i).length()<smallest)
{
smallest = A.get(i).length();
int shortt = A.indexOf(A.get(i));
position = shortt;
}
return position;
}
else
{
return -1;
}
}
Put your isEmpty() call outside the for loop.
if(A.isEmpty()) return -1;
for(int i = 0; i<A.size(); i++)
{
if(A.get(i).length()<smallest)
{
smallest = A.get(i).length();
int shortt = A.indexOf(A.get(i));
position = shortt;
}
}

Return the sum of all integers from a random String without using regex

I was asked this question in an interview recently (Java programming que)
Return the sum of all integers from a random String.
Just iterate over the string, handle one digit at a time. This is pretty much exactly what the regex would do anyway:
String testStrings[] = { "-1a2b3c", "123ab!45c", "abcdef", "0123.4",
"dFD$#23+++12##T1234;/.,10" };
for (String testString : testStrings) {
String currentNumber = "";
int sum = 0;
for (int i = 0; i < testString.length(); i++) {
char currentChar = testString.charAt(i);
// Add digits or a leading minus to "currentNumber"
if (Character.isDigit(currentChar)
|| (currentNumber.equals("") && currentChar == '-')) {
currentNumber += currentChar;
} else {
// We've stumbled across a non-digit char.
//Try to parse the "currentNumber" we have so far
if (!currentNumber.equals("") && !currentNumber.equals("-"))
sum += Integer.parseInt(currentNumber);
currentNumber = "";
}
}
// Add the last "currentNumber" in case the string ends with a
// number
if (!currentNumber.equals("") && !currentNumber.equals("-"))
sum += Integer.parseInt(currentNumber);
System.out.println(sum);
}
Output:
4
168
0
127
1279
public class Random {
public int SumofNumbers(String s){
char[] str = s.toCharArray();
String answer="";
int sum = 0;
List<String> al = new ArrayList();
for (int i=0;i< str.length;i++){
if (checkNumber(str[i])){
answer=answer+str[i];
}
else
{
if(!answer.isEmpty()){
al.add(answer);
answer = "";
}
}
if (i == str.length -1 && !answer.isEmpty()) {
al.add(answer);
}
}
for (String a1 : al){
sum = sum + Integer.valueOf(a1);
}
return sum;
}
private boolean checkNumber(char c) {
if ((int)c > 47 && (int)c < 58){
return true;
}else if ((int)c == 45){
return true;
}
return false;
}
public static void main(String [] args){
Random r = new Random();
String test = "123ab!45c";
System.out.println(r.SumofNumbers(test));
}
}
public class StringToIntAddition {
public static void main(String[] args) throws Exception {
String str = "2e40 ssdf 23-9", number="";
int sum=0;
for(int i=0; i<str.length() ;i++){
if(Character.isDigit(str.charAt(i))){
number += str.charAt(i);
}
else if(!number.isEmpty()){
sum += Integer.parseInt(number);
number= "";
}
if (str.charAt(i) == '-'){
number = "-" ;
}
}
if(!number.isEmpty()){
sum += Integer.parseInt(number);
}
System.out.println("number= " + sum);
}
}
I've got a slightly 'cute' way to do this in Java 8: implement it as a Collector
public DigitCollector {
private boolean negative = false;
private int current = 0;
private int total = 0;
public int getTotal() {
if (negative) {
total -= current;
} else {
total += current;
}
current = 0;
negative = false;
return total;
}
public void accept(Character ch) {
if (Character.isDigit(ch)) {
current = 10 * current + Integer.parseInt(ch.toString());
} else if (ch.equals('-')) {
negative = true;
} else {
getTotal();
}
}
}
Now you can collect a stream of characters:
text.chars().map(ch -> new Character((char)ch))
.collect(DigitCollector::new, DigitCollector::accept, null)
.getTotal();
I realise the mapping ch -> new Character((char)ch)) looks strange but .chars() returns a stream of integers instead of characters. See here for reasons why (though pretty much everyone agrees it was a mistake).
This is a slightly longwinded way of doing it but it's pretty flexible: you could take a stream of Character from anywhere and do any sort of manipulation you wanted before collecting them. It seems to me to be a natural representation of the problem and, mostly, I just reckon streams are cooler than traditional iteration :-)
There's already quite a few answers, but this one seemed fun. I have a different solution that should be pretty efficient:
public static int countString(String input) {
if (input == null) return 0;
int sum = 0;
int accumulator = 0;
boolean lastCharWasDigit = false;
for (int i = 0, len = input.length(); ++i) {
char c = input.charAt(i);
// If a non-digit character is found, clear the
// accumulator and add it to the sum.
if (c < '0' || c > '9') {
sum += accumulator;
accumulator = 0;
lastCharWasDigit = false;
continue;
}
// If the previous character was a digit, that means
// this is a continuation. Multiply by ten to shift
// it over one power of ten before adding the new value
if (lastCharWasDigit) {
accumulator *= 10;
}
// Add the integer value of the character
int charValue = c - '0';
accumulator += charValue;
lastCharWasDigit = true;
}
// Finally, clear the accumulator for any ending digits,
// and return the sum
sum += accumulator;
return sum;
}

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

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;
}

Sorted / Not sorted - How do I print the answer to the console?

I've got a program that checks whether a list is sorted or not. How do I print the answer? (i.e "The list is sorted", "The list is not sorted").
public class CheckList {
public static void main(String[] args) {
int[] myList = new int[10];
// Read in ten numbers
Scanner input = new Scanner(System.in);
System.out.println("Enter ten numbers: ");
for (int i = 0; i < myList.length; i++) {
myList[i] = input.nextInt();
}
}
//Check if list is sorted
public static boolean isSorted(int[] myList) {
if (myList[0] > 1) {
for (int i = 1; i < myList[0]; i++)
if (myList[i] > myList[i + 1])
return false;
}
return true;
}
}
Just call the method inside a if:
if(isSorted(myList)) {
System.out.println("Array is sorted");
} else {
System.out.println("Array is not sorted");
}
Anyway, your isSorted method won't work, i would make something like this:
//checks if array is sorted in ascending order
public static boolean isSorted(int[] myList) {
if(myList == null) return false; //just checking
for (int i = 0; i < myList.length - 1; i++) {
if (myList[i] > myList[i + 1]) {
return false;
}
}
return true;
}
Just call the method after your for loop
for (int i = 0; i < myList.length; i++) {
myList[i] = input.nextInt();
}
if(isSorted(myList)) {
System.out.println("The list is sorted");
} else {
System.out.println("The list is not sorted");
}

Categories

Resources