Else if condition being ignored? - java

I'm new to Java and i have to make a small application that will calculate GCD of up to 5 numbers.
If the input is nothing before 5 numbers have been entered, the application will calculate it on the already given numbers
Unfortunately my code seems to ignore my else if statement that will make sure it doesn't try to add "" to a int array.
This is the part that i am struggling on, i have already tried contains instead of equals but with no result.
Am i writing the !input.. wrong? The code runs correct when i try to add a 0, it will not execute the else if.
But if i enter "" to make the application run the first part of the if statement it will go to the else if after its done and try to add "" to the array which of course results in an error.
I'm sure its something small i am missing or am unaware of, but i can't seem to figure it out.
}else if(Integer.parseInt(input) != 0 || !input.equals(""));{
ggdGetallen[count] = Integer.parseInt(input);
count++;
txtGetal.selectAll();
}
Full code
private void txtGetalActionPerformed(java.awt.event.ActionEvent evt) {
String input = txtGetal.getText();
//Berekenen van het kleinste getal in het array
if(count > 4 || input.equals("")){
int kleinsteGetal = ggdGetallen[0];
for (int getal : ggdGetallen){
if (getal < kleinsteGetal && getal != 0){
kleinsteGetal = getal;
}
}
boolean isDividableBy;
boolean ggdFound = false;
while(!ggdFound){
for (int getal : ggdGetallen) {
if (getal != 0){
isDividableBy = (getal % kleinsteGetal == 0);
ggdFound = true;
if(!isDividableBy){
kleinsteGetal--;
ggdFound = false;
break;
}
}
}
}
lblResultaat.setText(String.format("De grootste gemene deler is %d", kleinsteGetal));
}else if(Integer.parseInt(input) != 0 || !input.equals(""));{
ggdGetallen[count] = Integer.parseInt(input);
count++;
txtGetal.selectAll();
}
}

remove semicolon from your else if.

Related

Written code that converts decimal to hexadecimal - but wrong order output

I have written a code that will convert a decimal number to a hexadecimal. Let's take as example the decimal number 123456. My code will give output 042e1, so the total wrong order of the correct result 1e240.
My question, what I need to do to change the order of my output? I planned to convert to String and use new StringBuilder(hi).reverse().toString(). But this seems too complicated, I mean, how shall I take my outputs and convert them to string..? There must be an easier way.
I hope you can help me. I'm very happy I managed to get that far without any help, but I don't know how to get thisy work. This is no homework so feel free to help if you have some time :)
Here is my code:
import java.util.Scanner;
public class Convert{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
double x = input.nextInt();
double result = x;
do{
result = result / 16;
int temp = (int)result;
double rest = result*16-temp*16;
if((int)rest == 10){
System.out.print('a');
}
if((int)rest == 11){
System.out.print('b');
}
if((int)rest == 12){
System.out.print('c');
}
if((int)rest == 13){
System.out.print('d');
}
if((int)rest == 14){
System.out.print('e');
}
if((int)rest == 15){
System.out.print('f');
}
if((int)rest != 10 && (int)rest != 11 && (int)rest != 12 && (int)rest != 13 && (int)rest != 14 && (int)rest != 15){
System.out.print((int)rest);
}
}while((int)result != 0);
}
}
First, you'll need to make a StringBuilder object:
StringBuilder builder = new StringBuilder(); // place this before the do while block
then within each if block do this:
if((int)rest == 10){
builder.append("a");
}
if((int)rest == 11){
builder.append("b");
}
if((int)rest == 12){
builder.append("c");
}
....
....
Considering you've mentioned:
My code will give output 042e1, so the total wrong order of the
correct result 1e240.
then after the do while loop, simply reverse() it to yield the output 1e240:
System.out.println(builder.reverse());

Trying to get the code to check if there are even brackets

I am currently trying to come up with a code that will scan a string
and check to see if there is an even number of open and closing brackets on each line. If so, it would return true. (Excuse me for the incorrectness in formatting but I could not get the examples to properly take shape unless I identified it as code)
{} // The code would return true
{{}}
{}{}
{{{}{{}}}}
} // The code would return false
{}
}}{
{{{}{}
What I tried so far:
public boolean bracketsMatch(String brackets)
{
int lb = 0;
int rb = 0;
int i = 0;
while (brackets.charAt(i) == '{' || brackets.charAt(i) == '}' || brackets.charAt(i) == '')
{
if (brackets.charAt(i) == '{')
{
lb += 1;
}
if (brackets.charAt(i) == '}')
{
rb += 1;
}
if (brackets.charAt(i) == '')
{
if (lb / rb == 2)
{
// Is it possible to get the code scan the next line to next line?
// need an extra statement here for ^^ before I can place the if statement below
if (bracket.charAt(i + 1) == '')
{
return true;
}
}
else
{
return false;
}
}
i++
}
}
I apologize in advance for any experienced programmers as this would be an inefficient nightmare. I am relatively new to programming in general. I attempted to have the code check for the number of left brackets (lb) and right brackets (rb). Whenever the code came to an empty string, it would divide lb by rb. If the code did not equal 2, the code would return false. I probably have more than a dozen errors in this code, but I was wondering if there was any way to have the code go onto the next line to scan the next set of brackets. Thanks for any help in advance.
EDIT 1:
public boolean bracketsMatch(String brackets)
{
int balance = 0;
for (int i = 0; i < brackets.length(); i++)
{
char value = brackets.charAt(i);
if (value == '{')
{
balance += 1;
}
else if (value == '}')
{
balance -= 1;
}
}
if (balance != 0)
{
return false;
}
else
{
return true;
}
}
This won't compile, as '' is an invalid character literal:
if (brackets.charAt(i + 1) == '')
And your current approach of counting opening and closing brackets,
and checking the value of lb / rb won't yield the right result.
You don't need to count the right brackets. You only need to count the open brackets, and reduce that count as they get closed.
Here's a sketch of an algorithm you can use,
I hope to not spoil the exercise:
For each character in the string
If it's an open bracket, increment the count
If it's a close bracket
If the open count is 0, there's nothing to close, so they are not balanced, we can stop
Decrement the count
After all characters, if the open count is 0, the brackets are balanced
As an additional code review note, this is bad in many ways:
if (brackets.charAt(i) == '{') {
// ...
}
if (brackets.charAt(i) == '}') {
// ...
}
What's bad:
Calling brackets.charAt(i) repeatedly is unnecessary if the result will always be the same. Call it once and save the result in a variable.
The two if conditions are exclusive: if the first is true, the second won't be true, so it's pointless to evaluate it. The second condition should be if else instead of if. And instead of an if-else chain, a switch could be more interesting here.
Instead of calling the string brackets, it would be better to call it something more general. What if the actual input is "{something}"? Then it contains more than just brackets, but the algorithm would work just the same. Calling it brackets is misleading.
Alternative way to do
You can use Java Stack class [As it represent the List-In-First-Out stack of object].You can use the push and pop method of Stack class. Here is the implementation.
public class BracketMatching {
public static boolean bracketMatch(String input){
Stack<Character> st = new Stack<>();
for(char c : input.toCharArray()){
if( c == '{')
st.push(c);
else if(c == '}'){
if(st.isEmpty())
return false;
st.pop();
}
}
if(st.isEmpty())
return true;
return false;
}
public static void main(String[] args){
String input1 = "{}{{}}{}{}{{{}{{}}}}";
String input2 = "}{}}}{{{{}{}";
System.out.println(bracketMatch(input1));
System.out.println(bracketMatch(input2));
}
}

How to Match Parenthesis to Parse a S-Expression?

I am trying to create a function that does the following:
Assuming that the code input is "(a 1 2 (b 3 4 5 (c 6) |7) 8 9)"
where the pipe | symbol is the position of the cursor,
the function returns:
a String "b 3 4 5 (c 6) 7" representing the code that is in the scope of the cursor
an int 8 representing the start index of the string relative to the input
an int 30 representing the end index of the string relative to the input
I already have working code that returns exactly that. However, the problem lies in ignoring comments, while keeping track of context (e.g. String literals, my own literal delimiters, etc).
Here is the code which keeps track of context:
public static void applyContext(Context context, String s, String snext, String sprev) {
if (s.equals("\"")) {
if (context.context == Context.Contexts.MAIN) {
context.context = Context.Contexts.STRING;
context.stringDelimiterIsADoubleQuote = true;
} else if (context.context == Context.Contexts.STRING && context.stringDelimiterIsADoubleQuote && !sprev.equals("\\"))
context.context = Context.Contexts.MAIN;
} else if (s.equals("\'")) {
if (context.context == Context.Contexts.MAIN) {
context.context = Context.Contexts.STRING;
context.stringDelimiterIsADoubleQuote = false;
} else if (context.context == Context.Contexts.STRING && !context.stringDelimiterIsADoubleQuote && !sprev.equals("\""))
context.context = Context.Contexts.MAIN;
} else if (s.equals("/") && snext.equals("/")) {
if (context.context == Context.Contexts.MAIN)
context.context = Context.Contexts.COMMENT;
} else if (s.equals("\n")) {
if(context.context == Context.Contexts.COMMENT)
context.context = Context.Contexts.MAIN;
}
else if (s.equals("\\")) {
if(context.context == Context.Contexts.MAIN)
context.context = Context.Contexts.PATTERN;
else if(context.context == Context.Contexts.PATTERN)
context.context = Context.Contexts.MAIN;
}
}
Firstly, I'll be using the function above like so:
String sampleCode = "(a b "cdef" g \c4 bb2 eb4 g4v0.75\)";
Context c = new Context(Context.Contexts.MAIN);
for(int i = 0; i < sampleCode.length(); i++) {
String s = String.valueOf(sampleCode.charAt(i));
String snext = *nullcheck* ? String.valueOf(sampleCode.charAt(i + 1)) : "";
String sprev = *nullcheck* ? String.valueOf(sampleCode.charAt(i - 1)) : "";
applyContext(c, s, snext, sprev);
if(c.context == blahlbah) doBlah();
}
Second, I'll be using this both forwards an backwards, as the current method of doing the function stated at the top of the description is (in pseudocode) this:
function returnCodeInScopeOfCursor(theWholeCode::String, cursorIndex::int) {
var depthOfCodeAtCursorPosition::int = getDepth(theWholeCode, cursorIndex);
Context c = new Context(getContextAt(theWholeCode, cursorIndex));
var currDepth::int = depthOfCodeAtCursorPosition;
var startIndex::int, endIndex::int;
for(i = cursorIndex; i >= 0; i--) {//going backwards
s = .....
snext = ......
sprev = ......
applyContext(c, s, snext, sprev);
if(c.context == Context.MAIN) {
if s = "(" then currDepth --;
if s = ")" then currDepth ++;
}
when currDepth < depthOfCodeAtCursorPosition
startIndex = i + 1;
break;
}
currDepth = depthOfCodeAtCursorPosition;//reset
for(i = cursorIndex; i < theWholeCode.length; i++) {//going forwards
s = ...
snex......
sprev.....
applyContext(c, s, snext, sprev);
if(c.context == Context.MAIN) {
if s = "(" then currDepth ++;
if s = ")" then currDepth --;
}
when currDepth < depthOfCodeAtCursorPosition
endIndex = i - 1;
break;
}
var returnedStr = theWholeCode->from startIndex->to endIndex
return new IndexedCode(returnedStr, startIndex, endIndex);
As you can see, this function would work both forwards and in reverse. Or at least most of it. The only problem is that if I were to use this function backwards, the proper scanning of comments (denoted by the standard ECMA double slash "//") goes haywire.
If I were to create a separate function for reverse context application and check every line recursively for a double slash, then making everything after that '//' a COMMENT (or in the direction of the function's usage, everything before that //), it will take way too much processing time as I want to use this as a livecoding environment for music.
Also, removing the comments before trying to do that returnCodeInScopeOfCursor method may not be feasible... as I need to keep track of the indexes of the code and what not. If I were to remove the comments, there will be a big mess with all the code positions and keeping track of where did I remove what exactly and how many characters etc....
The text area input GUI I'm working with (RichTextFX) does not support Line-Char tracking, so everything is tracked using char index only, hence the problems...
So... I'm utterly perplexed as with what to do with my current code. Any help, suggestions, advice etc... will be greatly appreciated.
Could you pre-transform comments from // This is a comment<CR> to { This is a comment}<CR> you then have a language you can walk backwards and forwards.
Apply this transform on the way in and reverse it on the way out and all should be well. Notice we are replacing //... with {...} so all charaqcter offsets are retained.
Anyways, after a little experimenting with OldCurmudgeon's idea, I came up with a separate function to get context of the code in a reverse direction.
public static void applyContextBackwards(Context context, String entireCode, int caretPos) {
String s = String.valueOf(entireCode.charAt(caretPos));
//So far this is not used
//String snext = caretPos + 1 < entireCode.length() ? String.valueOf(entireCode.charAt(caretPos + 1)) : "";
String sprev = caretPos - 1 >= 0 ? String.valueOf(entireCode.charAt(caretPos - 1)) : "";
//Check for all the flags and what not...
if(context.commentedCharsLeft > 0) {
context.commentedCharsLeft--;
if(context.commentedCharsLeft == 0)
context.context = Context.Contexts.MAIN;//The comment is over
}
if(context.expectingEndOfString){
context.context = Context.Contexts.MAIN;
context.expectingEndOfString = false;
}
if(context.expectingEndOfPattern) {
context.context = Context.Contexts.MAIN;
context.expectingEndOfPattern = false;
}
//After all the flags are cleared, do this
if(context.commentedCharsLeft == 0) {
if (s.equals("\"")) {
if (context.context == Context.Contexts.MAIN) {
context.context = Context.Contexts.STRING;
context.stringDelimiterIsADoubleQuote = true;
} else if (context.context == Context.Contexts.STRING && context.stringDelimiterIsADoubleQuote && !sprev.equals("\\"))
context.expectingEndOfString = true;//Change the next char to a MAIN, cuz this one's still part of the string
} else if (s.equals("\'")) {
if (context.context == Context.Contexts.MAIN) {
context.context = Context.Contexts.STRING;
context.stringDelimiterIsADoubleQuote = false;
} else if (context.context == Context.Contexts.STRING && !context.stringDelimiterIsADoubleQuote && !sprev.equals("\""))
context.expectingEndOfString = true;//Change the next char to a MAIN, cuz this one's still part of the string
} else if (s.equals("\n")) {
int earliestOccuranceOfSingleLineCommentDelimiterAsDistanceFromThisNewLine = -1;//-1 for no comments
//Loop until the next \n is found. In the process, determine location of comment if any
for(int i = caretPos; i >= 0; i--) {
String curr = String.valueOf(entireCode.charAt(i));
String prev = i - 1 >= 0 ? String.valueOf(entireCode.charAt(i - 1)) : "";
if(curr.equals("\n"))
break;//Line has been scanned through
if(curr.equals("/") && prev.equals("/"))
earliestOccuranceOfSingleLineCommentDelimiterAsDistanceFromThisNewLine = caretPos - i;
}
//Set the comment context flag
//If no comments, -1 + 1 will be 0 and will be treated as no comments.
context.commentedCharsLeft = earliestOccuranceOfSingleLineCommentDelimiterAsDistanceFromThisNewLine + 1;
if(earliestOccuranceOfSingleLineCommentDelimiterAsDistanceFromThisNewLine > 0) {
context.context = Context.Contexts.COMMENT;
}
} else if (s.equals("\\")) {
if (context.context == Context.Contexts.MAIN)
context.context = Context.Contexts.PATTERN;
else if (context.context == Context.Contexts.PATTERN)
context.expectingEndOfPattern = true;//Change the next char to a MAIN cuz this one's still part of the Pattern
}
}
}

Checking if an IPv4 address is valid

I am trying to write a basic program in Java that checks if an IP address is valid. I am trying to use no external classes other than the Scanner class and also no regular expressions.
My code, available at this gisttakes in 4 integers as input, one for each octet. I also have this codewhich is a little more readable than the first but is longer.
My question is, is there any other way to implement this idea in significantly fewer lines, and if so, how would I accomplish this?
While this code segment is a bit verbose, it is simple, self-descriptive, and has proven to be tight.
private static boolean isIPAddressValid(String ip) {
boolean result = true;
int i = 0;
int [] val = new int[4];
if ((ip == null) || (ip.trim().length() == 0))
{
//null ip address entered
result = false;
}
else
{
if (!(ip.contains(".")))
{
//no '.' found
result = false;
}
else
{
String [] parts = ip.split("\\.");
if (!(parts.length == 4))
{
//not 4 quadrants
result = false;
}
else
{
for (String s : parts) {
try {
val[i] = Integer.parseInt(s);
if ((val[i] < 0) || (val[i] > 255))
{
//this quadrant's value exceeds limits
result = false;
}
i++;
} catch (Exception e) {
//failed to parse quadrant to an integer");
result = false;
}
}
}
}
}
return result;
}
only some minor enhancements (i think your code looks very good - my opinio so far) it is clearly to read and all work blocks are properly to understand....
boolean isFailed = false;
if (first < 0 || first > 255) {
System.out.println("Octet 1 is invalid");
isFailed = true;
}
if (second < 0 || second > 255) {
System.out.println("Octet 2 is invalid");
isFailed = true;
}
if (third < 0 || third > 255) {
System.out.println("Octet 3 is invalid");
isFailed = true;
}
if (fourth < 0 || fourth > 255) {
System.out.println("Octet 4 is invalid");
isFailed = true;
}
if (!isFailed){
System.out.println("IP Address: " + first + "." + second + "." + third + "." + fourth);
}
so i simply invert the order of printing - that saves you only that big check before...
your approach was to can check each octet...
you can simply do this 4 times or write a method for it:
private static boolean check(int octet, int index){
if (0xFF & octet < 256) return true;
System.out.println("Octet "+index+" is invalid";
return false;
}
and use this method in your main method
if (check(first,0) && check (second, 2) && check (third, 3) && check(fourth, 4) ){
System.out.println("your ip is valid");
}
note - this only reveals the first invalid octet - if you want to check all you need another boolean
boolean result = check(first,0) &&
check (second, 2) &&
check (third, 3) &&
check(fourth, 4); //reveals all errors
a totally different approach would be to use http://docs.oracle.com/javase/7/docs/api/java/net/InetAddress.html#getByName%28java.lang.String%29
try{
/*InetAdress adress =*/ InetAdress.
getByName(""+first+"."+second+"."+third+"."+forth)
System.out.println("your ip is valid");
}catch (UnknownHostException e){
//TODO represent that error message into a nice expression
System.out.println("your ip is invalid");
}
but this as well doesn't provide information about that octet which is invalid...
(by the way - what is wrong with your code? it's fine, really!)
I was just bored and wrote this regexp
public static boolean isValid(String ip) {
boolean isvalid;
isvalid = ip.matches(
"(([0-9]|[0-9]{0,2}|1[0-9]*{0,2}|2[0-5][0-5]|0{0,3}).){3}" +
"([0-9]|[0-9]{0,2}|1[0-9]*{0,2}|2[0-5][0-5]|0{0,3})"
);
return isvalid;
}
And it was tested on the following dataset:
String[] ips = {
"0.0.0.0",
"0.111.222.0",
"0.0.0.000",
"0.00.0.000",
"1.1.1.1",
"2.2.2.2",
"12.13.14.15",
"29.29.29.29",
"99.99.000.1",
"111.102.144.190",
"255.255.199.199",
"266.255.255.255", //inv
"255.265.255.255", //inv
"255.255.258.255", //inv
"255.255.255.259", //inv
"299.100.110.255" //inv
};
for (String s : ips) {
if (isValid(s) == false) {
System.err.println(s + " is invalid");
}
}

While Loops and Reverse Fibonacci

I've come across a problem. I'm trying to make a class which takes the maximum number that a user puts in and adds the integer before it until it gets to 0, however, when I run it, the numbers get larger and larger until it crashes. What seems to be throwing this into an infinite loop?
public class Summation {
public static void main(String[] args) {
EasyReader console = new EasyReader();
System.out.print("Debug? (Y/N): ");
char debug = console.readChar();
if ((debug!='Y')&&(debug!='N')){
System.out.println("Please enter Y or N");
main(null);
}
else{
System.out.print("Enter max range:");
int max = console.readInt();
int s = sum(max,debug);
System.out.print(s);
}
}
public static int sum(int m, char d){
int sm = 1;
boolean isRunning = true;
while ((isRunning == true)&&(d=='Y')){
if ((--m)==0) {
isRunning = false;
}
else{
sm = m+(--m);
System.out.println("sm is"+sm);
}
while ((isRunning == true)&&(d=='N')){
if ((--m)==0) {
isRunning = false;
}
else{
sm = m+(--m);
}
}
}return sm;
}
}
There's a scenario where your condition for exit
if ((--m)==0)
will never again be reached, because m is already less than 0, and it's never going back.
that scenario is whenever m is an even number.
while ((isRunning == true)&&(d=='Y'))
{
// this condition decriments `m` every time it runs, regardless of whether it evaluates to true
if ((--m)==0)
{
// if `m` was set to 0 on your last iteration, it will be set to -1
isRunning = false;
}
else
{
// if m is 1 before this line it will be 0 after it.
sm = m+(--m);
System.out.println("sm is"+sm);
}
while ((isRunning == true)&&(d=='N'))
{
// this code will never get executed
}
}
return sm;
Answer to your problem is very simple
Just modify the condition
if (m==0) {
isRunning = false;
}
When you are checking --m == 0, it is very much possible that m will be jumping over 0 and will enter negative territory without even setting this condition to be true.
Everything you are doing is wrong :).
First - FORMATTING. You maybe even dont know that, but the second while is INSIDE the first while cycle. If you use netbeans, its ALT+SHIFT+F.
The using of --m is not good for your example, cause it firsts decrease the "m" value and then it compares. So even when you asking at
(--m)==0
you decrease a value. And because you are using it again at
sm = m+(--m)
you can even skip the "0" value and get into negative numbers.
However if you want only "add numbers in reverse order from given number to 0 in while loop" it is not fibonacci and you can use this code (it could be done better, but this is using your code) :
public class Summation {
public static void main(String[] args) {
System.out.println(sum(10, 'Y'));
}
public static int sum(int m, char d) {
int sm = 0;
boolean isRunning = true;
while ((isRunning == true) && (d == 'Y')) {
sm += m;
if (m == 0) {
isRunning = false;
} else {
m--;
System.out.println("sm is" + sm);
}
while ((isRunning == true) && (d == 'N')) {
if ((--m) == 0) {
isRunning = false;
} else {
sm = m + (--m);
}
}
}
return sm;
}
}
Note that second while cycle couldnt be reached - it passes only when "d == Y" and then it starts only when "d == N"

Categories

Resources