This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 4 years ago.
Examples of the String
131-5923-213
1421-41-4-12-4
1-1
How would I extract the integers into an Array or find the sum of these integers? My code so far goes
int hyphenCount = socialNum.length()-socialNum.replaceAll("-", "").length();
ArrayList<Integer> sum = new ArrayList<Integer>();
for(int i = 0; i < hyphenCount; i++)
{
//my brain is too small
}
What I want to do is make a function like the following
public void extractSum(String s)
{
int outputSum;
//stuff
return outputSum;
}
Using Streams you can do:
int sum = Arrays.stream(str.replace("-", "").split("")).mapToInt(Integer::valueOf).sum();
Which will replace the hyphen and then split each character, parse the integer, and return the sum
Output: (For the String "131-5923-213")
30
If you want the sum of 131 + 5923 + 213 you could do:
int sum = Arrays.stream(str.split("-")).mapToInt(Integer::valueOf).sum();
Which will split on a hyphen, parse the integers, and return the sum
Apart from #GBlodgett's answer using stream, you could simply run a for loop to calculate the sum.
String string = "131-5923-213";
String[] num = string.split("-"); //<----num[0] = "131" ,num[1]="5923",num[2] = "213"
int hyphenCount = num.length; //<----it would give you 3 as length
int mySum = 0; //initialize the sum as 0
for(int i = 0; i < hyphenCount; i++)
{
mySum+= Integer.parseInt(num[i]); //<---convert the string to an int
}
Output: 6267
Related
Sudoku with Java Arrays
I am building a 9x9 2D array and trying to fill it by inputting a random 9 digits integer for each row. I want to insert each digit of that number as an element along the rows [0][0-8],[1][0-8]... I tried to convert the integer into a string and insert each character but I can't seem to figure it out.
System.out.println("Please insert 9 lines of 9 digits (1-9)");
int Choise = scan.nextInt();
char c =(char)Choise;
int soduko[][] = new int[9][9];
for (int i = 0; i< soduko.length; i++){
for(int j =0; j< soduko.length; j++){
soduko[i][j]=c;
}
}
i have tried another way that still uses the number as an int, by taking the remainder of that number to the last cell in the row, and dividing the number by 10 each time in the loop. although its not working when i try to divide by 10 to get the next remainder.
System.out.println("Please insert 9 lines of 9 digits (1-9)");
Choise = scan.nextInt();
for (int i =0; i <= soduko.length -1; i++){
for(int j = soduko.length -1; j > 0; j--){
int ChoiseDigit = Choise % 10;
soduko[0][j] = ChoiseDigit;
Choise = (int)(Choise / 10);
}
}
Building on your string conversion idea, you might benefit from using the split() method, which splits up a string based on a string you pass as an argument, and then returns an array of the split-up strings. So when you do split(""), the string is split up into single characters. Then you can parseInt to turn each string into an int. I would also recommend putting the scanner input in the loop, to make sure the user has to input a string 9 times.
System.out.println("Please insert 9 lines of 9 digits (1-9)");
int soduko[][] = new int[9][9];
for (int i = 0; i< soduko.length; i++){
//reading a string of input 9 times and splitting them by "" into 1-character strings
String Choise[] = scan.nextLine().split("");
for(int j =0; j< soduko[i].length; j++){
//Integer.parseInt converts each string to an int so we can save it to the 2d array
soduko[i][j]= Integer.parseInt(Choise[j]);
}
}
I need to write a program that calculates a moving average by a user inputted array. The first element of the array is the window size, and the input is terminated by a 0. The output values are printed with two digits after the decimal point.
Example input: 3 2 4 7 7 8 11 12 0
Corresponding Output: 4.33 6.00 7.33 8.67 10.33
(4.33 is average of 2,4,7 and 6 is average of 4,7,7 etc.)
Here's my code so far:
package movingaverage;
import java.util.Scanner;
public class MovingAverage {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
avg[0] = sum / 5;
int j = 1;
for (int i = 5; i < arr.length; i++) {
sum = sum + arr[i] - arr[i - 5];
avg[j++] = sum / 5;
}
}
}
I think I have the loop right, but I'm not sure how to get the array to end at 0.
This is a possible solution.
public class Test
{
private static final Scanner SCANNER;
static {
SCANNER = new Scanner(System.in);
}
public static final void main(final String... args) {
final String[] numbers = SCANNER.nextLine().trim().split(" ");
final int consideredElements = Integer.parseInt(numbers[0]);
float sum = 0;
int value = 0;
for (int i = 1; i < numbers.length; i++) {
sum = 0;
for (int k = 0; k < consideredElements; k++) {
value = Integer.parseInt(numbers[i + k]);
if (value == 0) {
return;
}
sum += value;
}
System.out.println(new BigDecimal(sum / consideredElements).setScale(2, RoundingMode.HALF_EVEN));
}
}
}
First, you are using 5 in a couple of places in your program, I see no justification for that. Could it be that your expectation of user input lead you to put 5 where the number you really should use, depends on user input? Maybe you should use the window size instead? I’m guessing a bit here.
Next, as #lppEdd pointed out, you are not reading the numbers from your input — only the window size.
Next, you are declaring your array of size n, which I believe was your window size, not your array size. I believe the real solution to this problem is using better and more explanatory variable names.
Your code does not compile since you have not declared the array avg that you try to store your moving average into.
Fifth, when you want your average as a double, you need to convert to double before dividing (this is a classic pitfall that has already generated many questions on Stack Overflow).
I hope this gets you a couple of steps further.
This question already has answers here:
split int value into separate digits
(8 answers)
Closed 6 years ago.
So I have a String array that has a number like "1234567898765" and I want to convert it to an int and assign each number to each index of an array of integers.
For example, array[i]= "1234567898765" and I want to do arrayOfIntegers[0] = 1 , arrayOfIntegers[1] = 2, arrayOfIntegers[2] = 3, ect... How can I do that?
public class StringTest {
public static void main(String args[])
{
String input = "123456789765";
int [] arrayOfInts = new int [input.length() ];
for (int i = 0; i < input.length(); i++ ) {
arrayOfInts[i] = Character.getNumericValue(input.charAt(i));
}
}
}
This question already has answers here:
Finding numbers in a text and summing them
(2 answers)
Closed 6 years ago.
I want to get the sum of all numbers from a JTextField. I'am using this code but it doesn't work. The problem is that is that I can't get the {d1} as numbers from the JTextField.
String a = jTextField1.getText();
int d1= Integer.parseInt(a);
int Arry[] = {d1};
int sum = 0;
for ( int i = 0; i<Arry.length; i++ )
{
sum=sum + Arry[i];
}
jTextField2.setText(sum+"");
If jTextField1 contains not only numbers, you may want to extract all the digits like this:
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(jTextField1.getText());
List<Integer> numbers = new ArrayList<>();
while (m.find()) {
numbers.add(Integer.parseInt(m.group()));
}
then sum the numbers:
int sum = 0;
for (Integer number : numbers)
sum += number;
If you can guarantee that the JTextField will only contain input that can be parsed into ints, e.g. no letters or symbols, then the only possible remaining issue is whitespace between your numbers. I would suggest that you go to the Pattern API and look for characters that can detect whitespace and then go to String API and find a method that can split a String based on an input regular expression (regex). Then from there you can easily parse the split String into ints and get your sum. For example:
String a = jTextFieldName.getText();
String[] storage = a.someSplittingMethod("whitespace regex");
int sum = 0;
for(int c = 0; c < storage.length; c++)
sum += Integer.parseInt(storage[c]);
This question already has answers here:
How to concatenate int values in java?
(22 answers)
Closed 7 years ago.
After finding the individual digits of a number by remainder procedure, the numbers are saved in an array.
What I want now is to take the individual elements of this array and make a single integer value of it.
eg.
int a = 4400
digits saved in array by using recursion (4400/10) :
let array be arr[]
arr[0]=0;
arr[1]=0;
arr[2]=4;
arr[3]=4;
final value:
int b= 4400 (by combining elements of array)
So I want to know if there is any way to combine the array elements to a single integer value ?
Just multiply and add the digits:
int result = 1000 * arr[3] + 100 * arr[2] + 10 * arr[1] + arr[0];
Or, if you need it to work for any length of array (up to the number of digits in Integer.MAX_VALUE):
int result = 0;
for (int i = arr.length - 1; i >= 0; --i) {
result = 10*result + arr[i];
}
I would use a stringbuilder.
StringBuilder builder = new StringBuilder();
builder.append(arr[3]);
builder.append(arr[2]);
builder.append(arr[1]);
builder.append(arr[0]);
System.out.println("Combined value is: " + Integer.parseInt(builder.toString());
How about using simple loop and multiplication (assuming you know basic math)
int b = 0;
int z = 10;
for (int i = 1; i <= arr.length; i++) {
b = (int) (b + (arr[i - 1] * Math.pow((double) z, i - 1)));
}