parseInt() method. Keep getting Null Pointer Exception on highlighted line - parseint

just been trying to convert a string into an Integer so that I can use it for something else but I keep falling into the null pointer exception trap.
public class ConvertToInt {
private InputReader reader;
public int changeToInteger(String word){
// Problem i've got is just below, I keep getting a null point exception on this line each time
// I want to return the result.
return reader.convertToInt(word); // null ponter exception on this line
}
}
parseInt method from InputReader class:
/**
* Convert the given word to an integer.
* #param word The word to be converted.
* #return The integer represented by word.
* #throws NumberFormatException if word is not an integer.
*/
public int convertToInt(String word)
{
return Integer.parseInt(word);
}

Related

Solution for "Return argument type string storage ref is not implicitly convertible to expected type (type of first return variable) string calldata"?

I'm a newb doing my first contract with no coding experience. Can someone help with resolving this error please? The error message is: "Return argument type string storage ref is not implicitly convertible to expected type (type of first return variable) string calldata." The error is in response to the getGreetings function, which is Ln 27, Col 16 where "return message;" is.
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
contract GreetingsContract {
/** This is a state variable of type string called message. This is an instance variable used to store the greetings message.
The string data type means that the variable will contain a variable length array of characters. */
string message;
/** This is a constructor "Greetings" with no paramater and no return value. This is public so that it can be called outside of the contract.
Solidity lets us define a constructor that will be called only once when the contract is first deployed to the blockchain.
The constructor does not return any value in the contract. */
function Greetings() public {
message = "I'm ready!";
}
/** This will take one parameter of type string and the name will be "_message" so we can differentiate with the internal state variable.
We'll only alter the state of the contract to overwrite the internal message with the argument.
This function will alter the instance variable with the value sent in parameter. This is also public and doesnt return anything.
This is often the case for functions that modify the state of the contract because there is currently no way to acces the values returned by such a function. */
function setGreetings(string calldata _message) public {
message = _message;
}
/**View will return the string and the message. */
**function getGreetings() public view returns (string calldata) {
return message;
}**
}
function getGreetings() public view returns (string calldata)
calldata is a read-only data location initialized in the function input. You could return string calldata in a different scenario - if you accepted a string calldata as an input, and then returned the same value.
function foo(string calldata inputString) public pure returns (string calldata) {
return inputString;
}
Since you're returning the value of a storage property, its value is loaded from storage to memory (not to calldata). So you need to return string memory.
function getGreetings() public view returns (string memory) {
return message;
}

Overloading a method which accepts `object` as default parameter type

I need to be able to call a method and pass in an object of an unknown type
but then have the correct overload called. I also need a default implementation that accepts
object as its parameter type. What I'm seeing is that the default overload is the only one that ever gets used.
Here's the gist of what I'm trying to do:
class Formatter
{
private object Value;
public Formatter(object val){
Value = val;
}
public override string ToString()
{
return Format(Value);
}
private string Format(object value)
{
return value.ToString();
}
private string Format(DateTime value)
{
return value.ToString("yyyyMMdd");
}
}
Ok, so far so good. Now I want to be able to do this:
public static class FancyStringBuilder()
{
public static string BuildTheString()
{
var stringFormatter = new Formatter("hello world");
var dateFormatter = new Formatter(DateTime.Now);
return String.Format("{0} {1}", stringFormatter, dateFormatter);
}
}
The result of FancyStringBuilder.BuildTheString() is "hello world 2012-12-21 00:00:00.000", when I expected "hello world 20121221"
The problem is that the overload that accepts a DateTime is not being called, instead defaulting to the overload which accepts an object. How can I call the proper method without resorting to a messy switch statement?
In Formatter.ToString(), the override Formatter.Format(object) is always called. This is because the overload resolution happens at compile-time, not run-time. At compile-time, the only thing known about Value is that it's an object.
If you really want to distinguish incoming types, you'll need to do so in Formatter's constructor. In this case, rather than hanging on to the object, you could just call ToString() immediately and only store the formatted result:
class Formatter
{
string formattedValue;
public Formatter(object value)
{
formattedValue = value.ToString();
}
public Formatter(DateTime value)
{
formattedValue = value.ToString("yyyyMMdd");
}
public string ToString()
{
return formattedValue;
}
}
Note that this does assume that your object isn't changing between the time you create the Formatter object and the time Formatter.ToString() is called, or at the very least that it's okay to take a snapshot of the string representation at the time the Formatter is created.
This also assumes that you know the incoming types at compile-time. If you want a truly run-time-only solution, you'll have to use the "is" operator or a typeof() comparison.
If your goal is just to provide custom ToString() formatting based on the incoming type, I'd probably do it using a list that maps from types to format strings:
static class Formatter
{
private static List<Tuple<Type, string>> Formats;
static Formatter()
{
Formats = new List<Tuple<Type, string>>();
// Add formats from most-specific to least-specific type.
// The format string from the first type found that matches
// the incoming object (see Format()) will be used.
AddMapping(typeof(DateTime), "yyyyMMdd");
// AddMapping(typeof(...), "...");
}
private static void AddMapping(Type type, string format)
{
Formats.Add(new Tuple<Type, string>(type, format));
}
public static string Format(object value)
{
foreach (var t in Formats)
{
// If we find a type that 'value' can be assigned to
// (either the same type, a base type, or an interface),
// consider it a match, and use the format string.
if (t.Item1.IsAssignableFrom(value.GetType()))
{
return string.Format(t.Item2, value);
}
}
// If we didn't find anything, use the default ToString()...
return value.ToString();
}
}
With that, calling code then looks like:
Console.WriteLine(
"{0} {1}",
Formatter.Format(DateTime.Now),
Formatter.Format("banana"));
I think this is because the class constructor takes an object as parameter, and then assign that object to variable Value which is also an object. There for calling Format(object) since Value is of type object
Try this
public override string ToString()
{
if(Value is DateTime)
return Format(Convert.ToDateTime(Value)); //this should call the right method
return Format(Value); //works for other non-custom-format types e.g. String
}

Custom transformation function throwing error.

This is my transformation function call:
<p><%# MyFunctions.getDocumentCategory(Eval("DocumentID"))%></p>
This is the function:
public static string getDocumentCategory(int documentID)
{
string category;
StringBuilder sb = new StringBuilder();
// Get document categories
var ds = CategoryInfoProvider.GetDocumentCategories(documentID, "CategoryEnabled = 1", null);
// Check whether exists at least one category
if (!DataHelper.DataSourceIsEmpty(ds))
{
// Loop thru all categories
foreach (DataRow dr in ds.Tables[0].Rows)
{
sb.Append(Convert.ToString(dr["CategoryDisplayName"]) + ",");
}
}
string content = sb.ToString();
category = content.Split(',')[0];
return category;
}
}
This is the error:
MyFunctions.getDocumentCategory(int) has some invalid arguments.
I've tried an alternate form of the function that accepts strings rather than ints but it throws the same error. I've verified that the Eval("DocumentID") works correctly when placed by itself. Any ideas?
Eval returns an object. You either need to convert it to an int, or change the function to accept an object, and convert that object to an int.
<p><%# MyFunctions.getDocumentCategory( Convert.ToInt32( Eval("DocumentID") ) )%></p>
OR
public static string getDocumentCategory(object document)
{
int documentID = Convert.ToInt32( document );
etc...
}
Thanks to Doozer for the nice explanation and example.
The second approach - to accept the object and make the conversion inside your custom function - may be better to keep the transformation code cleaner. The result is equal.
Just to add a little bit - you can use Kentico's ValidationHelper for conversions, for example:
transformation:
<%# MyFunctions.getDocumentCategory(Eval("DocumentID"))%>
code:
public static string getDocumentCategory(object docID)
{
int documentID = ValidationHelper.GetInteger(docID, 0); //0 is the default value
...

spring 3.0 type conversion from string in predefined format to a Map having key as the Enum type and value as any type

I am trying to create a generic convertor using Spring 3.0's Type Conversion feature for converting Strings in format "<KEY2>:<VAL>,<KEY2>:<VAL2>,<KEY3>:<VAL3>"
to a Map holding the key-value pairs where key can be an Enum type and value can be of any user-defined or Java's inbuilt type.
Below is the code I tried out.
Note: I am not good at using generics, so please bear with me if I have used generics in wrong way.
import java.lang.reflect.GenericDeclaration;
import java.lang.reflect.TypeVariable;
import java.util.HashMap;
import java.util.Map;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
/**
* Converts a string in a format
* "<KEY2>:<VAL>,<KEY2>:<VAL2>,<KEY3>:<VAL3>"
* to a {#link Map} instance holding the key-value pairs <i>where key
* can be an Enum type and value can be of any type</i>.
*
* #author jigneshg
*
* #param <K>
* #param <V>
*/
public class StringToMapConvertorFactory<V> implements ConverterFactory<String, Map<Enum<?>, V>> {
private static final String COMMA = ",";
private static final String COLON = ":";
#Override
public <T extends Map<Enum<?>, V>> Converter<String, T> getConverter(
Class<T> targetType) {
return new StringToMapConverter<T>(targetType);
}
private final class StringToMapConverter<T extends Map<Enum<?>, V>> implements Converter<String,T> {
public StringToMapConverter(Class<T> targetType) {
}
#SuppressWarnings("unchecked")
#Override
public T convert(String source) {
checkArg(source);
String[] keyValuePairs = source.split(COMMA);
// value at index 0 is assumed as the key
// value at index 0 is assumed as the value
Map<Enum<?>,V> resultMap = new HashMap<Enum<?>, V>();
String[] keyValueArr = null;
String key = null;
String value = null;
for (String keyValuePair : keyValuePairs) {
keyValueArr = keyValuePair.split(COLON);
key = keyValueArr[0];
value = keyValueArr[1];
// TODO: How to specify the enumType here ??
resultMap.put(Enum.valueOf(enumType, key.trim()), (V) value);
}
return resultMap;
}
private void checkArg(String source) {
// In the spec, null input is not allowed
if (source == null) {
throw new IllegalArgumentException("null source is in allowed");
}
}
}
}
I am stuck at how to specify the enum type when putting the key-value pair in resultMap in my code.
Also have I taken the correct approach to implement my requirement or there is a better way in which this can be achieved?
Thanks,
Jignesh
You can implement GenericConverter instead of Converter, and access key type as TypeDescriptor.getMapKeyType().

Simple exercice with exceptions in java

Here's the problem to solve: a method of a class that represents a gas network. This class manages objects of type Line that represent each single gas supply line.
An object of type Line is represented by the following members:
String startCity;
String endCity;
int capacityUsed;
int capacityAvail;
int maxCapacity;
The method I'm having trouble implementing is:
boolean carry(String city1, String city2, int capacity)
Consider all the lines from city1 tocity2. For each of these lines
try using capacity with the method use() (I don't think it's necessary to know how
use() works ). If use() throws the exception CapacitaSuperataException search
other lines between city1 and city2, if there are no other lines use()
must return False. If a call to use() does not throw CapacitaSuperataException means that the line was assigned the capacity, and the method returns True.
I tried some solutions but I don't know how to manage exceptions.
Thanks
Try using the try-catch inside a loop covering all suitable lines in your carry-Method:
for (Line line : getLines("start", "end"))
{
try
{
line.use(cap);
System.out.println("Line used, great!");
return true;
}
catch (CapacitaSuperataException e)
{
System.out.println("Line full, try next");
}
}
System.out.println("No line found");
return false;
public void use(int desiredCapacity) throws CapacitaSuperataException {
if(desiredCapacity > maxCapacity) throw CapacitaSuperataException
...
}
public void example() {
try {
this.use(999999)
} catch(CapacitaSuperataException) { /* show error message */ }
}

Resources