Integer.valueOf(char) returning ASCII value - java

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;
}
}

Related

how to write a code for return an integer value in java with various cases like if condition

There are 3 integers i.e. a=5 , b=10, c=5. So if all are same then it returns 0. If any 2 are same then it returns 1. If no one is same the it should return 2.
public class Return {
int decide(int a, int b, int c) {
if(a==b && b==c) {
return 0;
}
if(a==b||a==c||b==c) {
return 1;
}
if(a!=b && a!=c && b!=c) {
return 2;
}
return 0;
}
public static void main(String[] args) {
new Return().decide(5,10,15);
}
}
For an output just sub your last line of code with this one:
System.out.print(new Return().decide(5,10,15));

Reverse a number using String builder in java

Problem Statement: Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
My Solution:
class Solution7{
public int reverse(int x) {
if(x>Integer.MAX_VALUE || x<Integer.MIN_VALUE) {
return 0;
}
StringBuilder S_rev = new StringBuilder();
String S_r_v=S_rev.append(Math.abs(x)).reverse().toString();//.toString() String builder to String
double reverse_no=Double.parseDouble(S_r_v);
if (x < 0) {
return -(int)reverse_no;
}
return (int)reverse_no;
}
}
My Solution is ok for most of the test case. But it cannot pass one test case and I got a error
Error: Line 10: java.lang.NumberFormatException: For input string: "8463847412-"
If someone know what type of error it is please discuss.
Thank you in advance.
It seems like you are trying to pass in Integer.MIN_VALUE
When you pass in the minimum integer value, Math.abs seems to return a negative number as stated here
https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#abs-int-
Note that if the argument is equal to the value of Integer.MIN_VALUE, the most negative representable int value, the result is that same value, which is negative.
You can either check for x<=Integer.MIN_VALUE and return 0 if x is Integer.MIN_VALUE or handle the special case for Integer.MIN_VALUE
if(x== Integer.MIN_VALUE)
return -8463847412;
By converting number to String and reversing the sign symbol ended up on the end of the value. This makes the number invalid.
You don't have to convert to String or double. You can use module operator % to extract digits:
public int reverse(int x) {
long result = 0;
while (x != 0) {
result *= 10;
result += x % 10;
x /= 10;
}
if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
throw new IllegalArgumentException(); // overflow
}
return result;
}
If you necessarily want to implement it using StringBuilder, here it is:
public static void main(String[] args) {
ReverseNum reverseNum = new ReverseNum();
System.out.println(reverseNum.reverse(-123));
System.out.println(reverseNum.reverse(123));
System.out.println(reverseNum.reverse(0));
}
public int reverse(int x) {
int res = 1;
String xStr = String.valueOf(x);
StringBuilder builder = null;
if (xStr.startsWith("-")) {
builder = new StringBuilder(xStr.substring(1));
res = -1;
} else {
builder = new StringBuilder(xStr);
}
return res * Integer.valueOf(builder.reverse().toString());
}
Output:
-321
321
0
P.S. If you want to avoid integer overflow, then you can simply use long instead of int, like this:
public long reverse(int x) {
long res = 1;
String xStr = String.valueOf(x);
StringBuilder builder = null;
if (xStr.startsWith("-")) {
builder = new StringBuilder(xStr.substring(1));
res = -1;
} else {
builder = new StringBuilder(xStr);
}
return res * Long.valueOf(builder.reverse().toString());
}
public class ReverseString {
public static void main(String args[]) {
ReverseString rs = new ReverseString();
System.out.println(rs.reverse(-84638));
System.out.println(rs.reverse(5464867));
}
public long reverse(int number) {
boolean isNegative = number < 0;
StringBuilder reverseBuilder = new StringBuilder();
String reversedString = reverseBuilder.append(Math.abs(number)).reverse().toString();
long reversedStringValue = Long.parseLong(reversedString);
if(isNegative) {
return reversedStringValue * -1;
} else {
return reversedStringValue;
}
}
}
This code provides the output you have mentioned in the requirement. And It also supports for integer overflow. Your requirement is to convert int values. It is okay to get the converted value in the higher format since converted value may not be in the range of int. I have changed the reverse method return type to long.
I have identified a few issues in your code.
public int reverse(int x) {
if(x>Integer.MAX_VALUE || x<Integer.MIN_VALUE) {
return 0;
}
Above code segment, not point of checking whether the value is inside the int range because it is already received in the param as a string. It should throw an error before executing your code lines since it is not able to fit the larger value to int variable.
Finally, the int number you have used is not in the int range. (-8463847412)
What about this?
public class ReverseNumber {
public static void main(String[] args) {
System.out.println(reverse(123456));
System.out.println(reverse(0));
System.out.println(reverse(-987654));
}
private static int reverse(int i) {
final int signum;
if(i < 0) {
signum = -1;
} else {
signum = +1;
}
int reversedNumber = 0;
int current = Math.abs(i);
while(0 < current) {
final int cipher = current % 10;
reversedNumber = Math.addExact(Math.multiplyExact(reversedNumber, 10), cipher);
current = current / 10;
}
return signum * reversedNumber;
}
}
Output:
654321
0
-456789
This solution avoids strings and can handle negative numbers.
It throws an Arithmetic exception if an integer overflow happens.

How to convert integral number passed as parameter to String

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;
}

Searching through an Array of Objects

I'm attempting to return the index of where an object appears in an array of objects.
public static int search(WordCount[] list,WordCount word, int n)
{
int result = -1;
int i=0;
while (result < 0 && i < n)
{
if (word.equals(list[i]))
{
result = i;
break;
}
i++;
}
return result;
}
WordCount[] is the array of objects.
word is an instance of WordCount.
n is the number of objects in WordCount[]
It runs, but isn't returning the index correctly. Any and all help is appreciated. Thanks for your time.
CLASS
class WordCount
{
String word;
int count;
static boolean compareByWord;
public WordCount(String aWord)
{
setWord(aWord);
count = 1;
}
private void setWord(String theWord)
{
word=theWord;
}
public void increment()
{
count=+1;
}
public static void sortByWord()
{
compareByWord = true;
}
public static void sortByCount()
{
compareByWord = false;
}
public String toString()
{
String result = String.format("%s (%d)",word, count);
return result;
}
}
How I'm calling it...
for (int i=0;i<tokens.length;i++)
{
if (tokens[i].length()>0)
{
WordCount word = new WordCount(tokens[i]);
int foundAt = search(wordList, word, n);
if (foundAt >= 0)
{
wordList[foundAt].increment();
}
else
{
wordList[n]=word;
n++;
}
}
}
}
By default, Object#equals just returns whether or not the two references refer to the same object (same as the == operator). Looking at what you are doing, what you need to do is create a method in your WordCount to return word, e.g.:
public String getWord() {
return word;
}
Then change your comparison in search from:
if (word.equals(list[i]))
to:
if (word.getWord().equals(list[i].getWord()))
Or change the signature of the method to accept a String so you don't create a new object if you don't have to.
I wouldn't recommend overriding equals in WordCount so that it uses only word to determine object equality because you have other fields. (For example, one would also expect that two counters were equal only if their counts were the same.)
The other way you can do this is to use a Map which is an associative container. An example is like this:
public static Map<String, WordCount> getCounts(String[] tokens) {
Map<String, WordCount> map = new TreeMap<String, WordCount>();
for(String t : tokens) {
WordCount count = map.get(t);
if(count == null) {
count = new WordCount(t);
map.put(t, count);
}
count.increment();
}
return map;
}
This method is probably not working because the implementation of .equals() you are using is not correctly checking if the two objects are equal.
You need to either override the equals() and hashCode() methods for your WordCount object, or have it return something you want to compare, i.e:word.getWord().equals(list[i].getWord())
It seems easier to use:
public static int search(WordCount[] list, WordCount word)
{
for(int i = 0; i < list.length; i++){
if(list[i] == word){
return i;
}
}
return -1;
}
This checks each value in the array and compares it against the word that you specified.
The odd thing in the current approach is that you have to create a new WordCount object in order to look for the count of a particular word. You could add a method like
public boolean hasEqualWord(WordCount other)
{
return word.equals(other.word);
}
in your WordCount class, and use it instead of the equals method:
....
while (result < 0 && i < n)
{
if (word.hasEqualWord(list[i])) // <--- Use it here!
{
....
}
}
But I'd recommend you to rethink what you are going to model there - and how. While it is not technically "wrong" to create a class that summarizes a word and its "count", there may be more elgant solutions. For example, when this is only about counting words, you could consider a map:
Map<String, Integer> counts = new LinkedHashMap<String, Integer>();
for (int i=0;i<tokens.length;i++)
{
if (tokens[i].length()>0)
{
Integer count = counts.get(tokens[i]);
if (count == null)
{
count = 0;
}
counts.put(tokens[i], count+1);
}
}
Afterwards, you can look up the number of occurrences of each word in this map:
String word = "SomeWord";
Integer count = counts.get(word);
System.out.println(word+" occurred "+count+" times);

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");
}

Categories