Can't make my own custom exception. Please help me - java

When I try and make a catch statement using InvalidTestScore exception java won't allow me. However when I use IllegalArgumentException, java does allow me to make it.
// George Beazer
public class TestScores2 {
public TestScores2(int[] arg) {
System.out.println(average(arg));
}
public int average(int[]arg)
{
int temp=0;
for (int i = 0; i < arg.length; i++) {
if(arg[i]<0 || arg[i]>100)
{
IllegalArgumentException e = new IllegalArgumentException();
throw e;
}
else
{
temp+=arg[i];
}
}
return temp/arg.length;
}
public static void main(String[] args) {
int []ar={4,78,33,89};
TestScores2 ts=new TestScores2(ar);
}
}
Runs fine
However if i run
public class TestScores2 {
public TestScores2(int[] arg) {
System.out.println(average(arg));
}
public int average(int[]arg)
{
int temp=0;
for (int i = 0; i < arg.length; i++) {
if(arg[i]<0 || arg[i]>100)
{
InvalidTestScoreException e = new InvalidTestScore();
throw e;
}
else
{
temp+=arg[i];
}
}
return temp/arg.length;
}
public static void main(String[] args) {
int []ar={4,78,33,89};
TestScores2 ts=new TestScores2(ar);
}
}
I get can't find symbol. What does it take to make your own custom exception .

InvalidTestScoreException e = new InvalidTestScore();
??? shouldn't that be:
InvalidTestScoreException e = new InvalidTestScoreException();

As #Falmarri pointed out, you need to declare an InvalidTestScoreException class
Here is what a revised version might look like:
public class TestScores2 {
public class InvalidTestScoreException extends RuntimeException {
//Constructors go here
}
public TestScores2(int[] arg) {
System.out.println(average(arg));
}
public int average(int[]arg)
{
int temp=0;
for (int i = 0; i < arg.length; i++) {
if(arg[i]<0 || arg[i]>100)
{
InvalidTestScoreException e = new InvalidTestScoreException();
throw e;
}
else
{
temp+=arg[i];
}
}
return temp/arg.length;
}
public static void main(String[] args) {
int []ar={4,78,33,89};
TestScores2 ts=new TestScores2(ar);
}
}

Related

How to create generic code for objects of different types

I have an entity that has as children several lists of objects that, although they have different classes, all have the order attribute, in several parts I end up with repeated code, for example in one part I need to order the lists by that attribute and I cannot simplify because they are of different type.
The relevant part of the entity is this:
contenido={
"educaciones":[
{
...
"orden":0
},{
...
"orden":1
}
],
"experiencias":[
{
...
"orden":0
},{
...
"orden":1
}
]
},
...
The code I would like to simplify:
if(tipo.equals("experiencias")){
List<Experiencia> iterable=contenido.getExperiencias();
for(int i = 0; i < iterable.size(); i++){
iterable.get(i).setOrden( orden.get(i) ); //orden = [0,3,5,...]
}
iterable.sort((it1,it2)-> it1.getOrden().compareTo(it2.getOrden()));
}else if(tipo.equals("educaciones")){
List<Educacion> iterable=contenido.getEducaciones();
for(int i = 0; i < iterable.size(); i++){
iterable.get(i).setOrden( orden.get(i) );
}
iterable.sort((it1,it2)-> it1.getOrden().compareTo(it2.getOrden()));
}else if...
Is there a way to create a code that is more generic and supports different objects?
Create an interface for the methods that are common between all you classes:
interface HasOrden {
int getOrden();
void setOrden(int i);
}
Each of your classes needs to implement HasOrden.
Then you can declare sortOrden function:
import java.util.ArrayList;
import java.util.List;
interface HasOrden {
int getOrden();
void setOrden(int i);
}
class Experiencia implements HasOrden {
private final String name;
int orden;
public Experiencia(String name) {
this.name = name;
}
#Override
public int getOrden() {
return orden;
}
#Override
public void setOrden(int i) {
orden = i;
}
public String toString() {
return name;
}
}
public class Eg {
static void sortOrden(List<? extends HasOrden> l, List<Integer> order) {
if (l.size() != order.size()) {
throw new RuntimeException("length mismatch");
}
for (int i = 0; i < l.size(); i++) {
l.get(i).setOrden(order.get(i));
}
l.sort((it1,it2)-> Integer.compare(it1.getOrden(), it2.getOrden()));
}
public static void main(String[] args) {
List<Experiencia> items = new ArrayList<>(List.of(new Experiencia("a"), new Experiencia("b")));
List<Integer> order = List.of(2,1);
sortOrden(items, order);
System.out.println(items);
}
}
You can call sortOrden on any list of HasOrden instances.
you can try to create a List<?> - list with a dynamic type outside of your if else block and move your duplicated code outside too and at the end of the if else block. In addition, you have to create a common class or some interface for your classes, which holds all the common field you needed
public class Main {
public static class Something {
private Integer sth;
public Integer getSth() {
return sth;
}
public void setSth(Integer sth) {
this.sth = sth;
}
}
public static class ThisClass extends Something {
private Integer num;
public ThisClass(Integer num) {
this.num = num;
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
}
public static class ThatClass extends Something {
private String str;
public ThatClass(String str) {
this.str = str;
}
public String getStr() {
return str;
}
public void setNum(String str) {
this.str = str;
}
}
public static List<? extends Something> sortList(Class<?> itemClass, List<? extends Something> list)
throws Exception {
for(int i = 0; i < list.size(); i++){
list.get(i).setSth(i);
}
list.sort((it1,it2)-> it1.getSth().compareTo(it2.getSth()));
return list;
}
public static void main(String[] args) {
System.out.println("Hello World");
List<? extends Something> someList = new ArrayList<>();
boolean check = true;
if(check) {
someList = Arrays.asList(new ThisClass(1),new ThisClass(1),new ThisClass(1),new ThisClass(1));
} else {
someList = Arrays.asList(new ThatClass("a"), new ThatClass("a"),new ThatClass("a"),new ThatClass("a"));
}
try {
someList = sortList(ThisClass.class, someList);
for(int i = 0; i < someList.size(); i++){
System.out.println(someList.get(i).getSth());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

I'm trying to find the sum of the objects that are defined as numbers

I'm doing an exercise, in which I have to create the method add, however due to p and v being defined as objects, I'm having a hard time figuring out how I can define this method in the syntax I've been given in the exercise (I'm only allowed to change the methods).
I would like to add the two inputs 5 and 17 so that it returns 22. I've done a lot of research into other questions where I've seen them write it as Positiv(p + v) but this doesn't quite work.
public class Positiv {
public static void main(String[] args) {
try {
Positiv p = new Positiv(5);
Positiv v = new Positiv(17);
p.add(v);
System.out.println(p.get());
} catch (Exception e) {
e.printStackTrace();
}
}
private int n;
public Positiv(int n) {
if (n < 0) { throw new IllegalArgumentException("exception");
}
this.n = n;
}
public static Positiv add(Positiv v)
{
return new Positiv(n + v);
}
public int get() {
return n;
}
}
In your add method:
public static Positiv add(Positiv v)
{
return new Positiv(n + v);
}
You return a whole new Positiv object. However (correct me if I'm wrong) it looks as if you just want to add the two n fields. You can do this by adding this.get to v.get:
public void add(Positiv v)
{
this.n += v.get();
}
Which will return 22
Tutorial for this
public class HelloWorld{
public static void main(String []args){
Numbers a = new Numbers(5);
Numbers b = new Numbers(10);
int num1 = a.getN();
int num2 = b.getN();
System.out.println(addTwoNumbers(num1, num2));
}
public static int addTwoNumbers(int a, int b) {
return a + b;
}
}
class Numbers {
private int n;
public Numbers(int n) {
this.n = n;
}
public int getN() {
return n;
}
}

Words Counter using Dictionary

For homework I have to implement a Words Counter using a Dictionary.I have an inner class named Couple
protected class Couple
{ public Coppia(String key, Integer value)
{ setKey(key);
setValue(value);
}
public String toString()
{ return String.format("%-15s", key) + " | " + value; }
public String getKey()
{ return key; }
public Integer getValue()
{ return value; }
public void setKey(String key)
{ this.key = key; }
public void setValue(Integer value)
{ this.value = value; }
//campi di esemplare
private String key;
private Integer value;
}
}
I created the class WordsCounter with put,find,remove methods
class WordsCounter
{ private Couple [] a;
private int inputSize;
public WordCounter()
{ a=new Couple [10];
inputSize=0;
}
public boolean isEmpty()
{return inputSize==0;}
public int size()
{return inputSize;}
public String toString()
{String s="";
for(int i=0;i<inputSize;i++)
{s=s+a[i].toString()+"\n";
}
return s;
}
public void put(Comparable key, Comparable value)
{if(inputSize==a.length) //resize
{ Coppia [] newA=new Coppia [2*inputSize];
for(int i=0;i<inputSize;i++)
{ newA[i]=a[i];
}
a=newA;
}
for(int i=0;i<inputSize;i++) // if the word is already in, i replace the old value with the new one
{ if(a[i].getKey().equals((String)key))
{ a[i].setValue((Integer)value);
return;
}
}
//otherwise i add the word in the array
a[inputSize++]=new Couple((String)key,(Integer)value);
mergeSort(a,inputSize);
}
public void remove(Comparable key)
{ int pos=binarySearch(a,0,inputSize-1,(String)key);
if(pos<0)
{ throw new MapItemNotFoundException();
}
else
{ a[pos]=a[inputSize-1];
inputSize--;
mergeSort(a,inputSize);
}
}
public int binarySearch(Couple [] a,int start,int end,String k)
{ if(start>end)
return -1;
int mid=(start+end)/2;
if(a[mid].equals(k))
{ return mid;}
else if(k.compareTo(a[mid].getKey())<0)
{ return binarySearch(a,start,mid-1,k);
}
else if( k.compareTo(a[mid].getKey())>0)
{ return binarySearch(a,mid+1,end,k);
}
else return -1;
}
public Comparable find(Comparable key)
{ int pos=binarySearch(a,0,inputSize-1,(String)key);
if(pos<0) // the word isn't inside the array ,so i throw an exception
{ throw new MapItemNotFoundException();
}
else
{ return a[pos].getValue();
}
}
public void mergeSort(Couple [] a,int input)
{ if(input<2)
return;
int mid=input/2;
Coppia [] first=new Coppia [mid];
Coppia [] second=new Coppia [input-mid];
for(int i=0;i<first.length;i++)
{ first[i]=a[i];
}
for(int i=0;i<second.length;i++)
{ second[i]=a[i+first.length];
}
mergeSort(first,mid);
mergeSort(second,input-mid);
merges(a,first,second);
}
public void merges(Couple [] a,Couple [] b,Couple [] c)
{ int i=0;
int k=0;
int j=0;
while(i<b.length&&j<c.length)
{ if(b[k].getKey().compareTo(c[j].getKey())<0)
{ a[i++]=b[k++];
}
else
{ a[i++]=c[j++];
}
}
while(i<b.length)
{ a[i++]=b[k++];
}
while(j<c.length)
{ a[i++]=c[j++];
}
}
The main class is
public class ContatoreParoleTester
{
public static void main(String[] args)
{
FileReader read=null;
try{ read=new FileReader(in.nextLine());
}
catch(IOException e)
{
}
Scanner c=new Scanner(read);
WordCounter parole=new WordCounter();
while(c.hasNextLine())
{ Scanner token=new Scanner(c.nextLine());
token.useDelimiter("[^A-Za-z0-9]+");
while(token.hasNext())
{
String tok=token.next();
tok=tok.toLowerCase();
try{
Comparable n= parole.find(tok); // i find the word ,if it isn't inside (the method throw an exception message) i catch the exception and i insert the word in the array with value=1; else i insert it in the array with the new value
parole.put(tok,(Integer)n+1);
}
catch(MapItemNotFoundException e)
{ parole.put(tok,1);}
}
}
System.out.println(parole);
}
}
When I print the counter the variable "value" doesn't seem to update, in fact i got something like this :
word1::1
word2::1
word3::1
etc.
I think that the update method doesn't work well, but I don't know why!:(
Could anyone help me please?
Thanks
Your binary search doesn't work... It only ever returns -1. I know this because it if ever did, this line in main: parole.put(tok,(Integer)n+1); would create a ClassCastException

cannot cast java.util.concurrent.ForkJoinWorkerThread into java.lang.Thread- Complex structure

I understand the concept of fork/join, but almost all resources over the internet use, Fibonacci as an example, but my scenario is more complex. I sketched the program, and I have an exception as commented in the below code..
Class Test
{
public static void main(String[] args)
{
ForkJoinPool p= new ForkJoinPool(5);
p.invoke(new Train());
}
}
Class Train extends RecursiveAction
{
public Train(int d, int n)
{
//some intialization
}
public Train()
{
t= new Train[5];
new Vec().run_Vec(t);
}
#Override
protected void compute() {
for(int i= 1; i< 8; i++)
{
// x, and y are predefined
temp[x][y] = some calculation;
}
}
}
class Vec
{
public void run_Vec(Train[] t) {
for (int i = 0; i < 5; i++) {
t[i] = new Train(i*4, i/2);
t[i].fork(); // error java.lang.Thread cannot be cast to java.util.concurrent.ForkJoinWorkerThread
}
for (int i = 0; i < 5; i++) {
t[i].join();
}
}
}
}
I think your problem is due to calling fork() from the main thread. When you call p.invoke(new Train()), your default train constructor actually calls the run_vec() and tries to fork(). Upon reading the javadocs, there are examples that fork() is called within compute(). You need to be calling fork from a thread started by p.invoke().
Based on this Java article I made the following code snippet: http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/RecursiveAction.html
You should only call fork (spawn) within a "running" Thread. This means you must pass on the Train array within the compute method:
package ...;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
class ConcurrentTest {
public static void main(String[] args) {
ForkJoinPool p= new ForkJoinPool(5);
p.invoke(new Train());
}
public static class Train extends RecursiveAction {
private Train[] t = null;
public Train(int d, int n) {
//some code
}
public Train() {
t= new Train[5];
}
#Override
protected void compute() {
if(t != null) {
new Vec().run_Vec(t);
for(int i= 1; i< 8; i++) {
System.out.println("Test.Train.compute(): " + i);
}
}
}
}
public static class Vec
{
public void run_Vec(Train[] t) {
for (int i = 0; i < 5; i++) {
t[i] = new Train(i*4, i/2);
System.out.println("Clazz: " + t[i].getClass());
t[i].fork(); // error java.lang.Thread cannot be cast to java.util.concurrent.ForkJoinWorkerThread
}
for (int i = 0; i < 5; i++) {
t[i].join();
}
}
}
}

Stuck in using 2D arrays?

I am not good with arrays.In the below code there are 2 methods which takes the data from two 2D Arrays.The first method COMBINATION is working correctly.But the second Method doesn't.
Am I doing anything wrong in the array Declaration ???
The Below Methods takes the KeyEvent from the Array & perform the Keypress & keyRelease according to the KeyEvents in the array.
For Example :
Combination.UNICODE_COPY, KeyEvent.VK_CONTROL, KeyEvent.VK_C
The above line presses CTRL+C. It performs the Copy Function.
I think that in the Second Method i am passing 3 KeyEvents.Is that a Problem ???
private static final int[][] COMBINATION = {
{
Combination.UNICODE_CUT, KeyEvent.VK_CONTROL, KeyEvent.VK_X
}, {
Combination.UNICODE_COPY, KeyEvent.VK_CONTROL, KeyEvent.VK_C
}, {
Combination.UNICODE_PASTE, KeyEvent.VK_CONTROL, KeyEvent.VK_V
}
};
private static final int[][] COMBINATIONS = {
{
Combinations.UNICODE_TASK, KeyEvent.VK_CONTROL, KeyEvent.VK_ALT, KeyEvent.VK_DELETE
}
};
private void keyboardCombination(Combination action)
{
boolean exception = false;
for (int i = 0; i < COMBINATION.length; i++)
{
if (action.unicode == COMBINATION[i][0])
{
exception = true;
this.application.getRobot().keyPress(COMBINATION[i][1]);
this.application.getRobot().keyPress(COMBINATION[i][2]);
// this.application.getRobot().keyPress(COMBINATION[i][3]);
this.application.getRobot().keyRelease(COMBINATION[i][1]);
this.application.getRobot().keyRelease(COMBINATION[i][2]);
// this.application.getRobot().keyRelease(COMBINATION[i][3]);
break;
}
}
if (!exception)
{
pressUnicode(this.application.getRobot(), action.unicode);
}
}
private void keyboardCombinations(Combinations action)
{
boolean exception = false;
for (int i = 0; i < COMBINATIONS.length; i++)
{
if (action.unicode == COMBINATIONS[i][0])
{
exception = true;
this.application.getRobot().keyPress(COMBINATIONS[i][1]);
this.application.getRobot().keyPress(COMBINATIONS[i][2]);
this.application.getRobot().keyPress(COMBINATIONS[i][3]);
this.application.getRobot().keyRelease(COMBINATIONS[i][1]);
this.application.getRobot().keyRelease(COMBINATIONS[i][2]);
this.application.getRobot().keyRelease(COMBINATIONS[i][3]);
break;
}
}
if (!exception)
{
pressUnicode(this.application.getRobot(), action.unicode);
}
}
COMBINATIONS
public class Combinations extends ControllerDroidAction
{
public static final int UNICODE_TASK = 40;
public int unicode;
public Combinations(int unicode)
{
this.unicode = unicode;
}
public static Combinations parse(DataInputStream dis) throws IOException
{
int unicode = dis.readInt();
return new Combinations(unicode);
}
public void toDataOutputStream(DataOutputStream dos) throws IOException
{
dos.writeByte(COMBINATIONS);
dos.writeInt(this.unicode);
}
}

Categories