Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a java method for summing the elements of a singly linked list of integers

ID: 672244 • Letter: W

Question

Write a java method for summing the elements of a singly linked list of integersthat are greater than a given value. The driver class provided will guide on the name and parameters of the method. Create a class(named Steady) in which the method will reside rather than modify the linkedlist. The method must make use of the Node/linkedlist framework provided. Arrays should not be used. The first value of the input is used as a parameter to the method. The rest are used to construct the lis upon which the method is performed.

Sample I/O:

5 1 9 7 12 3 4 20 2

List: 1 9 7 12 3 4 20 2

The sum of values greater than 5 is 48.

public class Node {
private int data;
private Node next;

Node(int number) { data=number; }

public Node getNext() { return next; }
public void setNext(Node n) { next=n; }
public boolean hasNext() { return next!=null; }

public int getData() { return data; }
public void setData(int number) { data=number; }   

public String toString () { return ""+data; }
}

public class LinkedList {
protected Node head;

public LinkedList () { head = null; }

public void add ( int number ) {
Node t = new Node (number);
t.setNext (head);
head = t;
}

public String toString () {
Node t = head;
if (t==null) {
return "";
}
else {
String list = t.toString();
while (t.hasNext()) {
t=t.getNext();
list=list+" "+t.toString();
}
return list;
}
}
}

Explanation / Answer

import java.util.Scanner;

public class Steady
{
public static void sumL(LinkedList list,int n){
   String l=list.toString();
   String[] elements=l.split(" ");
   int sum=0;
   for(String i:elements){
       if(Integer.parseInt(i)>5){
       sum=sum+Integer.parseInt(i);
       }
   }
   System.out.println("The sum of values greater than"+n+" is "+sum);
}
public static void main(String[] args){
   Scanner s=new Scanner(System.in);
   LinkedList list=new LinkedList();
System.out.println("Enter the integers into array: ");
for(int i=0;i<9;i++){
   System.out.print((i+1)+" element: ");
   int n=s.nextInt();
   list.add(n);
}
System.out.println(list.toString());
System.out.println("Enter the number to find sum: ");
int sum=s.nextInt();
sumL(list,sum);
}
  
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote