java


Slowly trying to code something in java that will say if insertion of brackets is correct (arithmetic)


You type something in the console, let's say (8+8). Then the program will tell you if the insertion of brackets is correct.
Here is my (of course not finished) definition of wrong brackets:
() this means if one array element is ( and next )
)(
if the amount of "(" is not equal to amount of ")"
else we have correct brackets.
What my code does is it splits the console input into String array elements. And I work with these. The problem is I cannot write a statement where I get an output True when we have (8), as example.
Here is my code:
import java.util.Scanner;
public class Brackets{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String any = input.nextLine();
String sArray[] = any.split("");
int counter1=0;
int counter2=0;
for(int i=0; i<sArray.length-1; i++){
if(sArray[i].equals("(")){
counter1++;
}
if(sArray[i].equals(")")){
counter2++;
}
if(sArray[i].equals("(") && sArray[i+1].equals(")")){
System.out.println("False");
return;
}
if(sArray[i].equals(")") && sArray[i+1].equals("(")){
System.out.println("False");
return;
}
}
if(counter1 == counter2){
System.out.println("True");
}
if(counter1 != counter2){
System.out.println("False");
}
}
}
I think there is a problem with this
if(sArray[i].equals("(") && sArray[i+1].equals(")")){
System.out.println("False");
return;
}
But how can I fix that if I'm looking for 2 neighbor array elements such as ()
These checks are both wrong and redundant.
if(sArray[i].equals("(") && sArray[i+1].equals(")")){
System.out.println("False");
return;
}
if(sArray[i].equals(")") && sArray[i+1].equals("(")){
System.out.println("False");
return;
}
You can also simplify things a lot, you only need one counter for example.
int counter = 0;
for(int i=0; i<sArray.length-1; i++){
if(sArray[i].equals("(")){
counter++;
}
if(sArray[i].equals(")")){
counter--;
}
if (counter<0) {
System.out.println("Close bracket with no open bracket found");
}
}
if (counter > 0) {
System.out.println("An open bracket was never closed");
}
This has a number of improvements.
Meaningful messages on what it found
Detects a close bracket without an open even if there is a later open. For example ")(" would fail but "()" pass.
Only uses one counter variable
The last change is stylistic really. You could still do this with two counters and compare the second one to the first rather than comparing with zero. The end result is the same though.
One more improvement, there is no need to split the string, and else if will be a tiny bit more efficient as we know it can't be a ')' if it was a '('.
int counter = 0;
for(int i=0; i<any.length()-1; i++) {
if(any.charAt(i) == '(') {
counter++;
} else if(any.charAt(i) == ')')) {
counter--;
}
if (counter<0) {
System.out.println("Close bracket with no open bracket found");
}
}
if (counter > 0) {
System.out.println("An open bracket was never closed");
}
This will be far more efficient as no need to do all the string splitting etc. All method names are from memory so may need a bit of tweaking.
You only need one counter to count the number of opened scopes. Then if it goes negative at any point, Fail. Then if it is zero at the end, Pass, otherwise Fail.

Related Links

Validate access rights on method call
how to handle dynamically changing iframe id using selenium webdriver
Dynamically setting width and height for a button in android
Find the Information of USB Devices In C/C++/Java
Swing layout which does not increase spacing when resized
problems using JDateChooser with a database
String Comparison Using Nested Loops
parsing error in json
How to resolve 'package not found' error when building using gradle?
Java for-loop never terminates
Why should the length property at hibernate mapping file be a power of 2?
Error creating bean with name 'securityConfig': Injection of autowired dependencies failed
java.io.StreamCorruptedException: invalid stream header: 54657374
Downloading a file created in server using Java
Can Java package name be a keyword?
MultiDimensional ArrayList in kmeans clustering algorithm

Categories

HOME
compiler-construction
stock
mean-stack
rsync
maven-3
jsrender
blueprintjs
echarts
flyway4
azure-media-services
podio
upload
contact
virtualization
vifm
ssl-client-authentication
modelica
google-cloud-ml
usergrid
phaser
caml
facebook-page
angular-ui
ab-testing
nodatime
facebook-instant-articles
accessor
mustache.php
icloud-api
firebase-crash-reporting
crystal-reports-2010
xpages-ssjs
chromebook
uninstall
fifo
typo3-6.2.x
neo4j-spatial
objectanimator
stormpath
exuberant-ctags
winrt-xaml-toolkit
column-family
gammu
mapbox-gl
revolution-slider
bitbucket-pipelines
twitch
mesos-chronos
hp-ux
janrain
keydown
node-sass
xml-documentation
dds
paxos
tactic
sqlclient
akka-cluster
pillow
mako
arrow-keys
eventkit
yt-project
xcb
elements
mikroc
py2app
etsy
bluemix-app-scan
pyke
jfugue
hsv
unity-networking
kendonumerictextbox
lib.web.mvc
wordml
angular-leaflet-directive
riak-cs
php-ci
ios9.1
operation
mmc
oberon
csquery
oxwall
jsonpickle
htmlcleaner
doskey
balanced-payments
uv-mapping
jmapviewer
padarn
html-editor
enterprisedb
itmstransporter
first-responder
datawindow
ticoredatasync
infobox
winbugs14
pyinotify
iphone-web-app
asp.net-profiles
rescale
zend-tool
ctp4
sustainable-pace
pascal-fc
document-conversion
ntvdm.exe

Resources

Encrypt Message



code
soft
python
ios
c
html
jquery
cloud
mobile