Supposedly,this program allows us to store data into the vector.We can keep on entering integers and then the program terminates when there is a non-integer.The program is supposed to print the largest value entered.
****however when I run this code below,I can only keep on entering the integers.And when I enter a non-integer,it gives a list of errors.
My code is(I'm not sure if Im running it correctly):
package javaapplication58;
import java.util.Scanner;
import java.util.Vector;
public class JavaApplication58 {
public static void main(String[] args) {
Vector <Integer> v=new Vector();
v=readInVectorOfIntegers();
System.out.println(largest(v));
}
public static Vector <Integer> readInVectorOfIntegers()
{Scanner in=new Scanner(System.in);
Vector<Integer>w=new Vector ();
while (in.hasNextLine())w.addElement(in.nextInt());
return w;
}
public static int largest(Vector <Integer> v)
{int largestsofar;
if(v.size()>0){largestsofar=v.elementAt(0);
for (int i=0;i<v.size();i++)
if(largestsofar<v.elementAt(i))
largestsofar=v.elementAt(i);
return largestsofar;
}
return 0;
}
}
Related
How to put the results of this if condition in a array list?
import java.util.ArrayList;
import java.util.Scanner;
public class GreatestCommonDivisor {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a value whose GCD to be computed");
int number = scan.nextInt();
for(int i=1;i<=10;i++) {
if(number%i==0) {
ArrayList<Integer> arr = new ArrayList<Integer>(number) {
}
}
}
}
}
GCD stands for Greatest Common Divisor...which finds the greatest number that divides all the numbers that you specify, but in your code I just see one number.
So from your code I get the idea that you wish to find all the numbers less than 10 (inclusive) that divide number and store those numbers in an arraylist. Assuming my assumption to be correct you can do the following.
Declare your arraylist before the loop:
ArrayList<Integer>arr = new ArrayList<Integer>()
Now run the loop:
for(int i=1;i<=10;i++){
if(number%i==0){
v.add(i);
}
}
Since Java doesn't allow to return two types in one method, I thought best way to do it is to use get methods.
Simply, I wanted computer to generate two random numbers, and if they were not the same I wanted it to print sum of them. If they were the same, I wanted it to roll once more and sum all of the rolls. Until here, it was okay, but then I wanted to see not only sum, but also the numbers that computer generated randomly before adding them up. Therefore, it had to be several return types.
But it prints 0 three times instead.
Can you help me with this? I want to learn what is wrong exactly with this code and if it can be done neater and cleaner? I know Java loves long ways..
Thank you.
class App {
public static int monopolyRoll(int side) {
double randomNumber = Math.random();
randomNumber = randomNumber * side;
randomNumber = randomNumber + 1;
int randomInt = (int) randomNumber;
return randomInt;
}
private int roll1 = monopolyRoll(6);
private int roll2 = monopolyRoll(6);
public int userRolls() {
if (roll1 != roll2) {
return roll1 + roll2;
} else {
int roll3 = monopolyRoll(6);
int roll4 = monopolyRoll(6);
return roll1 + roll2 + roll3 + roll4;
}
}
private static int first;
private static int second;
private static int third;
public App(int first, int second, int third) {
App.first = roll1;
App.second = roll2;
App.third = userRolls();
}
public static int getFirst() {
return first;
}
public static int getSecond() {
return second;
}
public static int getThird() {
return third;
}
public static void main(String[] args) {
int first = getFirst();
int second = getSecond();
int third = getThird();
System.out.println(first);
System.out.println(second);
System.out.println(third);
}
}
Math.random() works, but you never actually call it in your application. This is what your application does:
int first = getFirst();
int second = getSecond();
int third = getThird();
System.out.println(first);
System.out.println(second);
System.out.println(third);
That's it. Aside from the single return statements in those getter methods and the declared-but-never-assigned integers they return (so, zeroes), none of that other code ever executes.
I suspect this is coming from a bit of a misunderstanding on your part about the static keyword. By sprinkling around the static keyword until the code compiled, what you've done is create something that's syntactically correct but doesn't do anything :)
As a bit of a learning exercise, try moving all of the business logic out of the App class, leaving only the main() method as the application's entry point. And removing all static keywords from the new class you create. This should make the use of that class more clear.
Something like:
class Roller {
private int roll1;
private int roll2;
// other private variables
private int monopolyRoll(int side) {
// your code
}
// your other methods, also private and non-static
public Roller(int first, int second, int third) {
this.first = roll1;
this.second = roll2;
this.third = userRolls();
}
// and so on
}
The idea here is to make things instance-based (non-static) by default. Also make things private by default until explicitly needed to be accessed outside the class. Currently the only things your class needs to expose publicly are the constructor and the getters.
Then in the main() method you'll need to create an instance of your class to use it. Something like this:
Roller roller = new Roller(1, 2, 3);
int first = roller.getFirst();
int second = roller.getSecond();
int third = roller.getThird();
System.out.println(first);
System.out.println(second);
System.out.println(third);
Why does this work only up to n=90 or so?
Trying to calculate the 94th fibonacci number gives the incorrect result.
Same thing happens if I use the Integer class instead of Long.
import java.util.HashMap;
public class FDP {
private static HashMap<Long, Long> fib = new HashMap<Long, Long>();
private static Long calculateFib(Long n) {
if(fib.get(n)==null){
Long temp = calculateFib(n-1) + calculateFib(n-2);
fib.put(n, temp);
return temp;
}
else{
return fib.get(n);
}
}
}
public static void main(String[] args) {
fib.put(0L, 0L);
fib.put(1L, 1L);
System.out.println(calculateFib(90L)); //success
System.out.println(calculateFib(94L)); //garbage??
}
}
here is a list of the Fibonacci numbers:
http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibtable.html
Its an overflow.
The 94th Fibonacci number is: 19740274219868223167
Long.MAX_VALUE is:
9223372036854775807
19740274219868223167 - 9223372036854775807 > 0
You can use BigInteger to handle numbers with arbitrary length.
You reach the limitations of the type Long (64bit), use BigInteger instead
Say I have an enum
public enum E {A,B,C}
Is it possible to add another value, say D, by AspectJ?
After googling around, it seems that there used to be a way to hack the private static field $VALUES, then call the constructor(String, int) by reflection, but seems not working with 1.7 anymore.
Here are several links:
http://www.javaspecialists.eu/archive/Issue161.html (provided by #WimDeblauwe )
and this: http://www.jroller.com/VelkaVrana/entry/modify_enum_with_reflection
Actually, I recommend you to refactor the source code, maybe adding a collection of valid region IDs to each enumeration value. This should be straightforward enough for subsequent merging if you use Git and not some old-school SCM tool like SVN.
Maybe it would even make sense to use a dynamic data structure altogether instead of an enum if it is clear that in the future the list of commands is dynamic. But that should go into the upstream code base. I am sure the devs will accept a good patch or pull request if prepared cleanly.
Remember: Trying to avoid refactoring is usually a bad smell, a symptom of an illness, not a solution. I prefer solutions to symptomatic workarounds. Clean code rules and software craftsmanship attitude demand that.
Having said the above, now here is what you can do. It should work under JDK 7/8 and I found it on Jérôme Kehrli's blog (please be sure to add the bugfix mentioned in one of the comments below the article).
Enum extender utility:
package de.scrum_master.util;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import sun.reflect.ConstructorAccessor;
import sun.reflect.FieldAccessor;
import sun.reflect.ReflectionFactory;
public class DynamicEnumExtender {
private static ReflectionFactory reflectionFactory =
ReflectionFactory.getReflectionFactory();
private static void setFailsafeFieldValue(Field field, Object target, Object value)
throws NoSuchFieldException, IllegalAccessException
{
// let's make the field accessible
field.setAccessible(true);
// next we change the modifier in the Field instance to
// not be final anymore, thus tricking reflection into
// letting us modify the static final field
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
int modifiers = modifiersField.getInt(field);
// blank out the final bit in the modifiers int
modifiers &= ~Modifier.FINAL;
modifiersField.setInt(field, modifiers);
FieldAccessor fa = reflectionFactory.newFieldAccessor(field, false);
fa.set(target, value);
}
private static void blankField(Class<?> enumClass, String fieldName)
throws NoSuchFieldException, IllegalAccessException
{
for (Field field : Class.class.getDeclaredFields()) {
if (field.getName().contains(fieldName)) {
AccessibleObject.setAccessible(new Field[] { field }, true);
setFailsafeFieldValue(field, enumClass, null);
break;
}
}
}
private static void cleanEnumCache(Class<?> enumClass)
throws NoSuchFieldException, IllegalAccessException
{
blankField(enumClass, "enumConstantDirectory"); // Sun (Oracle?!?) JDK 1.5/6
blankField(enumClass, "enumConstants"); // IBM JDK
}
private static ConstructorAccessor getConstructorAccessor(Class<?> enumClass, Class<?>[] additionalParameterTypes)
throws NoSuchMethodException
{
Class<?>[] parameterTypes = new Class[additionalParameterTypes.length + 2];
parameterTypes[0] = String.class;
parameterTypes[1] = int.class;
System.arraycopy(additionalParameterTypes, 0, parameterTypes, 2, additionalParameterTypes.length);
return reflectionFactory.newConstructorAccessor(enumClass .getDeclaredConstructor(parameterTypes));
}
private static Object makeEnum(Class<?> enumClass, String value, int ordinal, Class<?>[] additionalTypes, Object[] additionalValues)
throws Exception
{
Object[] parms = new Object[additionalValues.length + 2];
parms[0] = value;
parms[1] = Integer.valueOf(ordinal);
System.arraycopy(additionalValues, 0, parms, 2, additionalValues.length);
return enumClass.cast(getConstructorAccessor(enumClass, additionalTypes).newInstance(parms));
}
/**
* Add an enum instance to the enum class given as argument
*
* #param <T> the type of the enum (implicit)
* #param enumType the class of the enum to be modified
* #param enumName the name of the new enum instance to be added to the class
*/
#SuppressWarnings("unchecked")
public static <T extends Enum<?>> void addEnum(Class<T> enumType, String enumName) {
// 0. Sanity checks
if (!Enum.class.isAssignableFrom(enumType))
throw new RuntimeException("class " + enumType + " is not an instance of Enum");
// 1. Lookup "$VALUES" holder in enum class and get previous enum
// instances
Field valuesField = null;
Field[] fields = enumType.getDeclaredFields();
for (Field field : fields) {
if (field.getName().contains("$VALUES")) {
valuesField = field;
break;
}
}
AccessibleObject.setAccessible(new Field[] { valuesField }, true);
try {
// 2. Copy it
T[] previousValues = (T[]) valuesField.get(enumType);
List<T> values = new ArrayList<T>(Arrays.asList(previousValues));
// 3. build new enum
T newValue = (T) makeEnum(
enumType, // The target enum class
enumName, // THE NEW ENUM INSTANCE TO BE DYNAMICALLY ADDED
values.size(), new Class<?>[] {}, // could be used to pass values to the enum constuctor if needed
new Object[] {} // could be used to pass values to the enum constuctor if needed
);
// 4. add new value
values.add(newValue);
// 5. Set new values field
setFailsafeFieldValue(valuesField, null, values.toArray((T[]) Array.newInstance(enumType, 0)));
// 6. Clean enum cache
cleanEnumCache(enumType);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage(), e);
}
}
}
Sample application & enum:
package de.scrum_master.app;
/** In honour of "The Secret of Monkey Island"... ;-) */
public enum Command {
OPEN, CLOSE, PUSH, PULL, WALK_TO, PICK_UP, TALK_TO, GIVE, USE, LOOK_AT, TURN_ON, TURN_OFF
}
package de.scrum_master.app;
public class Server {
public void executeCommand(Command command) {
System.out.println("Executing command " + command);
}
}
package de.scrum_master.app;
public class Client {
private Server server;
public Client(Server server) {
this.server = server;
}
public void issueCommand(String command) {
server.executeCommand(
Command.valueOf(
command.toUpperCase().replace(' ', '_')
)
);
}
public static void main(String[] args) {
Client client = new Client(new Server());
client.issueCommand("use");
client.issueCommand("walk to");
client.issueCommand("undress");
client.issueCommand("sleep");
}
}
Console output with original enum:
Executing command USE
Executing command WALK_TO
Exception in thread "main" java.lang.IllegalArgumentException: No enum constant de.scrum_master.app.Command.UNDRESS
at java.lang.Enum.valueOf(Enum.java:236)
at de.scrum_master.app.Command.valueOf(Command.java:1)
at de.scrum_master.app.Client.issueCommand(Client.java:12)
at de.scrum_master.app.Client.main(Client.java:22)
Now you can either add an aspect with an advice executed after the enum class was loaded or just call this manually in your application before extended enum values are to be used for the first time. Here I am showing how it can be done in an aspect.
Enum extender aspect:
package de.scrum_master.aspect;
import de.scrum_master.app.Command;
import de.scrum_master.util.DynamicEnumExtender;
public aspect CommandExtender {
after() : staticinitialization(Command) {
System.out.println(thisJoinPoint);
DynamicEnumExtender.addEnum(Command.class, "UNDRESS");
DynamicEnumExtender.addEnum(Command.class, "SLEEP");
DynamicEnumExtender.addEnum(Command.class, "WAKE_UP");
DynamicEnumExtender.addEnum(Command.class, "DRESS");
}
}
Console output with extended enum:
staticinitialization(de.scrum_master.app.Command.<clinit>)
Executing command USE
Executing command WALK_TO
Executing command UNDRESS
Executing command SLEEP
Et voilà! ;-)
I would like some help in casting a pointer to a C struct to a jna strucuture. I am using jna to receive a callback function from a dll, the function has a parameter that is a pointer to a C struct, when a I try to cast the pointer to a jna structure I get wrong structure values.
That is the C struct:
typedef struct
{
int x;
int y;
}Point;
Point *gpt;
typedef struct
{
int x;
int y;
Point pt1;
}Point2;
Point2 *gpt2;
That is the callback function in C with a pointer (void *params) to Point2 sctruct:
void __stdcall PointCallback(void *params, int param_size)
So, I've made this code in java to receive the callback and get the original struct:
// Point.java
package Callback.UsePointLib;
import com.sun.jna.Structure;
public class Point extends Structure
{
public static class ByValue extends Point implements Structure.ByValue {}
public int x;
public int y;
}
//Point2.java
package Callback.UsePointLib;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
public class Point2 extends Structure {
public int x;
public int y;
Point pt1;
public Point2(Pointer p){
super(p);
}
}
Callback implementation:
//UsePointLib.java
public interface IFuncCallback extends StdCallCallback{
void callback(Pointer Params, int ParamSize);
}
public class FuncCallback implements IFuncCallback{
#Override
public void callback(Pointer Params, int ParamSize) {
Point2 pt2; // = new Point2();
pt2 = new Point2(Params);
System.out.println("pt2.x = "+pt2.x); **<- I get zero here instead of four**
System.out.println("pt2.y = "+pt2.y); **<- I get zero here instead of five**
System.out.println("pt2.pt1.x = "+pt2.pt1.x);**<- pt1 is null, throwing exception**
System.out.println("pt2.pt1.y = "+pt2.pt1.y);**<- same as pt1.**
}
}
I've made a C program to access the dll and receive the callback and it works ok, it receives the correct values. So, the problem is my java code. I've tried many alternatives with no success.
Please, I'd appreciate any help on that.
Thanks,
Fernando.
EDIT
I've modified the code and it works partially.
//UsePointLib.java
public interface IFuncCallback extends StdCallCallback{
void callback(Pointer Params, int ParamSize);
}
public class FuncCallback implements IFuncCallback{
#Override
public void callback(Pointer Params, int ParamSize) {
Point2 pt2; // = new Point2();
pt2 = new Point2(Params);
*pt2.read();* **<--Modification**
System.out.println("pt2.x = "+pt2.x); **<- I get the correct value (four)**
System.out.println("pt2.y = "+pt2.y); **<- I get the correct value (five)**
System.out.println("pt2.pt1.x = "+pt2.pt1.x);**<- pt1 is still null, throwing exception**
System.out.println("pt2.pt1.y = "+pt2.pt1.y);**<- same as pt1.**
}
}
The jna docs say that the constructor Structure(Pointer) allocates a structure onto a preallocated memory. It wont automatically assign values for you.I don't think thats what you want.
Change the constructors to
public Point2(){
super();
}
public Point2(Point1 p){
super();
pt1.x = p.x;
pt1.y = p.y;
this.x = something;
this.y = something;
}
Within the context of a callback, JNA will automatically call Structure.read on entry and Structure.write on exit for any parameters of type Structure.
If you declare your callback method signature to use a Structure type of the appropriate subclass ("Point2" in your example), the copying to/from native memory should be automatic.