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 8 years ago.
Improve this question
I am having issues when solving this problem:
Write a structures program that can accept two integer numbers up to 40 digit and perform the following:
add the two numbers together and display the result
the result number should should be seperated by commas.
So I was able to do number 1 using BigInteger, but for part 2 I am having issues. I don't know how I'm supposed to add a comma to a string, I was using a for loop to do with split but its not working.
I was able to figure it out thanks for all the help
public static String NewString (String num)
{
String sent = "" ;
int count = 0;
for ( int index = num.length()-1 ; index >= 0 ; index --)
{
count++;
sent = num.charAt(index) + sent;
if(count % 3 == 0 && index != 0)
sent = "," + sent;
}
return sent;
}
You can use
String formattedInteger = NumberFormat.getNumberInstance(Locale.US).format(bigInteger);
or you can write your own. It would be pretty simple, just convert your BigInteger to a String then loop through it backwards and every 3rd character you pass add a comma.
The code below -
Adds two numbers together and displays the result
The result number should be separated by commas.
Is quite self explanatory, Hope this helps :)
package stackoverflow;
import java.math.BigInteger;
/**
* Created by Nick on 11/13/14.
*
* Add two numbers together and display the result
* The result number should be separated by commas.
*/
public class SO_26916958 {
private static BigInteger arg1;
private static BigInteger arg2;
public static void main(String[] args) {
arg1 = new BigInteger (args[0].getBytes());
arg2 = new BigInteger (args[1].getBytes());
BigInteger sum = arg1.add(arg2);
String bigIntegerString = sum.toString();
String output = recursivelyAddComma(bigIntegerString);
System.out.print(bigIntegerString +"\n");
System.out.print(output);
}
private static String recursivelyAddComma (String s) {
int length = s.length();
StringBuilder output = null;
if(length <= 3) {
return s.toString();
}
return recursivelyAddComma(s.substring(0, length - 3)).concat(",").concat(s.substring(length - 3, length));
}
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
How can i seperate this String:
"thisisanexampleforthisproblemicantsolvetestes"
To this array:
{"thisi","sanex","ampl","efor","this","prob","lemi","cant","solv","etes","tes"}
I want to seperate the first 10 letters in the String into 2 elemnts in an array and the rest should be every 4 letters, to one elemnt in an array.
I hope you can help me. I tried this all day but still didnt solve it
Assuming your input string length >= 10 you can do something like below using streams:
String str = "thisisanexampleforthisproblemicantsolvetestes";
String[] splited = Stream.of(str.substring(0, 10).split("(?<=\\G.{5})"),
str.substring(10).split("(?<=\\G.{4})"))
.flatMap(e -> Arrays.stream(e))
.toArray(String[]::new);
System.out.println(Arrays.toString(splited));
where the regex "(?<=\\G.{n})" is used to split a string at each nth char
More simple to understand:
Results in: thisi, sanex, ampl, efor, this, prob, lemi, cant, solv, etes, tes
public static List<String> strangeThingsDo(String str)
{
List<String> li = new ArrayList<>();
int len = str.length();
if (len <= 5)
{
li.add(str);
return li;
}
if (len <= 10)
{
li.add(str.substring(0,5));
li.add(str.substring(5));
return li;
}
li.add(str.substring(0,5));
li.add(str.substring(5,10));
String s,rest = str.substring(10);
int restlen = rest.length();
int end = 0;
for (int i = 0; i < restlen;i += 4)
{
end = i + 4;
if (end > restlen)
{ s = rest.substring(i);
li.add(s);
break;
}
s = rest.substring(i,end);
li.add(s);
}
System.out.println("---: " + li );
return li;
}
The following code will show you how to split a string by numbers of characters. We create a method called splitToNChars() that takes two arguments. The first arguments is the string to be split and the second arguments is the split size.
This splitToNChars() method will split the string in a for loop. First we’ll create a List object that will store parts of the split string. Next we do a loop and get the substring for the defined size from the text and store it into the List. After the entire string is read we convert the List object into an array of String by using the List‘s toArray() method.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SplitStringForEveryNChar {
public static void main(String[] args) {
String text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println(Arrays.toString(splitToNChar(text, 3)));
System.out.println(Arrays.toString(splitToNChar(text, 4)));
System.out.println(Arrays.toString(splitToNChar(text, 5)));
}
private static String[] splitToNChar(String text, int size) {
List<String> parts = new ArrayList<>();
int length = text.length();
for (int i = 0; i < length; i += size) {
parts.add(text.substring(i, Math.min(length, i + size)));
}
return parts.toArray(new String[0]);
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm really new to java and just learning. I'm doing a java assignment and I don't quite understand; I am supposed to create a method that will take in a String array and return a randomly selected Sting from that array. here are the exact instructions:
*getRandomWord --> consumes an array of Strings and selects
(returns) one of the words at random.
signature: String getRandomWord (String [] array)
*
Then I think I have to create another method. I doubt an you have two methods named the same thing but the instructions say:*getRandomWord --> consumes an array of Strings and an integer (len).
This method selects a word from the array whose
length is more than len. If the length of the word
selected is less than len, then this method selects
another word at random. This is repeated 500 times
until a word is found/returned or no word is found
in which case this method will return null.
signature: String getRandomWord (String [] array, int len)
*
As I said I'm really new so help is appreciated.
Since this is an assignment I will only give you pointers to write the method yourself. The algorithm to use in String getRandomWord (String [] array)is elucidated below:
Calculate the length of the array. See How to find length of a string array
Generate the index of the random word from the array's length. See Getting random numbers in java
Get and return the random word from the array.
All these should be done in not more than 3 lines of code. Good Luck!
I would suggest to do it yourself. If you don't get, code is here :) Use the Random API. nextInt() method of Random method gives the Random value, which can be used as index to return random String from Arra.
Below is complete code of 2 methods:
import java.util.Random;
public class TestJava {
public static void main(String[] args) {
String[] strArray = { "first", "second", "third" };
System.out.println(getRandomWord(strArray));
}
static String getRandomWord(String[] array) {
Random random = new Random();
int index = random.nextInt(array.length);
return array[index];
}
static String getRandomWordWithLength(String[] array, int len) {
Random random = new Random();
for (int i = 0; i < 500; i++) {
int index = random.nextInt(3);
String selectedString = array[index];
if (selectedString.length() > len)
return selectedString;
}
return null;
}
}
Try to do yourself at first as it is an assignment. Take help from the code below if you failed it to do yourself.
private String getRandomWord(String[] array) {
int idx = new Random().nextInt(array.length);
return (array[idx]);
}
private String getRandomWord(String[] array, int len) {
String word = null;
for (int i = 1; i <= 500; i++) {
word = getRandomWord(array);
if (word.length() > len) {
break;
} else {
word = null;
}
}
return word;
}
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 7 years ago.
Improve this question
I have a class like below
public class EXOR{
public static void conv(){
String [] Parray={"243f6a88","85a308d3","13198a2e","03707344","a4093822","299f31d0","082efa98",
"ec4e6c89","452821e6", "38d01377", "be5466cf","34e90c6c","c0ac29b7","c97c50dd","3f84d5b5","b5470917","9216d5d9","8979fb1b"};
String binAddr[]=new String[18];
for (int i=0;i<18;i++)
{
int x[]=new int[18];
binAddr[i]= Integer.toBinaryString(Integer.parseInt(Parray[i],16));
System.out.println("binernya : " +binAddr[i]);
}
}
public static void main(String[] args){
new EXOR().conv();
}
}
and I want to convert that array to binary array format.
I want to get output like below
for example
00100100001111110110101010001000
10000111101000110000100011010011
................................
How to fix this problem?
I suppose while executing your code you must've got a number point exception. This occurs when the Hexadecimal string is out of the range of Integer.
You can use:
binAddr[i]= (new BigInteger(Parray[i],16)).toString(2);
instead of
binAddr[i]= Integer.toBinaryString(Integer.parseInt(Parray[i],16));
This will solve your problem for quick reference
Big Integer Documentation
Code:
public class EXOR {
public static void conv(){
String [] Parray={"243f6a88","85a308d3","13198a2e","03707344","a4093822","299f31d0","082efa98",
"ec4e6c89","452821e6", "38d01377", "be5466cf","34e90c6c","c0ac29b7","c97c50dd","3f84d5b5","b5470917","9216d5d9","8979fb1b"};
String [] binAddr = new String[Parray.length];
for (int i = 0; i < binAddr.length; i++)
{
int strLen = Parray[i].length();
binAddr[i] = "";
for(int j = 0; j < strLen; j++) {
String temp = Integer.toBinaryString(
Integer.parseInt(String.valueOf(
Parray[i].charAt(j)), 16));
// Pad with leading zeroes
for(int k = 0; k < (4 - temp.length()); k++) {
binAddr[i] += "0";
}
binAddr[i] += temp;
}
System.out.println("Original: " + Parray[i]);
System.out.println("Binary: " + binAddr[i]);
}
}
public static void main(String[] args){
conv();
}
}
First few lines of Output:
Original: 243f6a88
Binary: 00100100001111110110101010001000
Original: 85a308d3
Binary: 10000101101000110000100011010011
We have Integer.MAX_VALUE = 2147483647
But, the 2nd item "85A308D3" = 2242054355. It exceed the capability of an Integer.
So, you use Integer.parseInt(85A308D3) will cause java.lang.NumberFormatException.
To fix it, change your code to use Long instead of Integer
binAddr[i] = Long.toBinaryString(Long.parseLong(Parray[i], 16));
Hope this help!
This question already has answers here:
Splitting String to list of Integers with comma and "-"
(4 answers)
Closed 8 years ago.
The following code I have spent several hours on using multiple different strategies for extracting the integer values from the String st and getting them into their own int variables.
This is a test program, the actual assignment that I am working on requires me to build a class that will make another program ( program5 ) run correctly. The string generated by program5 could contain more than just three integers, but all will be seperated by a space. Because of the specifics of the assignment I am not allowed to use arrays, or regex because we have not covered them in class.
As of right now I can't even get it to print out all of the three integers I have in my test string. If anyone sees anything wrong with my syntax or problems with my logic please let me know!
public class test {
public static void main(String[] args){
String st = "10 9 8 7 6";
int score;
int indexCheck = 0;
String subSt;
for(int i=0; i <= st.length(); i++)
{
if(st.indexOf(' ') != -1)
{
if(st.charAt(i) == ' ')
{
subSt = st.substring(indexCheck, i);
score = Integer.parseInt(subSt);
indexCheck = st.indexOf(i);
System.out.println(score);
}
}
else
{
subSt = st.substring(st.lastIndexOf(" "));
score = Integer.parseInt(subSt);
System.out.println(score);
}
}
}
}
Use st.split(" ") to get a String[] that stores the string split by spaces, and then use Integer.parseInt(array[0]) on each index to to convert it to an int.
Example
String str = "123 456 789";
String[] numbers = str.split(" ");
int[] ints = new int[numbers.length];
for(int c = 0; c < numbers.length; c++) ints[c] = Integer.parseInt(numbers[c]);
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
Given a directory name as a string like so:
c:\can\be\anything\...\2013\12\01
or without the 'day' like so:
c:\can\be\anything\...\2011\10
How can I easily parse out the year, month, and day into integers:
int iYear;
int iMonth;
int iDay;
Any suggestions are greatly appreciated!
rh
Based on Java 1.7 API:
String dir1 = "c:\\test1\\2013\\12\\01"; // c:\test1\2013\12\01
String dir2 = "c:\\test1\\2013\\10"; // c:\test1\2013\10
public void getDate(String dir) {
String parts[] = (java.io.File.separatorChar == '\\' ? dir.split("\\\\") : dir.split("/"));
int len = parts.length();
if (len >= 3) {
int iYear, iMonth, iDay;
if (parts[len-2].length() == 4) {
iYear = Integer.parseInt(parts[len-2]);
iMonth = Integer.parseInt(parts[len-1]);
iDay = 0;
} else {
iYear = Integer.parseInt(parts[len-3]);
iMonth = Integer.parseInt(parts[len-2]);
iDay = Integer.parseInt(parts[len-1]);
}
}
}
Notes:
Split method of String requires a string of regular expression. Since the elements of directory's name is separated by backslash (\) then you have to use string's escaped character (\\), plus regular expression's escaped character (\\\\).
Line 4 will retrieve OS's path separator: \ in Windows, / in *nix.
Line 7 will check whether the date is in first or second form.
I'd split the string by '\', take the last three, and assign the values.
import java.lang.Number;
import java.lang.String;
import java.lang.StringBuffer;
import java.util.Iterator;
public class Test{
private static String path = "c:\\can\\be\\anything\\...\\2013\\12\\01";
public static void main(String[] args){
String[] tmp = path.split("\\\\");
if(tmp.length > 3){
String day = tmp[tmp.length-1];
String month = tmp[tmp.length-2];
String year = tmp[tmp.length-3];
System.out.println(day+" "+month+" "+year);
}
}
}
Try this.
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub>
String test = new String("c:\\can\\be\\anything\\test\\2013\\12\\01");
System.out.println("test "+test);
String[] result = test.split("\\\\");
for(String s : result){
System.out.println(">"+s+"<");
}
}
}
Probably the easiest thing would be to use split("\") then get the strings back as an array and throw out the first n elements until you get to the one with the year.
String[] elements = requestUrl.split("\");
int yearIndex;
int monthIndex = yearIndex + 1;
int dayIndex = monthIndex + 1;
for (int i = 0; i < elements.length; i++){
int value = Integer.parseInt(element);
if (value > 1900){
yearOffset = i;
break;
}
}
int year = Integer.parseInt(elements[yearIndex]);
int month = Integer.parseInt(elements[monthIndex]);
int day = Integer.parseInt(elements[dayIndex]);
If you know how many elements there will be before the year, you don't have to scan.