How To Find Maximum Of Two Enum Values

Oct 6, 2014

I have a set of enum values (let's call then ONE, TWO, THREE.....). I want to find the larger of two of them. But max(ONE,THREE) gives a compile error as MAX isn't defined for type-safe enums. Fair enough.
 
I also agree that one shouldn't be able to use arithmetic functions on enums.
 
But as Enum implements Comparable, one can write a function which implements max and min, rather inefficiently I assume.
 
Is there a better way of getting the max/min of an enum? And if not, can the Java team be persuaded to implement it?

View Replies


ADVERTISEMENT

Method Values For Enum Types

Nov 21, 2014

What class does method Planet.values() in the code below belong to? I thought it belongs to java.lang.Enum but when I could not see it in Java API 7.

package enumeration;
public class EnumTest {
public static void main(String[] args) {
//Planet myPlanet = Planet.EARTH;
// Check arguments supplied
if (args.length != 1) {
System.err.println("Usage: java EnumTest <earth_weight>");
System.exit(-1);

[code]....

View Replies View Related

Enum Properties / Values / Fields

Jul 11, 2014

So I have an Enum file with 119 constants and each constant of that type has 20 fields that come with it. All the fields are the same type and named the same (e.g. there are 119 of Object obj, one for each constant), and I want to run the same methods over them. Since the Objects of the same type are named the same for each constant, I just have them named explicitly in get-er methods.

This worked fine when I just put all 20 fields through the constructor and set them as fields under all the constants. But I realized that if I wanted to make an instance of this Enum class, I'd have to enter in all 20 fields when they are all a set of Objects with unique values. So I then put them as fields under their own respective constant to make it easier to create instances of this enum. But now my methods don't work.

A) I don't really understand why they don't work anymore?
B) Is there a way to fix it without putting all the methods under each constant?

Example:

public enum MyEnum {
AAA {
private MyObject obj = new MyObject (3.0);
},
BBB {
private MyObject obj = new MyObject (1.5);
},
CCC {
private MyObject obj = new MyObject (6.5);
},
DDD {
private MyObject obj = new MyObject (3.5);
};

public double getObjVal() {
return obj.value(); // it can't find this obj should I move it up to where the constants are declared?
}
}

View Replies View Related

Find Maximum Between Three Numbers Using Ternary Operator?

Aug 23, 2014

Write a program to find maximum between three numbers using ternary operator.

View Replies View Related

How To Find Maximum Element Of Each Column In 2D Array

Oct 26, 2014

import java.io.IOException;
public class Largestcolumn
{
public static void main ( String[] args ) throws IOException
{
int largest = 0;
int newnumber = 0;
int[][] data = { {3, 2, 5},

[Code] ....

When I run this code, I get this following output: The largest element in column 0 is: 9.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at largestcolumn.Largestcolumn.main(Largestcolumn.java:27)
Java Result: 1

It outputs the first column's maximum element but then throws an out of bounds error. I'm new to Java and I can't figure out how to fix my code so that it will work for this multidimensional array and output the maximum elements in all of the columns.

View Replies View Related

Strings With Digits Not Permitted Enum Values?

May 28, 2013

If you have an enumeration type with instances whose publicly accepted names are numbers, e.g. a Chevy 396 and I'm sorting this car according to makes and models that I've already laid out within enum types for each. Here the make instance is "Chevy" and the model instance is just "396".

I know I could make this "396" into "Ch396" and this would work programmatically. But this might confuse some people who just expect to see "396".

In short, why are enum instances not allowed to be of String type rather than just standard Java identifiers ?

View Replies View Related

Sorting Arraylist Of Calendar Objects To Find Maximum

Oct 14, 2014

I have a requirement to find the greatest/maximum of the given list of Calendar objects in Java.

i.e., 2013/01/26
2014/03/03
2012/02/27
2014/01/15

So the above list of calendar objects are in Arraylist. I need to get the max/greatest among these. Eventually, the answer should be 2014/03/03

View Replies View Related

Array Is A Set Of Numbers In Triangle - Find Maximum Path

Aug 12, 2014

If you aren't familiar with the euler problem 67, you are given an array that is a set of numbers in a triangle. Like this

3
7 4
2 4 6
8 5 9 3

and you have to find the maximum path, which for this one is

(3)
(7) 4
2 (4) 6
8 5 (9) 3

I have solved this problem iteratively with the code below

depth = depth-2;
while (depth >=0) {
for (int j = 0; j <= depth; j++) {
values[depth][j] += Math.max(values[depth+1][j], values[depth+1][j+1]);
}
depth -= 1;
}

depth is a variable for the row in the triangle. My problem is that i need the solution to be recursive and i am having trouble doing this. So far i have

public static int findMax(int[][] array,int depth) {
if (depth==0)
return array[0][0];
else if
}

View Replies View Related

Print Maximum And Minimum Values Of Integers From User Input

Apr 27, 2015

So I'm learning java from a website and I was tasked with creating a simple program which allows the user to enter a series of integers, then finally when they decide to input a non-integer the program will print the maximum and minimum values of the integers they entered. So for example if they entered 5, 4, 3 and 2 then enter a non-integer the program would output 5 (maximum value), then 2 on a new line (minimum value).

Here is my code:

import java.util.Scanner;
public class MaxMinPrinter {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;

[Code] ....

And this is what the output looks like:

Actual output
-------------------------------------------
Enter an integer: 5
- 10
-
- Enter an integer: -4
- 8
- -6
-
- Enter an integer: 11
- -1
-
- Enter an integer: q
- -1
- -6

When it's supposed to look like this:

Expected output
-------------------------------------------
Enter an integer: 5
Enter an integer: 10
Enter an integer: -4
Enter an integer: 8
Enter an integer: -6
Enter an integer: 11
Enter an integer: -1
Enter an integer: q
11
-6

View Replies View Related

Find Min And Max Values And Calculate Mean For Data Set

May 2, 2014

The first is MyArray Class (You can either use an array or an arrayList)Create a class called LastNameFirstNameMyArray according to the UML diagram. This class will allow a user to enter 5 integer values into an array(or object of ArrayList<Integer>). It contains methods to find min and max values and calculate the mean for the data set.

LastNameFirstNameMyArray - data[ ] : int (or data : ArrayList<Integer> )
- min : int
- max: int
- mean : double + LastNameFirstNameMyArray()
+ findMin() : void
+ findMax() : void
+ calculateMean(): void
+ toString() : String

Attributes:
data[]the array which will contain the values or data<Integer>the arraylist which will contain the values
minthe minimum value among the values in the arraylist
maxthe maximum value among the values in the arraylist
mean the arithmetic average of the values

Methods:
You need to implement the constructor LastNameFirstNameMyArray(), which populates 5 values. In addition, the constructor should call findMin() and findMax(), and also calculateMean().

Methods:
LastNameFirstNameMyArray()the constructor. It will allocate memory for the array (or arraylist) of size 5. Use a for loop to repeatedly display a prompt for the user which should indicate that user should enter value 1, value 2, etc. Note: The computer starts counting with 0, but people start counting with 1, and your prompt should account for this. For example, when the user enters value 1, it will be stored in indexed variable 0. The constructor should populate 5 integer values, call findMin() and findMax(), and also calculateMean().

findMin()this is a method that uses a for loop to access each data value in the array (or arraylist) and finds the minimum value. The minimum value is stored into min.

findMax()this is a method that uses a for loop to access each data value in the array (or arraylist) and finds the maximum value. The maximum value is stored into max.

calculateMean()this is a method that uses a for loop to access each data value in array (or arraylist) and add it to a running total. The total divided by the number of values (use the length of the array), and the result is stored into mean.
toString()returns a String containing data, min, max, and the mean.

Task #2 TestMyArray

1. Create a LastNameFirstNameTestMyArray class. This class only contains the main method. The main method should declare and instantiate a LastNameFirstNameMyArray object.
2. Compile, debug, and run the program. Then, it should print out the contents, the min, max, and mean of the data.

and the second is A theater seating chart is implemented as two-dimensional array of ticket prices, like this:

10 10 10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10 10 10
10 10 20 20 20 20 20 20 10 10
10 10 20 20 20 20 20 20 10 10
10 10 20 20 20 20 20 20 10 10
20 20 30 30 40 40 30 30 20 20
20 30 30 40 50 50 40 30 30 20
30 40 50 50 50 50 50 50 40 30

Write a program that prompts the users to pick either a seat or price. Mark sold seats by changing the price the 0. When a user specifies a seat, make sure it is available. When a user specifies a price, find any seat with that price.

Note: Assume that if the user enters 1 for the row and 1 for the seat, the yellow marked sit will be sold.

View Replies View Related

Code That Find Median Value In List Of Values

Mar 19, 2014

a simple Java program for finding the median value in a list of values with the following requirements:

- Create an array with an even number of values in it (an odd number of values is little bit trickier, so if you want a challenge, do it for either an even or odd number of values)

- Find the value with an equal number of values greater than the value as there are values less than the value

- Your solution must not require a sorted list of values - Output the median value

This assignment is intended to get you to demonstrate basic knowledge of arrays, and to create methods with both input and output.

View Replies View Related

JSP :: EL Expressions - Find A Place Where Values For Status Is Being Set / Assigned To

Feb 4, 2014

I have a web application project built in Spring MVC 2.5. There are some EL expressions which are used in JSP as below:

${status.value}
${status.expression}
${status.errorMessages}

But, I coudln't find any place in Java/JSP where the value for status is being set. What could be the possible place where the values for status is being set.

As the code is client specific, so, I couldn't paste the specific code over here but I have searched in whole workspace i couldn't find a single place where values for status is being set/assigned to.

View Replies View Related

How To Get Enum Name By Value

Jan 12, 2015

I want to have a priceObject which is constructed by a price the enumtype and the name.

public class Testing {
public static void main(String[] args) {
PreisObject p1 = new PreisObject(1,Price.liquid,"TEST1");
System.out.println(p1);
PreisObject p2 = new PreisObject(2,Price('f'),"Test2");

[Code] .....

As you can see with PreisObject2 I want to check the enum by the value and not by the name as in PreisObject1.

Or do I have to use a if-else or switch statement to do something like this?

View Replies View Related

Enum Type And Array List

Feb 10, 2015

Here I have an enum class

public enum Money{

ONE_PENNY(1),
TWO_PENCE(2),
FIVE_PENCE(5),
TEN_PENCE(10),
TWENTY_PENCE(20),
FIFTY_PENCE(50),
ONE_POUND(100),
TWO_POUNDS(200);

private int coin;
Money(int c) {
coin = c;
}
int showCoin() {
return coin;
}

and for a test class, I need an array list with a couple of coins in it (i.e. ONE_POUND, TWO_POUNDS) and a loop that adds together the values of the coins in the list and prints the result. How can I do this?

View Replies View Related

JSF :: Enum Type In Parametrized Class

Dec 4, 2014

I'm developing a JSF application.I have some enums, for example

public enum Gender {
MALE("Male"),
FEMALE("Female");
private final String label

[code]....

I want to put the enum value in <h:selectOneMenu>. I use a bean:

@Named(value = "genderBean")
@RequestScoped
public class GenderBean {
/**
* Creates a new instance of GenderBean
*/
public GenderBean() {

[code]...

How can i call the method .values() of enum for a generic enum T, like in the striked code?

View Replies View Related

Iterate Enum Type Without Instance

Sep 16, 2014

Is there anyway to iterate an enum type without an instance. As some context, consider the following code:

Java Code: public interface GenericChecker
{
public bool isValid(String str);
} mh_sh_highlight_all('java'); Java Code: public class EnumChecker<T extends Enum<T> > extends GenericChecker
{
private Class<T> enumType; //No instance

[code]....

toString method of the enum types has been overridden so that it returns the name assigned to the enum rather than the enum name itself. For example an enum might be SOME_ENUM("Assigned name"), therefore toString returns "Assigned name" rather than "SOME_ENUM". The idea is that a field from a table can be handed to the isValid(String) function on the GenericChecker base, and the derived class will then check to see if the field matches valid data as far as it is concerned.Thus, I can create a whole bunch of checkers easliy:

Java Code: GenericChecker checker1 = EnumChecker<EnumType1>();
GenericChecker checker2 = EnumChecker<EnumType2>();
GenericChecker checker3 = EnumChecker<EnumType3>();
GenericChecker checker4 = SomeOtherChecker(); mh_sh_highlight_all('java');

The problem is, if I use the EnumChecker then the expression "enumType.getEnumConstants()" in the isValid function blows up because enumType is null.

View Replies View Related

Why Enum Types Not Being Recognized By Methods

Mar 17, 2014

Attempting to write a custom comparator for sorting songs, but I keep getting errors saying that the types cannot be resolved.

Java Code:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.*;
public class SongCollection {

[Code] .....

View Replies View Related

Creating Enum With String And Method

Nov 9, 2014

How would I go about and make an enum, that has Strings and Methods?I want to make a class called GraphicalEffects, this class and be instanstiated and it has a method to apply graphicalEffects AS methods or some type of references to methods in an ArrayList.

View Replies View Related

Maximum Size Of Collections

Apr 23, 2014

I am just not sure of some theory in collections, ArrayList and LinkedList maximum capacity depends on the memory allocated to the JVM. But according to few people those list has a maximum capacity of Integer.MAX_VALUE.

According to my experiment, those list has a maximum capacity of Integer.MAX_VALUE since the get method of List accept a parameter of int primitive type (index of element), therefore we can conclude that the maximum capacity of List is equal to Integer.MAX_VALUE.

But what about the Map? get() method of map accepts object(the key of the map). So does it mean that the maximum capacity of Map depends on the memory allocated to our JVM? Or its maximum size is Integer.MAX_VALUE also just like Lists and Arrays? Is there a way to prove it? Is Map designed to hold infinite number of data (disregarding the heap memory space exception)?

And also about Stack, Deque? is it also the same as Map (in terms of maximum capacity)?

View Replies View Related

Calculate Minimum And The Maximum

Nov 21, 2014

i need to calculate the minimum and the maximum, actually it seems to be easy but, the minimum should be the smallest number but 0..this is my code

Java Code:

Scanner s = new Scanner (System.in);
int max = 0 ;
int min = 0 ;
System.out.println(" Please enter 3-5 numbers");
int a = s.nextInt();
int b = s.nextInt();
int c = s.nextInt();
int d = s.nextInt();
int e = s.nextInt();

[code]....

View Replies View Related

Minimum And Maximum Loop

Feb 20, 2015

I am doing a homework assignment for a class I'm taking and writing a java program that finds the smallest and largest number in an array entered by the user. For some reason no matter what I enter as the smallest number it returns 0 as the smallest. I'm not sure what I have done wrong. Here is my code:

import javax.swing.JOptionPane;
public class MinimumAndMaximumJamesBulow
{
public static void main(String[] args)
{
int minimum = 0;
int maximum = 0;
 
[Code] ....

View Replies View Related

Getting Error - Class Interface Or Enum Expected

Aug 7, 2014

import java.io.*;
class addition {
public static void main(String[] args) {
int num1,num2,sum;
try {
DataInputStream x=new DatainputStream(system.in);

[Code] ,,,,,

View Replies View Related

Constructor Needs To Import Enum Blackjack Game

Jun 21, 2014

I am just not importing the Enum value properly. The error I am getting with the DECK class is

import java.util.ArrayList;
public class Deck {
ArrayList<Card> deckList = new ArrayList<Card>();
String[] value = {"Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King","Ace"};
String[] suit = {"Hearts","Clubs","Spades","Diamonds"};

[Code] ....

1 error found:
File: C:UsersFouadDesktopSchooCSC 162 SUMMER 14lackjack1Deck.java [line: 19]
Error: constructor Card in class Card cannot be applied to given types;
required: CardEnum.Rank,CardEnum.Suit
found: java.lang.String,java.lang.String
reason: actual argument java.lang.String cannot be converted to CardEnum.Rank by method invocation conversion

I have also tried this with the Deck Class

import java.util.ArrayList;
public class Deck {
ArrayList<Card> deckList = new ArrayList<Card>();
String[] value = {"Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King","Ace"};
String[] suit = {"Hearts","Clubs","Spades","Diamonds"};

[Code] ....

Resulting ERROR message

2 errors found:
File: C:UsersFouadDesktopSchooCSC 162 SUMMER 14lackjack1Deck.java [line: 19]
Error: cannot find symbol
symbol: variable value
location: class CardEnum
File: C:UsersFouadDesktopSchooCSC 162 SUMMER 14lackjack1Deck.java [line: 19]
Error: cannot find symbol
symbol: variable suit
location: class CardEnum

THE FULL CODE!(BELOW)

public class BlackJack{
BlackJack() {
Deck deck = new Deck();
deck.createDeck();
System.out.println(deck.deckList);
}
public static void main(String[] args) {
new BlackJack();

[Code] ....

View Replies View Related

Dynamic Enum - How To Make DIME(10) False

Apr 20, 2015

I wrote a simple enum and a test class. The enum represents us coins and my test class uses the enum to calculate the change with the least number of coins. For example, I pass in 95 cents, I get back 3 quarters, 2 dimes. It all works just fine, easy to implement and I see why I should use an enum. Then I thought, what if the person is out of dimes. How could I tell the enum to skip dimes in it's switch statements? How would I make DIME(10) false?

View Replies View Related

JDBC :: Maximum Number Of Connections

Feb 29, 2012

I am using a static initialization block to register the driver and a static synchronized method to get a connection. The problem is I need to run 15 threads but always only two threads get the connection. I want to know if there is a default maximum number of concurrent connections a DriverManager can provide or is it my threading logic that may be faulty.

CODE:

static {
     try {
Class jdbcDriverClass = Class.forName( JDBC_DRIVER );
driver = (Driver) jdbcDriverClass.newInstance();
DriverManager.registerDriver( driver );

[Code] ....

View Replies View Related

Enum Class Throwing Illegal Argument Exception?

Mar 4, 2015

I have a enum class which contains some string which i am comparing to a string i get from a user

Java Code:

public enum Compare {
a, b, c, d, e, f
} class SomeClass {
String method(String letter){
Compare word= Compare.valueOf(letter);
}
} mh_sh_highlight_all('java');

Everything works fine but when I added a new word to it like "g" it throws the IllegalArgumentException ?

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved