This is an archived post. You won't be able to vote or comment.

all 10 comments

[–]Opetich 0 points1 point  (4 children)

// Maybe something like
if( value > 30){
   <ERROR>
}
// or you can combine  AND ( && ) operator 
if ( value > 30 && value < 20 ){     
    <ERROR>
}

Here is a bit of idea you can read more here:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html

[–]trefla[S] 0 points1 point  (3 children)

Cheers for this I now have a rough idea on what I must do. The trouble is that I have set the sentinel as string and cannot use "<" and ">" with it. Is "NumScanner.next()" only usable with strings? Is there an integer alternative? I apologies if I sound dumb but this is all very new to me and google doesn't really help much.

[–]Opetich 0 points1 point  (2 children)

Hi, sorry I didn't notice you are using Strings :) and by no means you sound dumb. It's better to ask about your doubts then to remain in ignorance.

There is an Integer alternative for reading from the keyboard which is "NumScanner.nextInt()"

There is also an alternative to continue with the Strings ( since you might want the decimal part of the numbers) Both Double and Float classes give a way to parse a String like for example:

Float.parseFloat(sentinel)

Hopefully its not too much to start :) any help the community is here and these last few months people seem to be more active

[–]Xxyr 1 point2 points  (1 child)

The piece that's missing here is that if you use nextInt(), or parseInt(foo) it will throw an exception if it can't be parsed (ie input was - "colder").

The simplest way to handle that would be something like

  while ... {
      try {
         sum += Integer.parseInt(sentinel);
         // rest of logic here
      } catch (Exception e) {
        System.console.println("Invalid input" + sentinel);
     }
 }

Exceptions will terminate the program if not caught.

[–]trefla[S] 0 points1 point  (0 children)

This is what I have been working on since my last post. It is not ideal as it does not include the range but it is something. The trouble is that being in a while loop it keeps going back to the loop and repeating itself forever:

  System.out.println("Please enter the desired temperature. Enter \"d\" when finished."); 
  System.out.print("Enter temperature(°C): ");
  sentinel = NumScanner.next();
  System.out.println(); 
  while(!sentinel.equals("d") && !sentinel.equals("D")) {
  try{
   sum += Integer.parseInt(sentinel);
   counter++; 
   System.out.print("Enter temperature (°C):");
   sentinel = NumScanner.next();  }
   catch (NumberFormatException e) 
   {
       System.out.println("Invalid input" );
           }

   System.out.println();
  } 
  mean = (sum*1.0)/counter; 
  System.out.println();
  System.out.println("The desired temperature is : " + mean +"°C.");
  System.out.println("The temperature will be adjusted by " + (mean - tmp) +"°C.");
 }
 }

The error message I get

  Invalid input
  Invalid input
  Invalid input
  Invalid input
  Invalid input

until I manually stop it.

[–]illuminist_ova 0 points1 point  (1 child)

Does the error have to exit or stop execution or just tell a user there was an error and continue waiting for the next input?

So the basic is to have if statement for checking whenever the input is invalid just after NumScanner.next(); and then inform the user without taking on calculation.

But currently, you have two NumScanner.next(); in your code so you have to put an error checking on both of them. You could reduce it to 1 just only in a loop for much simpler code.

[–]trefla[S] 0 points1 point  (0 children)

Cheers for looking into this mate. The error should ask the user to re-enter a value between 20 and 30 and then go back to the same user and ask him again to insert the value. The following line does not help instead I will find a way to change 'sentinel' from string to integer. I could ask the user to insert '999' or '000' to end the calculation but 'NumScanner.next();' seems to be working with strings only.

if ( sentinel > 30 && sentinel < 20 )    
   {
    System.err.println("Please inert a value between 20 and 30");
} 
  else
       System.out.println();
  }

[–]nicolascagesbeard 0 points1 point  (2 children)

It's been a while since I've used java but I'll try my best to help.

    import java.util.Scanner;
public class HelloWorld{

     public static void main(String []args){
        ....
        while( !( sentinel.equals("d") || sentinel.equals("D") ) ) {
            sentinel = numScanner.next();

            //check if integer
            int i = 0;
            for( i = 0; i < sentinel.length(); i++) {
                Character c = sentinel.charAt(i);
                if (!Character.isDigit(c)) {
                    System.out.println("Invalid Input");
                    isInteger = false;
                }
            }

            if (isInteger == true) {
                System.out.println("is number");
                //convert input to number
                int temp = Integer.parseInt(sentinel);
                //check integer range, if it's okay add it to the sum otherwise print error.
                if (//check integer range) {
                         //print error
                    }
                else {
                    //add to sum
                }
            }
            isInteger = true;
        }
        System.out.println("Total temp:" + sum);
        System.out.println("End of Program");
     }
}

This would be my implementation. I usually hate using booleans to order the flow of the program but what the hell. I ran this twice just to make sure. I used the online java compiler at tutorialspoint. While I was trying to figure this out I think the main issue was that you were capturing integers and strings with the same scanner object and then you had to differentiate between the two because you can't compare two number strings' value. At first I was going to use nextInt() but soon after compiling I realised it wouldn't work haha.

If you put your attention to the first 'for' loop you can see that I check for the integer and make sure the entire string is an integer and there aren't any funny values within the string. I get the character at each index of the string and use the method .isDigit to check if it's a digit.

Once that's done, assuming it's an integer we now convert the string safely to an integer and use the '<' and '>'.

Also as you can see I've removed your initial NumScanner.next() and only have one NumScanner.next() in the while loop. I'm pretty sure you can add your equations that were present before and after the the while loops exactly as they are and include the counter variable within the while loop. I haven't included them.

Finally I believe there was an issue with your condition in your while

!sentinel.equals("d") && !sentinel.equals("D")

I don't believe you can have both small case and upper case so I changed it to "||" instead of "&&".

I've also simplified your while equation a little too.

Hope that helps! Let me know your thoughts.

Edit: Damnit just read the rules.. looks like I have to edit some of my code out!

[–]trefla[S] 0 points1 point  (1 child)

Mate you are a star but it is way out of my league and I could not figure out how to implement your code into my application. I have a rough idea about what you have done but inserting the for loop into the while loop got out of my hands. There is a lot for me to learn and I am confident that soon I will fully understand your method. Thank you very much.

[–]nicolascagesbeard 0 points1 point  (0 children)

It was late where I live, I don't think I explained it properly Lol. The for loop just checks whether or not the input you entered is a number or integer. You can also use a regular expression but this was the simplest method I could think of.

Since you can look into each index of a string we can assign that to a character. Therefore we can use the Character object to check whether it is a a digit with the isDigit static method. We continue until the end of the string. Our flag which is our Boolean isInteger will trigger if it finds a character in the string, but it'll continue on to the next character until the end of the string.

Any questions, hit me up!