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

For the following (in Java), this driver class works but does not catch incorrec

ID: 3597354 • Letter: F

Question

For the following (in Java), this driver class works but does not catch incorrect input (unsupported command) I.e. if you enter add4, instead of "add 4" I want the program to display error and then prompt user for another command. Can you help with this?

import java.util.Scanner;

public class Test {

   public static void main(String[] args){

   Set set = new Set();

Scanner scan = new Scanner(System.in);

while(true) {

         System.out.print("Enter command:");

         String command = scan.next();

         int x = scan.nextInt();

          

         if(command.equals("add")) {

             set.add(x);

             System.out.println(set);

         }

         else if(command.equals("del")) {

             if (set.exists(x)) {

                 set.delete(x);

                 }

             else if(!set.exists(x)) {

                 System.out.println("not in set");

             }

             System.out.println(set);

         }

         else if(command.equals("exists")) {

             System.out.println(set.exists(x));

         }

         //catches incorrect/invalid input

         else {

             System.out.println("Unsupported command!");

         }

}

}

}

Explanation / Answer

Here is the modification for Test.java:

import java.util.*;
public class Test {
public static void main(String[] args){
Set set = new Set();
Scanner scan = new Scanner(System.in);
while(true) {
int num = 0;
StringTokenizer st;
do
{
    System.out.print("Enter command:");  
   String line = scan.nextLine();   //Reads all line at a time.
   st = new StringTokenizer(line);   //Tokenizes the line based on space.
   num = st.countTokens();       //Counts the number of tokens.
}while(num != 2);       //If the number of tokens is not 2, re-run the loop.
String command = st.nextToken();   //Consider the first token as string.
int x = Integer.parseInt(st.nextToken());   //Consider the second token as integer.
//Proceed with your logic.
if(command.equals("add")) {
set.add(x);
System.out.println(set);
}
else if(command.equals("del")) {
if (set.exists(x)) {
set.delete(x);
}
else if(!set.exists(x)) {
System.out.println("not in set");
}
System.out.println(set);
}
else if(command.equals("exists")) {
System.out.println(set.exists(x));
}
//catches incorrect/invalid input
else {
System.out.println("Unsupported command!");
}
}
}
}