Store the enum constants in variable - enums

This code actually works fine, the question I have with my code is how do you store the enum constant in any variable, and why do we use enum? and what does the statement mean HouseType houseType;? Thank you so much in advance.
import java.util.Scanner;
public class HomeBuying {
public enum HouseType{UNKNOWN,SINGLEFAMILY,TOWNHOUSE,CONDOMINIUM};
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the type of house you want to purchase"); //1.Single Family/n" " 2. Townhouse/n" " 3. Condominium/n");
int choice = input.nextInt();
HouseType houseType;
switch(choice) {
case 1:
houseType = HouseType.SINGLEFAMILY;
break;
case 2:
houseType = HouseType.TOWNHOUSE;
break;
case 3:
houseType = HouseType.CONDOMINIUM;
break;
default:
houseType = HouseType.UNKNOWN;
break;
}
System.out.println(houseType);
}

The code snippet you provided already stores an Enum value in a variable.
HouseType houseType; //declaration of variable of type HouseType (means it can store values of the HouseType enum)
houseType = HouseType.UNKNOWN; //put value into the houseType variable
We use enums whenever we need to represent values from some known and finite set. For example if you want your program to keep track of whether it is day or night, you could just make up some rule for yourself and use integers, say 1 represents day and 0 represents night. But then what the other numbers mean? Or you could just use boolean for that (again, with some arbitrary meaning attached to false and true).
enum TimePeriod{
DAY,
NIGHT
}
Enums represent a better alternative by letting you to be explicit about what values mean. This is not just a convenience - being explicit in your intentions is what makes your program readable by others.

Related

How do I avoid returning a null value while avoiding mutation?

I am trying to create a method that will take a list of items with set weights and choose 1 at random. My solution was to use a Hashmap that will use Integer as a weight to randomly select 1 of the Keys from the Hashmap. The keys of the HashMap can be a mix of Object types and I want to return 1 of the selected keys.
However, I would like to avoid returning a null value on top of avoiding mutation. Yes, I know this is Java, but there are more elegant ways to write Java and hoping to solve this problem as it stands.
public <T> T getRandomValue(HashMap<?, Integer> VALUES) {
final int SIZE = VALUES.values().stream().reduce(0, (a, b) -> a + b);
final int RAND_SELECTION = ThreadLocalRandom.current().nextInt(SIZE) + 1;
int currentWeightSum = 0;
for (Map.Entry<?, Integer> entry : VALUES.entrySet()) {
if (RAND_SELECTION > currentWeightSum && RAND_SELECTION <= (currentWeightSum + entry.getValue())) {
return (T) entry.getKey();
} else {
currentWeightSum += entry.getValue();
}
}
return null;
}
Since the code after the loop should never be reached under normal circumstances, you should indeed not write something like return null at this point, but rather throw an exception, so that irregular conditions can be spotted right at this point, instead of forcing the caller to eventually debug a NullPointerException, perhaps occurring at an entirely different place.
public static <T> T getRandomValue(Map<T, Integer> values) {
if(values.isEmpty())
throw new NoSuchElementException();
final int totalSize = values.values().stream().mapToInt(Integer::intValue).sum();
if(totalSize<=0)
throw new IllegalArgumentException("sum of weights is "+totalSize);
final int threshold = ThreadLocalRandom.current().nextInt(totalSize) + 1;
int currentWeightSum = 0;
for (Map.Entry<T, Integer> entry : values.entrySet()) {
currentWeightSum += entry.getValue();
if(threshold <= currentWeightSum) {
return entry.getKey();
}
}
// if we reach this point, the map's content must have been changed in-between
throw new ConcurrentModificationException();
}
Note that the code fixes some other issues of your code. You should not promise to return an arbitrary T without knowing the actual type of the map. If the map contains objects of different type as key, i.e. is a Map<Object,Integer>, the caller can’t expect to get anything more specific than Object. Besides that, you should not insist of the parameter to be a HashMap when any Map is sufficient. Further, I changed the variable names to adhere to Java’s naming convention and simplified the loop’s body.
If you want to support empty maps as legal input, changing the return type to Optional<T> would be the best solution, returning an empty optional for empty maps and an optional containing the value otherwise (this would disallow null keys). Still, the supposed-to-be-unreachable code point after the loop should be flagged with an exception.

How to change string to integer

How can I change a string input to integer-
for example-
read_line_to_codes(user_input,L),
atom_codes(C,L).
In this C is storing a string.Suppose the user entered 18.So I want to use this 18 as an integer so that I can use operations like >= with C.Is this possible in Prolog?
Prolog datatypes don't include 'strings'. SWI-prolog added it recently, but you can stay on ISO safety lane with number_codes
You can forcefully assigned an int datatype to the user input, you are letting the JVM know that you know what you are doing and this will let the program compile in case if the int data type is smaller than the user input string size. Here is an example code to help you.
public class stringToInt{
public static void main(String []args){
string C = 18; //User input, make sure to use the scanner class to get the user input value
int int_C = (int) C;
/**Your new value is now in int datatype and you can go ahead and use int_C for your arithmetic
opreation **/
}
}

Creating a constructor

I've got some code I need help with. I'm an AP CS student (and it's introductory) so please don't judge me.
// name:
//
// program: CoinsTester
//
// purpose:
public class CoinsTester {
public static void main(String[] args) {
//create a new Coins object named money and pass it the amount of cents as a parameter
//***** STUDENTS NEED TO COMPLETE ******
Coins();
Coins money = new Coins();
// call the correct method in the Coins class to find your answer
//***** STUDENTS NEED TO COMPLETE ******
money.calculate();
}
}
// name:
//
// program: CoinsTester
//
// purpose: This class accepts a certain number of monetary change.
// The output is a list of the number of quarters, dimes, nickels,
// and pennies that will make that amount of change with the least
// number of coins possible. This is a skeleton that will be finished
// by the students
public class Coins {
//private variable to store the only attribute of a "Coins" object - how many cents the
// user wants to find change for.
private int myChange;
//constructor that accepts an initial value for the private data member
public Coins(int change) {
myChange = change;
}
// the method calculate will
// 1. use modular and regular division to determine the quantity of each type of coin
// 2. prints the quantity of the coins needed to make the entered amount
public void calculate(){
int quarters=25, dimes=10, nickels=5, pennies=1;
int temp1, temp2, temp3, temp4;
int remainquar1, remaindime2, remainnick3, remainpenn4;
//variable declarations to hold the values needed for different coin types
// make sure you use descriptive identifiers!
//***** STUDENTS NEED TO COMPLETE ******
// calculations for the various coin types
//***** STUDENTS NEED TO COMPLETE ******
// output statements, formatted as shown on specs
//***** STUDENTS NEED TO COMPLETE ******
}
}
So here is the thing, I do apologize for my improperly formatted code. So when I run it, it says that Coins money = new Coins() cannot find a constructor for the code. I need help in creating a proper object. The thing here is that I have to create an object for "CoinsTester" then it tells me I have no constructor linked to the object. I really can't find solutions right now. Could someone just give me tips on how to create a constructor for the CoinsTester class?
Add a "method" named CoinsTester (if you need a constructor for the class CoinsTester, it's not clear from your Q what constructor you need). Make sure the arguments correspond to the calling sequence, if you want the added explicit constructor to be used.
You have two lines that need reviewing:
Coins();
This would call a method named Coins, not a constructor. I sugggest you remove this, as you most likely will not use/need it.
Coins money = new Coins();
The reason there is no constructor linked to this is that you already have a constructor for Coins:
public Coins(int change) {
myChange = change;
}
When you created this constructor, you removed the default constructor new Coins();. If you'd like to be able to use the Coins constructor with no parameters, you can declare it again. Here's an example:
public Coins() {
myChange = 0;
}

Hangman Game: actual and formal argument lists differ in length

I'm struggling with this very simple code: I'm trying to print off "_ " marks, with one _ mark for each letter in a word inputted by a user. Whenever I try to compile the code, however, I get "error: method makeLine in class game_3 cannot be applied to given types; reason: actual and formal argument lists differ in length."
That seems like pretty clear feedback, but I don't think I really understand it - At first, I thought it was because I hadn't assigned a value to stringNumber, but assigning it a value didn't help. What's wrong?
/*Assignment:
Write a reverse Hangman game in which the user thinks of a word and the computer tries
to guess the letters in that word. Your program must output what the computer guessed
on each turn, and show the partially completed word. It also must use pseudorandom
functions to make guesses. That is, it should not simply try all the letters in order,
nor should it use the user’s input to its advantage.
*/
import java.util.*;
public class game_3 {
public static void main(String[] args) {
getIntroduction();
playGame();
}
public static void getIntroduction(){
System.out.println();
System.out.println();
System.out.println("*************************");
System.out.println("Welcome to Hangman");
System.out.println("In this game, you'll provide a word for the computer to guess.");
System.out.println();
System.out.println("The computer will guess letters randomly, and assess whether");
System.out.println("they can be used to complete your word.");
System.out.println();
System.out.println("Let's play!");
System.out.println();
System.out.println("*************************");
System.out.println();
}
public static void playGame(){
Scanner input = new Scanner(System.in);
System.out.print("Please enter a word: ");
String hangWord = input.next();
int stringNum = hangWord.length();
makeLine();
}
public static void makeLine(int stringNum){
for (int i = 0; i < stringNum; i++){
System.out.print("_ ");
}
}
}
The method makeline expects an argument of int:
public static void makeLine(int stringNum){
You're calling it with no arguments:
makeLine();
What it looks like you want is:
makeLine(stringNum);
Edit: To be clear, that's what the error message is referring to by formal argument list(expected) and the actual argument list(what you gave it). The other common error message that happens when what you give a method doesn't match what it expects is "The method methodName(expected args) is not applicable for the arguments (given args). This occurs when the types don't match up: if you pass in a String when it expects an int, or if you pass in the right types, but out of order.

Boolean that can only be flipped to true

Is there a name for a data structure (read: boolean) that can only be moved from false to true, and not back to false? Imagine something encapsulated like so:
private var _value = false
def value = _value
def turnOnValue() = value = true
And out of curiosity, are there any platforms that support it natively? This seems like something somebody must have come across before...
You're describing a temporal property of a variable; rather than a data structure as such. The data type is a simple boolean, but it is how it is used that is interesting -- as a sort of 'latch' in time.
That kind of latch property on a boolean data type would make it an example of a linearly typed boolean. Linear types, and other kinds of uniqueness types are used to enforce temporal properties of variables -- e.g. that they can only be used once; or cannot be shared.
They're useful for enforcing at compile time that an action has happened (e.g. initialization) or having a compile-time proof that an object is not shared. Thus, they're most common in systems programming, where proofs of low level properties of this are key to correct software design.
In perl you have Tie Variables and you can build your on scalar value and make this kind of "type". But natively... maybe in Smalltalk can be possible to build something like this, or Prolog, but I don't know.
Make your own data type
public final class CustomBoolean {
private boolean value;
public void setValue(boolean value){
// Bitwise OR
this.value |= value;
}
public boolean getValue(){
return value;
}
}
Example ::
public static void main (String[] args)
{
CustomBoolean foo = new CustomBoolean();
foo.setValue(false);
System.out.println(foo.getValue());
foo.setValue(true);
System.out.println(foo.getValue());
foo.setValue(false);
System.out.println(foo.getValue());
}
The output would be ::
false
true
true
This means you'll have to call getValue() before doing any explicit boolean operations
ie
if(foo.getValue() && 1 == 1)
The example is written in Java.

Resources