Question

In: Computer Science

Hi I have a java code for my assignment and I have problem with one of...

Hi

I have a java code for my assignment and I have problem with one of my methods(slice).the error is Exception in thread "main" java.lang.StackOverflowError

Slice method spec:

Method Name: slice
Return Type: Tuple (with proper generics)
Method Parameters: Start (inclusive) and stop (exclusive) indexes. Both of these parameters are "Integer" types (not "int" types). Like "get" above, indexes may be positive or negative. Indexes may be null.
Description:

  • Positive indexes work in the normal way
  • Negative indexes are described above for "get"
  • If the "start" index is null, that means start at the beginning of the list (index=0)
  • If the "stop" index is null, that means the slice should go to the end of the list (including the last element)
  • If both "start" and "stop are null, that means to copy the tuple (in other words, return a new tuple with the same elements).


Given this Tuple:

[10, 20, 30, 40]

Example slice results

Start Stop Result (New Tuple)
0 1 [10]
0 2 [10, 20]
0 3 [10, 20, 30]
0 4 [10, 20, 30, 40]
null 1 [10]
null 3 [10, 20, 30]
-2 -1 [30]
-2 null [30, 40]
-1 null [40]
null null [10, 20, 30, 40]



Note: Each result is a new tuple

Example usage:

tuple2 = tuple1.slice(0, 1);
tuple2 = tuple1.slice(-1, null);

My code is the following:


import java.util.*;
public class Tuple1 <T>{
  
   private List<T> elements;

  
   public Tuple1(List<T> newElements){
       this.elements=newElements;
   }
  
   @SafeVarargs
   public Tuple1(T...newElements){
      
       List<T> elementsss=new ArrayList<T>();
       for(T i:newElements){
          
           elementsss.add(i);
           }
          

           this.elements=elementsss;
       }
  
   public Tuple1(Tuple1<T> tuple){
       elements=tuple.elements;
       }
  

   public List<T> getElements(){
           return this.elements;
       }
  
   public T get(Integer index){
      
       if(index<0){
               return this.getElements().get(size()+index);
           }
      
       else{
           return this.getElements().get(index);
      
       }

       }
  
   public int size(){
       return getElements().size();
      
   }
   public T getFirst(){
       return this.get(0);
          
       }

   public T getLast(){
       return this.get(-1);
       }  

  
   public List toList(){
      
       List<T> copy=new ArrayList<>(this.getElements());
          
           return copy;
       }

   public Integer confirmStart(Integer start){
           Integer star=0;

           if (start==null){
               star=0;
           }

           else if (start<0){
               star=this.size()+start;
               }

           else {
               star=start;
               }
           return star;
       }
  
   public Integer confirmStop(Integer stop){
           Integer sto=0;

           if(stop==null){
                   sto=this.size();
           }

           else if(stop<0){
                   sto=this.size()+stop-1;
               }

           else{
                   sto=stop-1;
           }
           return sto;
              
          
       }

   public Tuple1 <T> slice(Integer start,Integer stop){
          
           List<T> list= new ArrayList<T>();
          
           Integer star=this.confirmStart(start);
           Integer sto=this.confirmStop(stop);
          
           list=this.getElements().subList(star,sto);
          
           Tuple1 <T> t;
           t= new Tuple1 <T>(list);
               return t;
          
           }

   @Override
   public String toString(){
       String output="Tuple Elementst: "+" "+this.getElements()+
           "\n Get Element: "+this.get(0)+
           "\nSize: "+this.size()+
           "\nFirst Element:"+" "+this.getFirst()+
           "\nLast Element :"+" "+this.getLast()+
           "\nconfirmStart: "+" "+this.confirmStart(1)+
           "\nConfirm Stop:"+" "+this.confirmStop(-1)+
           "\ntoList:"+" "+this.toList()+
           "\nSlice:"+" "+this.slice(0,2);
          
           return output;
}

   public static void main (String[]args){
       List<String>elementss=new ArrayList<String>();
       elementss.add("Haitham");
       elementss.add("Lindsey");
       elementss.add("Lamar");
       elementss.add("Narmin");
      
       Tuple1 <String> elm;
       elm=new Tuple1<String>(elementss);
       System.out.println(elm.toString());
       System.out.println("================================");
       Tuple1 <Integer> elms;
       elms=new Tuple1<Integer>(1,2,3,4,5);
       System.out.println(elms.toString());

       }
   }  






















































Solutions

Expert Solution

I fixed the code. It was getting into infinite loop because of the toString() method. Inside toString(), the slice(0,2) is being repeated called. Ideally toString() should only give a representation of the object. In this case only the elements need to be listed and not all the functions being called. So I have cleaned the code a bit and changed the main to show the proper usage. Hope it helps. For 2nd example with numbers, I have shown how to use negative index and null to show elements being fetched from last.


import java.util.*;
public class Tuple1 <T>{

   private List<T> elements;


   public Tuple1(List<T> newElements){
       this.elements=newElements;
   }

   @SafeVarargs
   public Tuple1(T...newElements){

       List<T> elementsss=new ArrayList<T>();
       for(T i:newElements){

           elementsss.add(i);
       }


       this.elements=elementsss;
   }

   public Tuple1(Tuple1<T> tuple){
       elements=tuple.elements;
   }


   public List<T> getElements(){
       return this.elements;
   }

   public T get(Integer index){

       if(index<0){
           return this.getElements().get(size()+index);
       }

       else{
           return this.getElements().get(index);

       }

   }

   public int size(){
       return getElements().size();

   }
   public T getFirst(){
       return this.get(0);

   }

   public T getLast(){
       return this.get(-1);
   }


   public List toList(){

       List<T> copy=new ArrayList<>(this.getElements());

       return copy;
   }

   public Integer confirmStart(Integer start){
       Integer star=0;

       if (start==null){
           star=0;
       }

       else if (start<0){
           star=this.size()+start;
       }

       else {
           star=start;
       }
       return star;
   }

   public Integer confirmStop(Integer stop){
       Integer sto=0;

       if(stop==null){
           sto=this.size();
       }

       else if(stop<0){
           sto=this.size()+stop-1;
       }

       else{
           sto=stop;
       }
       return sto;


   }

   public Tuple1 <T> slice(Integer start,Integer stop){

       List<T> list= new ArrayList<T>();

       Integer star=this.confirmStart(start);
       Integer sto=this.confirmStop(stop);

       list=this.getElements().subList(star,sto);

       Tuple1 <T> t;
       t= new Tuple1 <T>(list);
       return t;

   }

   @Override
   public String toString(){
       return elements.toString();
   }

   public static void main (String[]args){
       List<String>elementss=new ArrayList<String>();
       elementss.add("Haitham");
       elementss.add("Lindsey");
       elementss.add("Lamar");
       elementss.add("Narmin");

       Tuple1 <String> elm;
       elm=new Tuple1<String>(elementss);
       String output="Tuple Elementst: "+" "+elm+
               "\n Get Element: "+elm.get(0)+
               "\nSize: "+elm.size()+
               "\nFirst Element:"+" "+elm.getFirst()+
               "\nLast Element :"+" "+elm.getLast()+
               "\nconfirmStart: "+" "+elm.confirmStart(1)+
               "\nConfirm Stop:"+" "+elm.confirmStop(-1)+
               "\ntoList:"+" "+elm.toList()+
               "\nSlice:"+" "+elm.slice(0,2);
       System.out.println(output);
       System.out.println("================================");
      
       Tuple1 <Integer> elms;
       elms=new Tuple1<Integer>(1,2,3,4,5);
       output="Tuple Elementst: "+" "+elms+
                   "\n Get Element: "+elms.get(0)+
                   "\nSize: "+elms.size()+
                   "\nFirst Element:"+" "+elms.getFirst()+
                   "\nLast Element :"+" "+elms.getLast()+
                   "\nconfirmStart: "+" "+elms.confirmStart(1)+
                   "\nConfirm Stop:"+" "+elms.confirmStop(-1)+
                   "\ntoList:"+" "+elms.toList()+
                   "\nSlice:"+" "+elms.slice(-2,null);
           System.out.println(output);
   }
}

output
----
Tuple Elementst: [Haitham, Lindsey, Lamar, Narmin]
Get Element: Haitham
Size: 4
First Element: Haitham
Last Element : Narmin
confirmStart: 1
Confirm Stop: 2
toList: [Haitham, Lindsey, Lamar, Narmin]
Slice: [Haitham, Lindsey]
================================
Tuple Elementst: [1, 2, 3, 4, 5]
Get Element: 1
Size: 5
First Element: 1
Last Element : 5
confirmStart: 1
Confirm Stop: 3
toList: [1, 2, 3, 4, 5]
Slice: [4, 5]


Related Solutions

I have the following code for my java class assignment but i am having an issue...
I have the following code for my java class assignment but i am having an issue with this error i keep getting. On the following lines: return new Circle(color, radius); return new Rectangle(color, length, width); I am getting the following error for each line: "non-static variable this cannot be referenced from a static context" Here is the code I have: /* * ShapeDemo - simple inheritance hierarchy and dynamic binding. * * The Shape class must be compiled before the...
In Python I have a code: here's my problem, and below it is my code. Below...
In Python I have a code: here's my problem, and below it is my code. Below that is the error I received. Please assist. Complete the swapCaps() function to change all lowercase letters in string to uppercase letters and all uppercase letters to lowercase letters. Anything else remains the same. Examples: swapCaps( 'Hope you are all enjoying October' ) returns 'hOPE YOU ARE ALL ENJOYING oCTOBER' swapCaps( 'i hope my caps lock does not get stuck on' ) returns 'I...
This is the code I have. My problem is my output includes ", 0" at the...
This is the code I have. My problem is my output includes ", 0" at the end and I want to exclude that. // File: main.cpp /*---------- BEGIN - DO NOT EDIT CODE ----------*/ #include <iostream> #include <fstream> #include <sstream> #include <iomanip> using namespace std; using index_t = int; using num_count_t = int; using isConnected_t = bool; using sum_t = int; const int MAX_SIZE = 100; // Global variable to be used to count the recursive calls. int recursiveCount =...
in java: In my code at have my last two methods that I cannot exactly figure...
in java: In my code at have my last two methods that I cannot exactly figure out how to execute. I have too convert a Roman number to its decimal form for the case 3 switch. The two methods I cannot figure out are the public static int valueOf(int numeral) and public static int convertRomanNumber(int total, int length, String numeral). This is what my code looks like so far: public static void main(String[] args) { // TODO Auto-generated method stub...
HI. I have been trying to run my code but I keep getting the following error....
HI. I have been trying to run my code but I keep getting the following error. I can't figure out what I'm doing wrong. I also tried to use else if to run the area of the other shapes but it gave me an error and I created the private method. Exception in thread "main" java.util.InputMismatchException at java.base/java.util.Scanner.throwFor(Scanner.java:939) at java.base/java.util.Scanner.next(Scanner.java:1594) at java.base/java.util.Scanner.nextInt(Scanner.java:2258) at java.base/java.util.Scanner.nextInt(Scanner.java:2212) at project2.areacalculation.main(areacalculation.java:26) My code is below package project2; import java.util.Scanner; public class areacalculation { private static...
I need code written in java for one of my projects the instructions are Write a...
I need code written in java for one of my projects the instructions are Write a program that interacts with the user via the console and lets them choose options from a food menu by using the associated item number. It is expected that your program builds an <orderString> representing the food order to be displayed at the end. (See Sample Run Below). Please note: Each student is required to develop their own custom menus, with unique food categories, items...
Hi guys, I'm working on an assignment for my Java II class and the narrative for...
Hi guys, I'm working on an assignment for my Java II class and the narrative for this week's program has me a bit lost. I've put the narrative of the assignment in the quotation marks below. " Included with this assignment is an encrypted text file. A simple Caesar cipher was used to encrypt the data. You are to create a program which will look at the frequency analysis of the letters (upper and lowercase) to help “crack” the code...
Java homework problem: I need the code to be able to have a message if I...
Java homework problem: I need the code to be able to have a message if I type in a letter instead of a number. For example, " Please input only numbers". Then, I should be able to go back and type a number. import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class LoginGui {    static JFrame frame = new JFrame("JFrame Example");    public static void main(String s[]) {        JPanel panel...
JAVA JAVA JAVA Hey i need to find a java code for my homework, this is...
JAVA JAVA JAVA Hey i need to find a java code for my homework, this is my first java homework so for you i don't think it will be hard for you. (basic stuff) the problem: Write a complete Java program The transport Company in which you are the engineer responsible of operations for the optimization of the autonomous transport of liquid bulk goods, got a design contract for an automated intelligent transport management system that are autonomous trucks which...
Need this in C#. Below is my code for Problem 3 of Assignment 2. Just have...
Need this in C#. Below is my code for Problem 3 of Assignment 2. Just have to add the below requirement of calculating the expected winning probability of VCU. Revisit the program you developed for Problem 3 of Assignment 2. Now your program must calculate the expected winning probability of VCU through simulation. Run the simulation 10,000 times (i.e., play the games 10,000 times) and count the number of wins by VCU. And then, calculate the winning probability by using...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT