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

Hello. I need help altering my code a bit. I need it to print an error message i

ID: 3759277 • Letter: H

Question

Hello. I need help altering my code a bit.

I need it to print an error message if the string inputed does not start with a "(" . And I also need it to print out the symbols inputed.

For example if the user inputs (9+8-4). The output should be (9+84)

as of now my code would just output (984

I need it to print out (9+84).

so my general output should take in the (number "/,*,+,-" sybmbol and then disregard all other symbols and print out remaining numbers)

Here is the code i have so far.

import java.util.*;

class char_count
{
public static void main(String args[])
{

   System.out.println("Enter string: ");
   Scanner input = new Scanner(System.in);
String in= input.nextLine();
String in1="";
int i,d=0;
char cin = 0;

for(i=0;i<in.length();i++)
{
cin=in.charAt(i);
if(cin=='(')
{
d++;
in1=in1+cin;

}
if(d>=1 && Character.isDigit(cin))
{
d++;
in1=in1+cin;
}
else if(cin==')')
{

   break;   
}
}
System.out.println("Output:" + in1);
}
}

Explanation / Answer

/*The java program that prompt to enter a string of
* mathematical expression and prints
* the first symbol and ignres the rest of symbols
* Input :(9+8-4)
* output :(9+84)
* */

//Changes are in bold letters
//char_count.java
import java.util.*;
class char_count
{
   public static void main(String args[])
   {

       System.out.println("Enter string: ");
       Scanner input = new Scanner(System.in);
       String in= input.nextLine();
       String in1="";
       int i,d=0;
       //declare a boolean variable symbol and
       //set to false
       boolean symbol=false;
       char cin = 0;

       for(i=0;i<in.length();i++)
       {
           cin=in.charAt(i);
           if(cin=='(')
           {
               d++;
               in1=in1+cin;    

           }
           if(d>=1 && Character.isDigit(cin))
           {
               d++;
               in1=in1+cin;
           }
           //Add if conditon
           /*chec if symbol not true and cin character
              is either +,- ,%/, / then concatenate with in1.*/
           else if(!symbol && (cin=='+'||cin=='-'||cin=='*'||cin=='/'))
           {              
               in1=in1+cin;
               symbol=true;
           }

           else if(cin==')')
           {
               in1=in1+cin;
               break;
           }
       }
       System.out.println("Output:" + in1);
   }
}

------------------------------------------------------------------------------------------------------------------------------------------------

Sample Output:

sample run1:

Enter string:
(9+8-4)
Output:(9+84)


sample run2:

Enter string:
(9*8-4)
Output:(9*84)