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

Hello i need help with this problem i have with my code. Ok so i need it to do t

ID: 3759367 • Letter: H

Question

Hello i need help with this problem i have with my code.

Ok so i need it to do this.

This is correct:

Input: (9+4-5)

Output: (9+45)

But when I input the wrong format right now this is what happens:

input: 9-4+5

output: -

when i need it to output this:

input: 9-4+5

output would be an error message: ERROR!!

I almost have it. but right now it is outputing the first symbol in the string when i need it to be an error, so if the string does not start with a "(" it says error

so here is my code:

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;

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;
}
else if(!symbol && (cin=='+'||cin=='-'||cin=='*'||cin=='/'))
{
in1=in1+cin;
symbol=true;
}
else if(cin==')')
{
in1=in1+cin;
break;
}
}
System.out.println("Output:" + in1);
}
}

thanks for the help.

Explanation / Answer

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;

   boolean symbol=false;

   char cin = 0;

   if (in.charAt(0) != '(') {

       System.out.println("ERROR !!");

       return;

   }

   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(!symbol && (cin=='+'||cin=='-'||cin=='*'||cin=='/'))

   {

   in1=in1+cin;

   symbol=true;

   }

   else if(cin==')')

   {

   in1=in1+cin;

   break;

   }

   }

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

   }

}

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