String array with letters to int convertion [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I got this array of string
String s1[] = {"H","E","L","L","O"};
and a method to convert it into int
public static int[] String2Int(String[] k){
int[] arrayBuffer = new int[k.length];
for (int i=0; i < k.length; i++)
{
//arrayBuffer[i] = Integer.parseInt(k[i]);
arrayBuffer[i] = Integer.parseInt(k[i]);
}
return arrayBuffer;
I want the decimal values of the characters but no luck on getting it.
Google is only helping with if the string were a number.

You shouldn't convert it to integer. It should be
arrayBuffer[i] =k[i].charAt(0);
That way you get the ASCII value of char and gets assigned to int.
Edit :
You can also use arrayBuffer[i] = Character.codePointAt(input, 0); as pointed in comments.

Try this:
class MainClass
{
public static void main(String[] args)
{
System.out.println(Arrays.toString(String2Int("HELLO")));
}
public static int[] String2Int(String k)
{
int[] arrayBuffer = new int[k.length()];
for (int i = 0; i < arrayBuffer.length; i++)
{
//arrayBuffer[i] = Integer.parseInt(k[i]);
arrayBuffer[i] = k.charAt(i);
}
return arrayBuffer;
}
}
Output:
[72, 69, 76, 76, 79]
Explanation
char and int is almost the same in Java. You don't need to parse it, you just implicitly cast it by asigning it to the int[]. Also you shouldn't take a String[] as an argument, that makes no sense. A String is already almost a char[]. So either take a String, or a char[]. In my example I've used a String because that is more convenient to call.

Using the Java 8 Stream API:
public static int[] convert(String[] strings)
{
Objects.requireNonNull(strings);
return Arrays.stream(strings)
.mapToInt(str -> Character.getNumericValue(str.charAt(0)))
.toArray();
}
I assume you dont need to check that the input strings contain exactly one character.

Related

In Java, how can I convert a string to a double (not Double)? [duplicate]

This question already has answers here:
Convert String to double in Java
(14 answers)
Closed 6 years ago.
It's part of a school lab and I've researched and I can't find anything to accomplish this task. I'm reading in lines from a file using FileReader and BufferedReader. The data in the file is a name and an age in the following format:
John doe 20
Jane doe 30
etc. I already have code that will take each line and split as such:
split[0] = {"John", "doe", "20"}
I need to get the "20" and store in an array of doubles such as double[0] = 20;
The reason it has to be a double and not Double is because that part of the code in the assignment is already written and I'm sure I cannot just decide to change everything and use a Double instead. How can I do this? Thank you in advance!
Use Double#parseDouble.
As you can see the static method returns a primitive double and not an object Double:
public static double parseDouble(String s)
public static void main(String[] args) {
String strNumber = "20";
double myParsedDouble = Double.parseDouble(strNumber);
System.out.println(myParsedDouble);
}
You'll want to get it into a for loop and start iterating... I'll just use List to manipulate the data, since we don't know how many matches there are (and thus, we cannot set up an array).
String[] startingArray; // Whatever you put in here
List<Double> endingList = new ArrayList<Double>();
for (String element : startingArray) {
try {
endingList.add(Double.parseDouble(element));
} catch (NumberFormatException e) {
// do nothing if it doesn't parse
// note that catching exceptions do not have an adverse effect on performance
}
}
// Either, if you want it in a Double[]... or
Double[] endingArray = endingList.toArray(new Double[endingList.size()]);
// If you want a double[], start iterating...
double[] endingArray = new double[endingList.size()];
for (int i = 0; i < endingList.size(); i++) {
endingArray[0] = endingList.get(0);
}

Using contains method in java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have converted my string array to Array using Arrays.toString(array) method.
But still my string looks like an array in this way. [Monday, Sunday, Tuesday]. Okie thats not the issue. I have another array which is also converted to String.
Say [Monday, Tuesday]. Now this is my problem. When I try to use contains method in these arrays it is not working. Can anyone help.
See Arrays#toString(Object[]):
The value returned by this method is equal to the value that would be returned by Arrays.asList(a).toString(), unless a is null, in which case "null" is returned.
and String#contains(CharSequence):
Returns true if and only if this string contains the specified sequence of char values.
Example:
String[] stringArray = new String[] { "Monday", "Tuesday" };
String string = Arrays.toString(stringArray);
boolean result = string.contains("Tuesday");
But I would recommend:
String[] stringArray = new String[] { "Monday", "Tuesday" };
List<String> stringList = Arrays.asList(stringArray);
boolean result = stringList.contains("Tuesday");
See Arrays#asList(T...) and ArrayList#contains(Object)
This is one way to check if one array got (contains) content of another array without using the contains method
String[] string1 = new String[] { "Monday", "Sunday", "Tuesday" };
String[] string2 = new String[] { "Monday", "Tuesday" };
for (int i = 0; i < string1.length; i++) {
for (int j = 0; j < string2.length; j++) {
if (string1[i].equals(string2[j])) {
// do something here
}
}
}

String with numbers add them Java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm getting a string which contains numbers,
Eg:- 123312351863
which is the best method to separate each number and add them together?
as example total 38
I will not give you the exact answer.
Parse the entire String as an Integer using Integer.parseInt() or Long.parseLong() . Based on appropriate size.
You can add each digit by using the following 2 operators -> / and %.
You will also need a while loop.
Note : This approach fails for very large numbers or if the number starts with 0. You can indeed do it using charAt() + some other string methodd.
public class Simple {
public static void main(String `args`[]){
String str = "123456789";
Integer total = 0;
for (Character eachNumber : str.toCharArray()) {
total += Integer.parseInt(eachNumber.toString());
}
System.out.println(total);
}
}
A short way in Java 8:
String s = "123312351863";
int sum = s.chars().map(Character::getNumericValue).sum();
Try like this:
int res = 0;
String s= "123312351863";
for (int i = 0; i < s.length(); i++)
{
String str= ""+s.charAt(i);
int b = Integer.parseInt(str);
res = res + b;
}
System.out.println(res);
You can first split the string to single characters using String.split("") (note it will give an empty string at the beginning for prior to java8 versions)
Then, iterate the String[], parse each number to int, and sum them
You can split the string by "" , then convert each string to Integer and sum the numbers. E.g. in java 8
System.out.println(Stream.of(s).map(x -> x.split("")).flatMap(Arrays::stream).mapToInt(Integer::parseInt).sum());
Output
38
You can also do
Iterate over the charaters of string using loop and chatAt().
Convert the character to int values using Character.getNumericValue(yourChar).
Then sum up the int values.
I would try as below
public static void main(String args[])
{
String x="123312351863";
String r[]=x.split("");int sum=0;
for(int i=1;i<=x.length();i++)
{
sum+=Integer.parseInt(r[i]);
}
System.out.println(sum);
}

what is wrong with this program?the error comes 'cannot find symbol-variable Tom" [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Wap to initialize 2 arrays,one with 5 names & another with their telephone nos.search for a name input by user.Print the name along with telephone no
import java.io.*;
class search {
public static void main() throws IOException {
InputStreamReader read = new InputStreamReader(System. in );
BufferedReader in = new BufferedReader(read);
int i, j;
String a[] = {Tom, chirag, mohan, pagal, debo};
int t[] = {3442546, 5753432, 907879, 000, 3246};
System.out.println("enter a name");
String s = in .readLine();
for (i = 0; i < 5; i++)
if (a[i] == s) {
System.out.println("Successful");
System.out.println(t[i]);
} else System.out.println("unSuccessful");
}
}
String a[]={Tom,chirag,mohan,pagal,debo} You're missing the double quotes here that denote a string literal in Java, i.e. "Tom","chirag","mohan","pagal","debo"
Btw, a[i] == s won't work since the literals are different objects from the strings created by the input. Use a[i].equals(s) instead.
As a sidenote, I'd probably use a Map<String, Integer> to map the names to the numbers and then instead of looping through the arrays you'd just do map.get(s) and check whether you get something or not. This would get rid of the risk that both arrays might differ in length and order.
Besides that I'd use a.length in the loop instead of the hard coded value 5, i.e. for (i = 0; i < a.length; i++) or yet better for (i = 0; i < Math.min(a.length, t.length); i++).
String literals need double quotes around them.
For example Tom should be "Tom".
Since you left out the quotes, the compiler is trying to interpret Tom as an identifier / symbol. As you haven't declared Tom anywhere, it says "cannot find the symbol Tom".
Sometimes compiler messages can be a bit opaque. The trick to making sense of them is to try to understand what the compiler "thinks" you are trying to say ... not what you think you are trying to say. (It can't read your mind.)
The other answers are correct about ==. It is very dangerous to use == to compare strings. The compiler will happily except it, but the problem is that it usually gives the wrong answer. Always use the equals method to test if two strings are equal.
Finally, once you have gotten past the basics of programming, you need to learn about Java style. For example:
Consistent indentation is very important.
The correct capitalization for identifiers is very important:
A class name should always start with a capital letter; e.g. search should be Search.
A method or field name should never start with a capital letter.
I recommend you read / follow one of the following styles:
Sun's original "Code conventions for the Java language", or
Google Java Style
I see 2 problems in your code
Initialization of String array should be
String a[] = {"Tom", "chirag", "mohan", "pagal", "debo"};
ie string should be in double quotes.
Comparison of string is done with equals
so change if (a[i] == s) to if (a[i].equals(s))
So the final code should be
InputStreamReader read = new InputStreamReader(System. in );
BufferedReader in = new BufferedReader(read);
int i, j;
String a[] = {"Tom", "chirag", "mohan", "pagal", "debo"};
int t[] = {3442546, 5753432, 907879, 000, 3246};
System.out.println("enter a name");
String s = in.readLine();
for (i = 0; i < 5; i++)
if (a[i].equals(s)) {
System.out.println("Successful");
System.out.println(t[i]);
} else System.out.println("unSuccessful");
Demo

Improving this code for reversing the string and removing duplicate characters [duplicate]

This question already has answers here:
Reverse a string in Java
(36 answers)
Closed 8 years ago.
I recently attended an interview where I was asked to write a program.
The problem was:
Take a string. "Hammer", for example.
Reverse it and any character should not be repeated.
So, the output will be - "remaH".
This is the solution I gave:
public class Reverse {
public static void main(String[] args) {
String str = "Hammer";
String revStr = "";
for(int i=0; i<=str.length()-1;i++){
if(revStr.indexOf(str.charAt(i))==-1){
revStr = str.charAt(i)+revStr;
}
}
System.out.println(revStr);
}
}
How I can improve the above?
The problem is String is immutable object, and when using operator+ to concat a char with the current result, you actually create a new string.
This results in creating strings of length 1+2+...+n, which gives you total performance of O(n^2) (unless the compiler optimizes this for you).
Using a StringBuilder instead of concatting strings will give you O(n) performance, and with much better constants as well.
Note that a StringBuilder offers an efficient append() implementaiton, so you need to append elements to it, and NOT add them at the head of your StringBuilder.
You should also reconsider usage of indexOf() - if a characters cannot appear twice at all, consider using a Set<Chatacter> to maintain the list of 'used' characters, if it can appear twice, but not one after the other (for example "mam" is valid) - there is really no need for the indexOf() in the first place, just check the last character read.
Here is a solution without using any stringbuilder or intermediary String objects, just treating Strings as arrays of chars; this should be more efficient.
import java.util.Arrays;
public class Reverse {
public static void main(String[] args) {
String str = "Hammer";
String revStr = null;
char [] chars = str.toCharArray();
char [] reversedChars = new char[chars.length];
// copy first char
reversedChars[reversedChars.length - 1] = chars[0];
// process rest
int r = reversedChars.length - 2;
for(int i = 1 ; i < chars.length ; i++ ){
if(chars[i] != chars[i-1]){
reversedChars[r] = chars[i];
r--;
}
}
revStr = new String(Arrays.copyOfRange(reversedChars, r+1, reversedChars.length));
System.out.println(revStr);
}
package com.in.main;
public class Reverse {
public static void main(String[] args) {
String str = "Hammer";
StringBuilder revStr= new StringBuilder("");
for(int i=str.length(); i>=0;i--){
if(revStr.indexOf(str.charAt(i))==-1){
revStr.append(str.charAt(i));
}
}
System.out.println(revStr);
}
}

Categories

Resources