How to use try catch in this code for checking my error - try-catch

I am a beginner in Programming. I want to make sure how to check my errors. In this code, I just write plus operation.
private void number2ActionPerformed(java.awt.event.ActionEvent evt) {
}
private void buttonActionPerformed(java.awt.event.ActionEvent evt) {
double a, b;
a = Integer.parseInt(number1.getText());
b = Integer.parseInt(number2.getText());
result.setText("" + (a + b));
}

private void buttonActionPerformed(java.awt.event.ActionEvent evt) {
try
{
double a, b;
a = Integer.parseInt(number1.getText());
b = Integer.parseInt(number2.getText());
result.setText("" + (a + b));
}
catch(Exception e){
System.out.println("Exception:"+e);
}
}

Related

Having troubles with my binary search in java

When I run the below code I can not get it to give me a positive result. I can get this code to run, but once I add the binary search portion of the code, it keeps telling me my value is not in the list. And I know the value is on the list. Can someone please tell me what I did wrong? I want it to tell me the house value and the year of that value. Any help will be much appreciated.
import javax.swing.JOptionPane;
import java.util.*;
import java.util.Arrays;
static class House implements Comparable<House> {
private int price;
private int year;
public House(int price, int year) {
this.price = price;
this.year = year;
}
public int getPrice() {
return price;
}
public int getYear() {
return year;
}
#Override
public String toString() {
return "{" + "Price='" + price + '\'' +
", Year=" + year + '}';
}
#Override
public int compareTo(House o) {
if (this.year != o.getYear()) {
return this.year - o.getYear();
}
return this.price;
}
}
public static void main(String[] args)
{
BinarySearch ob = new BinarySearch();
House[] house = { new House(85480, 2013), new House(98873, 2012), new House(150592, 2022), new House(98035, 2014),
new House(114730, 2017), new House(178124, 2023), new House(137676, 2019),new House(104548, 2015),
new House(151330, 2021), new House(114730, 2016), new House(144452, 2020), new House(121614, 2018)};
System.out.println("Original Array of House objects:");
System.out.println(Arrays.toString(house));
Arrays.sort(house);
System.out.println("\nSorted Array of House objects:");
System.out.println(Arrays.toString(house));
String input = JOptionPane.showInputDialog("What house value do you want to search for: ");
int input2=Integer.parseInt(input);
int x = input2;
int result = ob.binarySearch(house, x);
if (result == -1)
{
JOptionPane.showMessageDialog(null, "The house value you are looking for is not in the list. ");
}
else
{
JOptionPane.showMessageDialog(null, "The house value is " + x + " year = " + "index " + result);
}
}
static class BinarySearch
{
int binarySearch(House[] house, int x)
{
int left = 0, right = house.length - 1;
while (left <= right)
{
int mid = left + (right - left) / 2;
if (house.length == x)
return mid;
if (house.length < x)
left = mid + 1;
else
right = mid - 1;
}
return -1;
}
}
}

Flink's AggregateFunction's getResult() can change Accumulator value?

Can the getResult() function change the value of the accumulator?It still takes effect value when accumulating.
The code is in below:
public class WeightedAverage implements AggregateFunction<Datum, AverageAccumulator, Double> {
public AverageAccumulator createAccumulator() {
return new AverageAccumulator();
}
public AverageAccumulator merge(AverageAccumulator a, AverageAccumulator b) {
a.count += b.count;
a.sum += b.sum;
return a;
}
public AverageAccumulator add(Datum value, AverageAccumulator acc) {
acc.count += value.getWeight();
acc.sum += value.getValue();
return acc;
}
public Double getResult(AverageAccumulator acc) {
int result = acc.sum / (double) acc.count;
acc.count = 0; //here
acc.sum = 0; //here
return result;
}
}
No, you cannot modify the accumulator during getResult.
Flink will create new accumulators as necessary (e.g., for each new window).

Checking input values with array contents in C#.net

I have an array with 5 integer values.
I need to check each value in it against input values from a text box.
A label displays a Value found message if the input value exists in the array.
If not, theValue not found message is displayed.
How do I display the Value not found message correctly?
Here's my code,
private void button1_Click(object sender, EventArgs e)
{
try
{
int[] id = { 1, 2, 3, 4, 5 };
int row;
int x = Convert.ToInt32(txtid.Text);
for (row = 0; row < id.Length; row++)
{
if (id[row] == x)
{
txtdesc.Text = "Value found!";
}
}
txtdesc.Text = "Value not found!";
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Without going into great detail, using a flag is the simplest way of tracking a Boolean state when you are first starting out.
private void button1_Click(object sender, EventArgs e)
{
try
{
int[] id = { 1, 2, 3, 4, 5 };
int row;
int x = Convert.ToInt32(txtid.Text);
bool found = false;
for (row = 0; row < id.Length; row++)
{
if (id[row] == x)
{
found = true;
}
}
txtdesc.Text = found ? "Value found!" : "Value not found!";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
With LINQ, these things get a lot easier:
// At the top of the file
using System.Linq;
private void button1_Click(object sender, EventArgs e)
{
try
{
int[] id = { 1, 2, 3, 4, 5 };
int x = Convert.ToInt32(txtid.Text);
txtdesc.Text = id.Contains(x) ? "Value found!" : "Value not found!";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
try
{
int[] id = { 1, 2, 3, 4, 5 };
int row;
int x = Convert.ToInt32(txtid.Text);
for (row = 0; row < id.Length; row++)
{
if (id[row] == x)
{
txtdesc.Text = "Value found!";
return; //only add this line
}
}
txtdesc.Text = "Value not found!";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Sorting 2D Points in an array...what am I missing?

So here is the deal: I got a code from my colleague who cant figure out the mistakes he made. He wanted to sort the array first by Y, then by X (if Y=Y). Can you help?
using System;
using System.Collections;
public class Point {
public int x;
public int y;
public Point(int x, int y) {
x = x;
y = y;
}
public string ToString() {
return x + "," + y;
}
}
public class PointList {
public static void Main(string [] args) {
ArrayList AL = new ArrayList();
Random R = new Random();
for (int i = 0; i < 10; i++) {
Point p = new Point(R.Next(50), R.Next(50));
AL.Add(p);
}
PrintValues(AL);
AL.Sort();
PrintValues(AL);
}
public static void PrintValues( IEnumerable myList ) {
foreach ( Object obj in myList )
Console.WriteLine( "{0}", obj );
Console.WriteLine();
}
}
Any ideas?
You can try with:
AL.Sort(delegate(Point a, Point b) {
if (a.y < b.y ) return -1;
else if (a.y > b.y ) return 1;
else {
if ( a.x < b.x ) return -1;
else if ( a.x > b.x ) return 1;
else return 0;
}
});
You could implement ICompareable and add the following code:
public class Point : IComparable
public int CompareTo(object obj)
{
if (obj == null) return 1;
Point otherPoint = obj as Point;
if (otherPoint != null)
{
if(this.y == otherPoint.y)
{
return this.x.CompareTo(otherPoint.x);
}
return this.y.CompareTo(otherPoint.y);
}
else
throw new ArgumentException("Object is not a Point");
}

How to avoid recursive dependency properties

I have a class LineG inherited from a shape which will draw a simple line between two points.. I did that simply by adding two dependency properties StartPointProperty and EndPointProperty... Lastly I want to add another functionality which is MidPoint, so when I draw the line there will be a midPoint in the middle of the line.
When I drag the StartPoint or EndPoint the shape will be redrawn, and when I drag the MidPoint the shape will translate depending on the MidPoint change...
private static void PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
LineG lineG = (LineG)d;
if (e.Property.Name == "StartPoint")
{
}
else if (e.Property.Name == "EndPoint")
{
}
else //if MidPoint
{
Point p1 = (Point)e.OldValue;
Point p2 = (Point)e.NewValue;
double offsetX = p2.X - p1.X;
double offsetY = p2.Y - p1.Y;
lineG.StartPoint = new Point(lineG.StartPoint.X + offsetX, lineG.StartPoint.Y + offsetY);
lineG.EndPoint = new Point(lineG.EndPoint.X + offsetX, lineG.EndPoint.Y + offsetY);
lineG.MidPoint = GeneralMethods.MidPoint(lineG.StartPoint, lineG.EndPoint);
}
lineG.InvalidateMeasure();
}
protected override Geometry DefiningGeometry
{
get
{
lg.StartPoint = StartPoint;
lg.EndPoint = EndPoint;
return lg;
}
}
In such cases you can add an int counter to each operation in your class that you increment during processing. You don't do something if the counter is not 0. Example:
private int _suspendCalculation;
private static void OnPropertyChanged(..)
{
if (_suspendCalculation > 0) return;
_suspendCalculation++;
try
{
CalculateAndSetOtherProperty();
}
finally
{
_suspendCalculation--;
}
}

Resources