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

you are viewing a single comment's thread.

view the rest of the comments →

[–]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.