How to convert integral number passed as parameter to String - java

I am working on program and I am struck at this point /
public static int numOutput( Integer.toString(int number))
{
String outputNumber="";
if (outputNumber.length()<=10)
{
outputNumber.concat(number);
}
else
{
return outputNumber;
}
}
How can I fix this??

Integer.toString(int number) should be in the body of the method, not in the argument declaration.
Are you trying to concat the number passed to an empty String? Just use take Integer.toString(number) or number + ""
You must return an integer as you have declared that. Either change the return type to String or change the values returned to an int.
You check the length of an empty string. It will always be less than 10.
public static int numOutput(int number) {
String outputNumber = "";
if (outputNumber.length()<=10) {
outputNumber = number + "";
} else {
return number;
}
return -1;
}

Related

Integer.valueOf(char) returning ASCII value

An integer is input as string s. This function checks if the integer is in the given base system. (Assume int base is between 2 and 10.)
public static boolean isBase(String s, int base) {
for (int n=0; n<s.length(); n++) {
if (Integer.valueOf(s.charAt(n))>=base) {
return false;
}
}
return true;
}
Integer.valueOf(s.charAt(n)) gives the ASCII value. For example, if s='110', then s.charAt(0)=1 and Integer.valueOf(s.charAt(0))=49. How can I return the integer value 1 instead?
Replace
Integer.valueOf(s.charAt(n))
by
Character.getNumericValue(s.charAt(n))
for(String c : s.split("")) {
if(Integer.valueOf(char) >= base){
return false;
}
}

Why do doubles not correctly parse from my String[] array?

I am trying to parse double values from a single dimension String array. When I attempt to do this, the doubles always parse as 0.0, never as the correct value. Why is this the case?
Code:
Parser Method: (Ignore integer parser, this one works fine when given an integer)
NumReturn numberParser(int cIndex) { // current index of array where num is
NumReturn nri;
NumReturn nrd;
try {
nri = new NumReturn(Integer.parseInt(Lexer.token[cIndex]), cIndex++, 'i');
System.out.println(nri.value + " ");
return nri;
}
catch (NumberFormatException intExcep) {
}
try {
nrd = new NumReturn(Double.parseDouble((Lexer.token[cIndex])), cIndex++, 'd');
System.out.println(nrd.dvalue + " ");
return nrd;
}
catch (NumberFormatException doubExcep) {
doubExcep.printStackTrace();
}
return null;
}
NumReturn Class:
package jsmash;
public class NumReturn {
int value;
double dvalue;
int pointerLocation;
char type;
NumReturn(int value, int pointerLocation, char type) {
this.value = value;
this.pointerLocation = pointerLocation;
this.type = type;
}
NumReturn(double dvalue, int pointerLocation, char type) {
this.dvalue = value;
this.pointerLocation = pointerLocation;
this.type = type;
}
}
String array which I am trying to parse from:
static String[] token = new String[100];
token[0] = "129.4"; // I call my parser on this element of the array
token[1] = "+";
token[2] = "332.78"; // I call my parser on this element of the array
It looks to me like the problem here is a simple typo. In the second NumReturn constructor (the one with the double parameter), you currently have the following:
this.dvalue = value;
This will assign this.dvalue to the initial value of this.value, which is 0. It is ignoring the constructor parameter entirely. What you actually want is this:
this.dvalue = dvalue;
^

java put null in int variable

I have a code
public int getValue()
{
int i = null;
if(condition)
{
i = 10;
}
return i;
}
This works fine for String variables. How to do the same with int variables ?
int is a primitive type. It cannot hold null value.
You can either use Integer to hold null values, or use 0 (or -1) as the default int value.
null is a valid value for objects, not for primitives.
Since String instances are objects, this is why it compiles it this case.
To get your code compiling in the case with the int, just do:
int i;
if (condition) {
i = 10;
} else {
i = -1; //or some other value when the condition is not met.
}
Only Objects can hold a null value. Since int is a primitive type it has its own default value.
Objects default is null
Data Type Default Value (for fields)
byte 0
short 0
**int** 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
**String (or any object)** null
boolean false
Try
int i = 0;
or even left it and assign later, If it is a instance member. Remember that local variables need to be initialize before they are using at that place you have to assign.
The nullequivalent for int is 0.
You can't put "null" as a value for primitive data type in java, but you can use Objects like "Integer":
Example:
public Integer getValue() {
Integer i;
return i = (condition ? null : 10);
}
The previous code will return null as Integer object if your condition is true, otherwise it will return 10.
But, commonly used to return -1 as default int value if conditions not matched, so you can use:
public int getValue() {
int i = -1;
return i = (condition ? -1 : 10);
}
You can use Integer instead of int .
public static Integer getValue()
{
Integer i = null;
if(condition)
{
i = 10;
}
return (i==null)?0:i;
}
If you don't want to change int , then you can give
public static int getValue()
{
int i=0;
if(condition)
{
i = 10;
}
return i;
}
I use a sentinel value like MIN_VALUE
public int getValue() {
int i = Integer.MIN_VALUE;
// do something
if (i == Integer.MIN_VALUE) {
i = 10;
}
return i;
}
However the simpler solution is to give an appropriate default value like 10
public int getValue() {
int i = 10;
// do something
return i;
}
Primitives (int, long, byte, etc) doesn't have null values, that applies only to objects (and String is an object in Java). Also note that default value for primitives is usually 0, for objects is null. You have several options to overcome this
Throw an exception
public int getValue() {
if(condition) {
return 10;
}
throw new IllegalStateException("Condition must be met");
}
Or you can return some arbitrary number which will tell you that condition wasn't met, -1 is a standard way.
public int getValue() {
int value = -1;
if(condition) {
value = 10;
}
return value;
}
Also note that i is usually used within for loop, so I would prefer different name for that variable, it can be confusing otherwise.

How to assign numbers to words in java?

I have a problem about the last part of the code. I want to assign numbers to specific words but i always get 0 value, even though I get those strings from the first System.out.println correctly, i cannot get the numerical equivalents of those strings at the second System.out.println.Any ideas how to solve this problem?
public static double number;
protected void myMethod(HttpServletRequest request, HttpServletResponse response) {
String speech= request.getParameter("speech");
System.out.println("The recognized speech is : "+ speech);
// There is no problem till here.
if(speech == "Hi")
number = 1 ;
if(speech== "Thanks")
number = 2 ;
if(speech== "Bye")
number = 0 ;
System.out.println("The number for the speech is : " + number);
}
However here i dont get the correct numbers but only 0 for each word!
The == will only be true if the Strings are the same object. Use:
if(speech.equals("Hi"))
or to match without case:
if(speech.equalsIgnoreCase("hi"))
You can't use the == operator to check if two Strings have the same value in Java, you need to use the .equals() or equalsIgnoreCase() methods instead:
if("Hi".equalsIgnoreCase(speech)) {
number = 1;
}
else if("Thanks".equalsIgnoreCase(speech)) {
number = 2;
}
else if("Bye".equalsIgnoreCase(speech)) {
number = 0;
}
else {
number = -1;
}
The reason for this is that the == operator compares references; that is it will return true if and only if the instance stored in variable speech is the same instance as the literal String you've created between double quotes ("Hi", "Thanks", or "Bye").
Note also that I use the equalsIgnoreCase() call on the literal String I'm declaring, rather than the variable that is assigned from the parameter. This way, if a speech == null, the method call is still valid ("Hi" will always be a String), and so you won't get a NullPointerException, and the flow will continue until the else branch.
Try the following snippet:
Main.java
public class Main {
public static void main(String[] args) {
List<StringWithValue> stringList = new ArrayList<StringWithValue>();
stringList.add(new StringWithValue("Hi", 1));
stringList.add(new StringWithValue("Thanks", 2));
stringList.add(new StringWithValue("Bye", 3));
String speech = "Hi";
int number = 0;
for(StringWithValue swv : stringList){
if(swv.getString().equals(speech)){
number = swv.getValue();
break;
} else {
number = -1;
}
System.out.println("The number for the speech is : " + number);
}
}
StringWithValue.java
public class StringWithValue {
private String string;
private int value;
public StringWithValue(String string, int value) {
this.string = string;
this.value = value;
}
public String getString() {
return string;
}
public int getValue() {
return value;
}
}
public static double number;
if(speech=="hi")
{
number=1;
}
else if(speech=="thanks")
{
number=2;
}
else if(speech=="Bye")
{
number=0;
}
else
{
System.out.println("Word Not Found");
}

how to uncompress a given string in java recursively?

this is very easy using iteration but i have to do this using recursion. I tried to keep a count of how many times a char occurs in a string, the position and the rest of the string and output.
public static String uncompress(String compressedText) {
return uncompress(compressedText, 1, 0, "");
}
public static String uncompress(String text, int count, int pos, String output) {
if (text.equals("")) {
return "";
}
if (Character.isLetter(text.charAt(pos))) {
output += text.charAt(0);
pos++;
}
else if(Character.isDigit(text.charAt(pos))) {
count = text.charAt(pos) - '0';
output += text.charAt(pos + 1);
count++;
pos++;
}
text = text.substring(pos + 1);
uncompress(text, count, pos, output);
return output;
}
There are multiple errors in your code such as:
you are substringing but also passing in a position, you should do one or the other
your base case is returning "" but instead it should return the accrued string 'output'
where you recurse you disregard the output from the returning method and just return the output in the current method so nothing is built up by the recursion
Below is code which uses only recursion both to parse the string and build up the output. I have added comments to show what is happening in the code. Note that, particularly in recursion, it is useful to have a printout of the current state so you can see what is happening at each stage so I have added this too.
Note that the getMultiple() method is in itself a very simple example of how recursion should work - that you call the same method but either A) pass in some work done in the current call so that it can be accrued by the base case or B) take the output of the method and add something to it / modify it before returning the modified output.
public class Recursion {
public static void main(String[] args) {
System.out.println(uncompress("10a2b"));
}
public static String uncompress(String compressedText) {
return uncompress(compressedText, "", "");
}
public static String getMultiple(char x, int N) {
if (N == 0) return "";
return ""+x+getMultiple(x,N-1);
}
public static String uncompress(String text, String count, String output) {
System.out.println("----");
System.out.println("TEXT:"+text);
System.out.println("COUNT:"+count);
System.out.println("OUTPUT:"+output);
if (text.equals("")) {
//base case - no text left to parse
return output;
}
if (Character.isLetter(text.charAt(0))) {
//letter case - need to take the count we have accrued, parse it into an integer and add to output
System.out.println(count);// * text.charAt(0);
output += getMultiple(text.charAt(0),Integer.parseInt(count));
count = "";
}
else if(Character.isDigit(text.charAt(0))) {
//digit case - need to add to the count but keep as a string because must be parsed later
count += (""+text.charAt(0));
}
//parse the *remainder* of the string, one character at a time, so pass in the substring(1)
return uncompress(text.substring(1), count, output);
}
}
Assuming that the input String has a correct format, try this:
public static String uncompress(String compressedText) {
if (compressedText.length() == 0)
return "";
return uncompress(compressedText, charToInt(compressedText, 0), 0);
}
public static String uncompress(String text, int count, int pos) {
if (pos == text.length() || (pos == text.length()-2 && count == 0))
return "";
else if (count == 0)
return uncompress(text, charToInt(text, pos+2), pos+2);
return text.charAt(pos+1) + uncompress(text, count-1, pos);
}
public static int charToInt(String str, int idx) {
return str.charAt(idx) - '0';
}

Categories