How to use try-catch in Java? - exception

I am trying to learn try and catch block but with below code something is missing, and my code is not giving my custom error given in catch block. What is the problem here?
Here is my code :
package com.example.java;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int num1;
int num2;
String operatorValue;
System.out.println("Please Enter First Number :");
Scanner firstInput = new Scanner(System.in);
num1 = firstInput.nextInt();
System.out.println("Please Enter Second Number :");
Scanner secondInput = new Scanner(System.in);
num2 = secondInput.nextInt();
System.out.println("Please Select operation + - * / % :");
Scanner operatorInput = new Scanner(System.in);
operatorValue = operatorInput.nextLine();
double results = 0;
try {
switch (operatorValue) {
case "+":
results = num1 + num2;
break;
case "-":
results = num1 - num2;
break;
case "*":
results = num1 * num2;
break;
case "/":
results = num1 / num2;
break;
case "%":
results = num1 % num2;
break;
default:
System.out.println("please Enter a valid operator value");
return;
}System.out.println("The Result is :"+ results);
} catch (Exception e) {
System.out.println("please enter a valid number "+ e.getMessage());
}
}
}

Your try...catch block doesn't include the input part. This is the part that is problematic so wrap it instead of the calculation:
int num1;
int num2;
String operatorValue;
try {
System.out.println("Please Enter First Number :");
Scanner firstInput = new Scanner(System.in);
num1 = firstInput.nextInt(); // can produce error
System.out.println("Please Enter Second Number :");
Scanner secondInput = new Scanner(System.in);
num2 = secondInput.nextInt(); // can produce error
System.out.println("Please Select operation + - * / % :");
Scanner operatorInput = new Scanner(System.in);
operatorValue = operatorInput.nextLine();
} catch (Exception e) {
System.out.println("please enter a valid number "+ e.getMessage());
}
// Rest of code

Related

Java Exception throw creates an infinite loop

I have established a do-while loop to verify user input is valid. If a 0 or negative number is entered, the Exception is thrown and the catch prints out. However, if a string is entered (i.e., twenty instead of 20) it becomes an infinite loop constantly printing out "Invalid input!!", asking for user input, and printing out "Invalid input!!" again. Here's my code:
import java.util.Scanner;
public class Paint {
public static void main(String[] args) {
// Create object for the scanner class
Scanner scnr = new Scanner(System.in);
//Declare variables
double wallHeight = 0.0;
double wallWidth = 0.0;
double wallArea = 0.0;
double gallonsPaintNeeded = 0.0;
final double squareFeetPerGallons = 350.0;
//Implement a do-while loop to verify user provides valid input
do {
try {
//Prompt user for wall's height in feet
System.out.println("Enter wall height (feet): ");
wallHeight = scnr.nextDouble();
//Verify wallHeight is not less than or equal to zero
//If so, throw an exception
if(wallHeight <= 0) {
throw new Exception();
}
}
catch(Exception e) {
//Print invalid message
System.out.println("Invalid input!!");
}
}
while(wallHeight <= 0);
//Implement a do-while loop to verify user provides valid input
do {
try {
//Prompt user for wall's width in feet
System.out.println("Enter wall width (feet):");
wallWidth = scnr.nextDouble();
//Verify wallWidth is not less than or equal to zero
//If so, throw an exception
if(wallWidth <= 0) {
throw new Exception();
}
}
catch(Exception e) {
//Print invalid message
System.out.println("Invalid input");
}
}
while(wallWidth <= 0);
//Calculate wallArea
wallArea = wallHeight * wallWidth;
//Print wallArea
System.out.println("Wall area: " + wallArea + " square feet");
//Calculate gallonsPaintNeeded
gallonsPaintNeeded = wallArea / squareFeetPerGallons;
//Print paint needed
System.out.println("Paint needed: " + gallonsPaintNeeded + " gallons");
}
}

Java:Handling Exception and cant able to input value

package scheme;
import java.math.BigDecimal;
import java.util.Scanner;
public class EnterSchemeDetails {
private Scanner sc;
public static void main(String []args){
EnterSchemeDetails schemes=new EnterSchemeDetails();
schemes.add();
}
public void add() {
NewEntry newEntry = new NewEntry();
String newOne = "newrecord";
sc = new Scanner(System.in);
System.out.println("Enter No of Times ");
int no = sc.nextInt();
for (int i = 1; i <= no; i++) {
System.out.println("Enter Scheme " + i);
gettingSchemeDetails(newOne, newEntry);
}
boolean condition = displayOption(newEntry);
if (condition) {
System.out.println("Stopped Working");
} else {
System.out.println("Wrong Input Specify Numeric value ");
displayOption(newEntry);
}
}
public boolean displayOption(NewEntry newEntry) {
String newOne = null;
System.out.println("Enter Option ");
System.out
.println("1.Display \t 2.Insert \t 3.Update \t 4.Delete \t 5.Exit");
int option = 0;
try {
option = sc.nextInt();
while (option != 5) {
if (option == 1) {
newEntry.display();
} else if (option == 2) {
newOne = "insert";
gettingSchemeDetails(newOne, newEntry);
} else if (option == 3) {
newOne = "update";
gettingSchemeDetails(newOne, newEntry);
} else if (option == 4) {
System.out.println("Enter Scheme No to Delete");
int schemeNo = sc.nextInt();
boolean check = newEntry.deleteOperation(schemeNo);
if (check) {
System.out.println("Deleted Successfully");
} else {
System.out.println("No such Record Found");
}
} else if (option == 5) {
System.out.println("Stopped");
} else {
System.out.println("Invalid Option");
}
System.out.println("Enter Option ");
System.out
.println("1.Display \t 2.Insert \t 3.Update \t 4.Delete \t 5.Exit");
option = sc.nextInt();
}
} catch (Exception e) {
return false;
}
return true;
}
public void gettingSchemeDetails(String newOne, NewEntry newEntry) {
sc = new Scanner(System.in);
int schemeNo = 0;
if (newOne == "update") {
System.out.println("Enter Scheme No to Update");
try {
schemeNo = sc.nextInt();
boolean check = newEntry.checkSchemeNo(schemeNo);
if (check == false) {
System.out.println("NO such record found");
displayOption(newEntry);
}
} catch (Exception e) {
System.out.println("Invalid Option");
displayOption(newEntry);
}
}
SchemeInfo bean = new SchemeInfo();
System.out.println("Enter Scheme Name :");
bean.setSchemeName(sc.next());
System.out.println("Enter Fund Name :");
bean.setFundName(sc.next());
gettingNavDate(bean);
try {
gettingNavAmount(bean);
} catch (Exception e) {
System.out.println("Input Mismatch enter Numeric value");
gettingNavAmount(bean);
}
try {
gettingNavUnits(bean);
} catch (Exception e) {
System.out.println("Input Mismatch enter Numeric value");
gettingNavUnits(bean);
}
gettingCategories(bean);
if (newOne != "update") {
newEntry.newRecord(bean);
} else {
newEntry.update(schemeNo, bean);
}
}
public void gettingNavDate(SchemeInfo bean) {
sc = new Scanner(System.in);
System.out.println("Enter Nav Date :");
String navDate = sc.next();
boolean check = NavDateCheck.checkDateFormat(navDate);
if (check == true) {
bean.setNavDate(navDate);
} else {
System.out
.println("Incorrect Date Format..Please Enter Correct Date Format Ex.YYYY-MM-DD");
gettingNavDate(bean);
}
}
public void gettingNavAmount(SchemeInfo bean) {
sc = new Scanner(System.in);
System.out.println("Enter Schmene Nav Amount :");
BigDecimal navAmount = new BigDecimal("0");
navAmount = sc.nextBigDecimal();
boolean check1 = NavDateCheck.checkNavAmount(navAmount);
if (check1 == true) {
bean.setNavAmount(navAmount);
} else {
System.out
.println("Incorrect NavAmount.Enter Correct Nav Amount.Ex.1000.21 ");
gettingNavAmount(bean);
}
}
public void gettingNavUnits(SchemeInfo bean) {
sc = new Scanner(System.in);
System.out.println("Enter Nav Units :");
BigDecimal navUnits = new BigDecimal("00");
navUnits = sc.nextBigDecimal();
boolean check2 = NavDateCheck.checkNavUnits(navUnits);
if (check2 == true) {
bean.setNavUnits(navUnits);
} else {
System.out
.println("Incorrect Nav Units.Enter Correct NavUnits Ex.");
gettingNavUnits(bean);
}
}
public void gettingCategories(SchemeInfo bean) {
sc = new Scanner(System.in);
System.out.println("Enter Divident Option :");
bean.setDividentOption(sc.next());
System.out.println("Enter Scheme Plan Name ");
bean.setSchemePlanName(sc.next());
System.out.println("Enter Scheme Category ");
bean.setSchemeCategory(sc.next());
System.out.println("Enter Scheme Subcategory");
bean.setSchemeSubcategory(sc.next());
}
}
I have 2 problems in my code
1.when giving characters/string(other than number) it will throw an exception and i have handled the exception.But second time i cant able to give user input to that option
Enter No of Times
1
Enter Scheme 1
Enter Scheme Name :
SchemeSample
Enter Fund Name :
FundSample
Enter Nav Date :
1234-12-1
Enter Schmene Nav Amount :
17826
Enter Nav Units :
7328736
Enter Divident Option :
SampleDivident
Enter Scheme Plan Name
SamplePlaan
Enter Scheme Category
SampleCategory
Enter Scheme Subcategory
SampleSubCategory
Enter Option
1.Display 2.Insert 3.Update 4.Delete 5.Exit
f
Wrong Input Specify Numeric value
Enter Option
1.Display 2.Insert 3.Update 4.Delete 5.Exit

cannot implement actionPerformed(ActionEvent) in ActionListener

I am making a profile encryption program with 2 ciphers. I want to have a GUI with buttons for enciphering, deciphering and exiting.
My problem is with the actionPerformed method. It needs to throw the exception that the outputStream throws. This is the error I get when I try to complie it:
:53: error: actionPerformed(ActionEvent) in ProfileEncryption_2 cannot implement actionPerformed(ActionEvent) in ActionListener
public void actionPerformed (ActionEvent e) throws FileNotFoundException//When a button is clicked
I have though of multiple solutions, but am not sure how to implement them properly. I could catch the exception and do something with it, but I am not sure how and what. I could also check if the file exists, and if so, then output, but what I tried for that didn't work either.
public void actionPerformed (ActionEvent e) throws Exception //When a button is clicked
{
if (e.getSource() == encrBtn)
{
menu.setVisible(false);
createProfile();
menu.setVisible(true);
}
else
{
if (e.getSource() == decrBtn)
{
menu.setVisible(false);
viewProfile();
menu.setVisible(true);
}
else
{
if (e.getSource() == exitBtn)
{
JOptionPane.showMessageDialog(null, "Goodbye!");
System.exit(0);
}
}
}
}
//End of menu
//Start of create/view section
public static void createProfile() throws Exception //Create profile
{
String username = JOptionPane.showInputDialog("Enter your username.");
String password, confirmPass, strEncrType;
int intEncrType = 0, unlock = 0;
do
{
password = JOptionPane.showInputDialog("Enter your password.\nIt must be more than 7 characters long.");
confirmPass = JOptionPane.showInputDialog("Confirm password");
if (password.equals(confirmPass) && (password.length() >= 7))
{
JOptionPane.showMessageDialog(null, "Passwords match!");
unlock = 1;
}
else
{
if (!password.equals(confirmPass))
JOptionPane.showMessageDialog(null, "Passwords do not match!");
if (password.length() < 7)
JOptionPane.showMessageDialog(null, "Password is not long enough!");
}
}
while (unlock==0);
do
{
strEncrType = JOptionPane.showInputDialog("Choose which encryption type you would prefer:\n1. Vigenère\n2. Erénegiv mod 4");
if(!strEncrType.equals("1")&&!strEncrType.equals("2"))
JOptionPane.showMessageDialog(null, "Invalid response, try again.");
}
while (!strEncrType.equals("1")&&!strEncrType.equals("2"));
intEncrType = Integer.parseInt(strEncrType);
String name = JOptionPane.showInputDialog("Enter your real name.");
String phone = JOptionPane.showInputDialog("Enter your phone number.");
String email = JOptionPane.showInputDialog("Enter your email.");
String other = JOptionPane.showInputDialog("Enter notes/extra data you want stored.");
String data = password + "-" + username + "-tester-" + name + "-" + phone + "-" + email + "-" + other + "-" + strEncrType;
if (intEncrType ==1)
data = encrypt1(data);
else
data = encrypt2(data);
data = data + strEncrType;
OutputStream output = new FileOutputStream(username + ".txt");
byte buffer[] = data.getBytes();
output.write(buffer);
output.close();
}

Drawing a route between 2 locations Google Maps API Android V2

I was playing around with the Google Maps API V2 on android.
Trying to get a path between 2 locations and doing this with the JSON Parsing.
I am getting a route. and the route starts out how it should be. but then at one point it goes the wrong way.
My end destination ends up wrong. And with some other locations my app just gets terminated.
This is what i have done
Here is my makeURL method
public String makeUrl(){
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.googleapis.com/maps/api/directions/json");
urlString.append("?origin="); //start positie
urlString.append(Double.toString(source.latitude));
urlString.append(",");
urlString.append(Double.toString(source.longitude));
urlString.append("&destination="); //eind positie
urlString.append(Double.toString(dest.latitude));
urlString.append(",");
urlString.append(Double.toString(dest.longitude));
urlString.append("&sensor=false&mode=driving");
return urlString.toString();
}
my JSON parser
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
// TODO Auto-generated constructor stub
}
public String getJSONFromURL(String url){
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch(UnsupportedEncodingException e){
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
sb.append(line + "\n");
//Log.e("test: ", sb.toString());
}
json = sb.toString();
is.close();
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e("buffer error", "Error converting result " + e.toString());
}
return json;
}
I draw my Path with this method
public void drawPath(String result){
try{
final JSONObject json = new JSONObject(result);
JSONArray routeArray = json.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
Log.d("test: ", encodedString);
List<LatLng> list = decodePoly(encodedString);
LatLng last = null;
for (int i = 0; i < list.size()-1; i++) {
LatLng src = list.get(i);
LatLng dest = list.get(i+1);
last = dest;
Log.d("Last latLng:", last.latitude + ", " + last.longitude );
Polyline line = googleMap.addPolyline(new PolylineOptions().add(
new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude, dest.longitude))
.width(2)
.color(Color.BLUE));
}
Log.d("Last latLng:", last.latitude + ", " + last.longitude );
}catch (JSONException e){
e.printStackTrace();
}
}
And I decode my JSON with
private List<LatLng> decodePoly(String encoded){
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0;
int length = encoded.length();
int latitude = 0;
int longitude = 0;
while(index < length){
int b;
int shift = 0;
int result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int destLat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
latitude += destLat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b > 0x20);
int destLong = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
longitude += destLong;
poly.add(new LatLng((latitude / 1E5),(longitude / 1E5) ));
}
return poly;
}
And then coded with an AsyncTask
Thanks in advance.
Sorry for the long wait.. i have fixed it a while ago but i hadn't put my solution on here yet.
It was basically a typo...
In my Json decoder i use 2 Do while statements with
while (b >= 0x20);
In the second Do While statement i forgot the "=".
Therefore it wasn't rendering correctly...
thanks
I believe that you are creating your LatLng objects from overview_polyline. This, according to Google documentation "contains an object holding an array of encoded points that represent an approximate (smoothed) path of the resulting directions.".
I'm pretty sure that you can get a more detailed route building your LatLng object based on legs[] and steps[] data as the official documentation states that A step is the most atomic unit of a direction's route, containing a single step describing a specific, single instruction on the journey.
Take a look at:
https://developers.google.com/maps/documentation/directions/#Routes
Tmichel,
the Michael has the correctly wave, because on legs and steps on your route plot the line out of the street.
Legs and steps, has informations around coordinates for informations to alert the user.
Polylines are the correct and precise points over the street.
Sorry my bad english

How can I convert the decimal representation of an IP address into binary?

Does anyone knows how to convert decimal notation of an IP address into binary form in Java? Please let me know...
An IP address written as a.b.c.d can be converted to a 32-bit integer value
using shift and bit-wise inclusive OR operators as,
(a << 24) | (b << 16) | (c << 8) | d
To be safe, each of a,b,c,d has valid range 0-255 -- you can check that in your conversion.
You can further validate the IP address using this regex example.
You can use the java.net.InetAddress class. Two methods you should look at are getByName and getAddress. Here is a simple code example
import java.net.InetAddress;
import java.net.UnknownHostException;
/* ... */
String ip = "192.168.1.1";
InetAddress address = null;
try {
address = InetAddress.getByName(ip);
} catch (UnknownHostException e) {
//Your String wasn't a valid IP Address or host name
}
byte [] binaryIP = address.getAddress();
Gathering your suggestions and some other sources, I found usefull to convert an InetAdress to an array of bit, as well as BitSet, which can help to compute and(), or(), xor() out of your binary representation.
Following sample shows how to convert ip to binary and binary to ip.
Enjoy!
public class IpConverter {
public static void main(String[] args) {
String source = "192.168.1.1";
InetAddress ip = null;
try {
ip = InetAddress.getByName(source);
} catch (UnknownHostException e) {
e.printStackTrace();
return;
}
System.out.println( "source : " + ip);
// To bit sequence ------------
byte[] binaryIP = ip.getAddress();
BitSet[] bitsets = new BitSet[binaryIP.length];
int k = 0;
System.out.print("to binary: ");
for (byte b : binaryIP) {
bitsets[k] = byteToBitSet(b);
System.out.print( toString( bitsets[k] ) + ".");
k++;
}
System.out.println();
// Back to InetAdress ---------
byte[] binaryIP2 = new byte[4];
k = 0;
for (BitSet b : bitsets) {
binaryIP2[k] = bitSetToByte(b);
k++;
}
InetAddress ip2 = null;
try {
ip2 = InetAddress.getByAddress(binaryIP2);
} catch (UnknownHostException e) {
e.printStackTrace();
return;
}
System.out.println( "flipped back to : " + ip2);
}
public static BitSet byteToBitSet(byte b) {
BitSet bits = new BitSet(8);
for (int i = 0; i < 8; i++) {
bits.set(i, ((b & (1 << i)) != 0) );
}
return bits;
}
public static byte bitSetToByte(BitSet bits) {
int value = 0;
for (int i = 0; i < 8; i++) {
if (bits.get(i) == true) {
value = value | (1 << i);
}
}
return (byte) value;
}
public static byte bitsToByte(boolean[] bits) {
int value = 0;
for (int i = 0; i < 8; i++) {
if (bits[i] == true) {
value = value | (1 << i);
}
}
return (byte) value;
}
public static boolean[] byteToBits(byte b) {
boolean[] bits = new boolean[8];
for (int i = 0; i < bits.length; i++) {
bits[i] = ((b & (1 << i)) != 0);
}
return bits;
}
public static String toString(BitSet bits){
String out = "";
for (int i = 0; i < 8; i++) {
out += bits.get(i)?"1":"0";
}
return out;
}
}
The open-source IPAddress Java library can do this for you. It can parse various IP address formats, including either IPv4 or IPv6, and has methods to produce various string formats, including one for binary. Disclaimer: I am the project manager of the IPAddress library.
This code will do it:
static void convert(String str) {
IPAddressString string = new IPAddressString(str);
IPAddress addr = string.getAddress();
System.out.println(addr + " in binary is " + addr.toBinaryString());
}
Example:
convert("1.2.3.4");
convert("a:b:c:d:e:f:a:b");
The output is:
1.2.3.4 in binary is 00000001000000100000001100000100
a:b:c:d:e:f:a:b in binary is 00000000000010100000000000001011000000000000110000000000000011010000000000001110000000000000111100000000000010100000000000001011