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);
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Very new java student here (My first post, sorry for wrong formatting). I need help with rephrasing a paragraph.
I need to change the letters of the paragraph to the 13th next letter ie changing a to n and so on meanwhile conserving the structure of the paragraph ie line breaks, full stops, etc...I have only been able to change a word so far and need to expand this code to be able to do it with a paragraph...Thanks in advance...Much appreciated...
public class Assignment1b {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Please type any word: ");
String word = s.nextLine();
String ROT13 = "";
for(int i = 0; i < word.length(); i++){
char c = word.charAt(i);
int value = c - 'a' + 1;
value = value + 13;
char ency = (char)((value % 26) + 'a' - 1);
ROT13 = ROT13 + ency;
}
System.out.println("The encrypted word is: " + ROT13);
}
}
General good programming practice: one method does one thing, and one thing only. This makes code easier to read, test, maintain and reuse. I suggest you start by taking the stuff in your for () loop and sticking it in a new method. Call it private char encryptCharacter(char oldCharacter), or some such. Add the return value to your ROT13 string to build the answer, as you are currently doing.
Your problem is now in this secondary module - how to preserve line breaks, spaces and similar characters. Refer to Charlie Armstrong's comment, that will help you identify them. You will probably end up with something like:
private char encryptCharacter(char oldCharacter) {
if (isWhiteSpaceOrPunctuation(oldCharacter)) {
return oldCharacter;
} else {
// add your code to encrypt the character here
return encryptedCharacter;
}
}
private boolean isWhiteSpaceOrPunctuation(char character) {
// return true or false, as appropriate
}
First you need to split paragraph by words, using method split of String class and passing the char, that splits words, in this case, the space " ". This method return array of String (String[]), which means, array of words, but I convert it to List<String> using Arrays.asList() method, to facilitate the process. Next, I iterate this list, and apply the rephrase method, that encript or change each word.
// this split your paragraph, and invoke your code, which means, rephrase method by word
public static String encript(String paragraph){
// split words by spaces, but punctuation still
List<String> words = Arrays.asList(paragraph.split(" ").clone());
StringBuilder sb = new StringBuilder();
for(String word : words) {
// rephrase and append
sb.append(rephrase(word));
}
return sb.toString();
}
// this is your code in a method, I recommend you rebuild this method using StringBuilder, it is more efficient
public static String rephrase(String word){
String ROT13 = "";
for(int i = 0; i < word.length(); i++){
char c = word.charAt(i);
int value = c - 'a' + 1;
value = value + 13;
char ency = (char)((value % 26) + 'a' - 1);
ROT13 = ROT13 + ency;
}
return ROT13;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I want to add a pair of numbers that are separated by a space. So a user inputs multiple numbers of any length separated by a space. I'm using BigInteger for this. Using two stacks, each pair of numbers must be added together and the results need to be printed out. For example, the output would be like this:
10
+ 10
= 20
99
+ 1
= 100
1000000000000000000000000000000
+ 1000000000000000000000000000000
= 2000000000000000000000000000000
I need to use stacks to do this. This is what I have so far but I'm not sure where to go after this.
public static void main (String[] args)
{
Stack<BigInteger> stack = new Stack<BigInteger>();
System.out.println("Please write some pairs of numbers to add separated by a space: ");
Scanner input = new Scanner(System.in);
for (BigInteger number : input.nextLine().split(" "))
{
for (int i = 0; i < number.length(); i++)
{
stack.push(number);
}
while (!stack.isEmpty()) {
reverseInput += stack.pop();
}
}
}
You don't need inner for loop. If you are trying to add two numbers using stack, you can push them into Stack, pop and add to the result, e.g.:
Stack<BigInteger> stack = new Stack<BigInteger>();
System.out.println("Please write some pairs of numbers to add by a space: ");
Scanner input = new Scanner(System.in);
for (BigInteger number : input.nextLine().split(" "))
{
BigInteger result = new BigInteger("0");
while (!stack.isEmpty()) {
result.add(stack.pop());
}
System.put.println("Result : " + result);
First of all,
for (BigInteger number : input.nextLine().split(" "))
Isn't going to work, because that .split() returns an object of type String[], and you can't directly treat String asBigInteger.
Also, you're doubling up on your for loops. That line I copied above, if it worked the way you wanted, would loop through all of the numbers in your input. So there's no need for that inner for loop. In fact, it won't even compile, since BigInteger doesn't have a .length() method.
But you're on the right track. What you can do is tokenize the input like you're already doing, and push each element into a the stack as-is. Because there's no need to push them into the stack as BigInteger. You can have a Stack<String>, and then convert them into BigInteger when you pop them back off to do the addition. Or alternatively, convert them to BigInteger as you push each one onto the stack.
input.nextLine().split(" ");
returns a String[], you cannot automatically cast it to BigInteger[], as that will throw a ClassCastException.
Do you allow decimal values? If so, you'd be better off converting each String element to a primitive double representation, as you won't need the additional precision offered by BigDecimal.
As decimal values won't be allowed, you'd want to convert the String to its integer representation.
for (final String s : input.nextLine().split(" ")) {
final int value = Integer.parseInt(s);
stack.push(value);
}
The stack generic type will be Integer. So Stack<Integer>
Have you considered the case of bad user input? In that case you need to handle a NumberFormatException
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.
This question already has answers here:
Reverse a string in Java
(36 answers)
Closed 5 years ago.
I can't get my function to return the reversed string. I keep getting the original string, plus the reversed sting attached together.
P.S this is obviously a question from someone new. Cut me some slack and save me from the horribly demoralizing down vote.
int i;
reverse = reverse.replaceAll("[^a-zA-Z]+", "").toLowerCase();
for (i = reverse.length() - 1; i >= 0; i--) {
reverse = reverse + reverse.charAt(i);
}
return reverse;
}
You need another String (or some other method / memory) to build your return value (consider "a", starting from the end of the String add "a" - thus you get "aa"). Instead, I would use a StringBuilder - and the entire method might be written like
return new StringBuilder(reverse.replaceAll("[^a-zA-Z]+", "")
.toLowerCase()).reverse().toString();
Change the snippet to,
String reverse_string="";
for (i = reverse.length() - 1; i >= 0; i--) {
reverse_string += reverse.charAt(i);
}
return reverse_string;
You will need a separate String variable to contsruct the newly reversed string.
Why not just let the existing Java api do this for you?
String someString = "somestring123";
System.out.println(new StringBuilder(someString).reverse().toString());
output:
StringBuilder
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How can I convert a string
(1,234)
into a number
(1234)
using java?
Use DecimalFormat
DecimalFormat format = new DecimalFormat ("#,###");
Number aNumber = format.parse("1,234");
System.out.println(aNumber.intValue());
you can use NumberFormat for that
String number = "1,234";
NumberFormat numberFormat = NumberFormat.getInstance();
int i = numberFormat.parse(number).intValue();
Try String.repaceAll()
String value = "1,234";
System.out.println(Integer.parseInt(value.replaceAll(",", "")));
String is immutable, so when you do replaceAll, you need to reassign object to string reference,
String str = new String("1,234");
str = str.replaceAll(",", "");
System.out.println(Integer.parseInt(str));
This works fine when tested.
String str = new String("1,234");
String str1=str.replace(",", "");
Integer.parseInt(str1);
try with the above code
output
1234
If speed was a major concern you may find something like this quite fast. It beat all comers in this post.
int value(String s) {
// Start at zero so first * 10 has no effect.
int v = 0;
// Work from the end of the string backwards.
for ( int i = s.length() - 1; i >= 0; i-- ) {
char c = s.charAt(i);
// Ignore non-digits.
if ( Character.isDigit(c)) {
// Mul curent by 10 and add digit value.
v = (v * 10) + (c - '0');
}
}
return v;
}