I want to split the amount value from a string I got from txt file, the problem is the split value is string and even after parsing it to integer I can't accumulate the summation of it.
Here is the main method:
public static void main(String[] args) throws IOException {
String file_name = "C:\\application\\TestFile2.txt";
try {
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();
int i;
for (i=0;i<aryLines.length;i++)
{
//System.out.println(aryLines[i]);
//////split each line to get the total amount
String[] parts = aryLines[i].split("\\|");
String amount = parts[5];
System.out.println(amount);
}
/////count total number of lines
System.out.println(file.readLines());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
Why are you doing num = num ++?
You should keep sum = 0 outside and sum += num in the loop;
Finally println(sum)
Your question is not clear to me. Can you please give an example of the String you want to split and what summation you want after splitting ?
Ok u can do something like this -
List<Integer> amt=new ArrayList<Integer>();
for(int i=0;i<aryLines.length;i++){
String arr[]=aryLines[i].split("\\|");
amt.add(Integer.parseInt(arr[5])); //assuming 6th position contains the amount.
}
Object amtArr[]=amt.toArray();
int sum=0;
for(int j=0;j<amtArr.length;j++){
sum=sum+(Integer)amtArr[j];
}
System.out.println("Sum is: "+sum);
Related
I have this code that prints out the max value of each row I have. But I am having trouble also printing out the row number for each output.I tried using i to add 1 to each row. Obviously this does not work with it, just wanted to show my attempt. Without the i the code works fine for finding the max value of my string from a text file. If there is another way to change my row number for each output it would be much appreciated. For example,
Row 1: 5
Row 2: 67
row 3: 43
is what i want. All i have been able to get is:
Row 1: 5
Row 1: 67
row 1: 43
My java code
import java.util.Scanner;
public class maxValue {
public static void main(String[] args) throws Exception {
int i=0;i<3;i++;
String fileName="C:\\Users\\Michael\\Documents\\input.csv";
File f = new File(fileName);
Scanner fileScan= new Scanner(f);
while(fileScan.hasNext()) {
String line=fileScan.nextLine();
System.out.println("ROW " + i + ": " + (extractMaximum(line)));
}
fileScan.close();
}
static int extractMaximum(String str) {
int num = 0;
int res = 0;
// Start traversing the given string
for (int i = 0; i<str.length(); i++) {
// If a numeric value comes, start converting
// it into an integer till there are consecutive
// numeric digits
if (Character.isDigit(str.charAt(i)))
num = num * 10 + (str.charAt(i)-'0');
// Update maximum value
else {
res = Math.max(res, num);
// Reset the number
num = 0;
}
}
// Return maximum value
return Math.max(res, num);
}
}
You need to increment i in the loop:
public static void main(String[] args) throws Exception
{
String fileName="C:\\Users\\Michael\\Documents\\input.csv";
File f = new File(fileName);
Scanner fileScan = new Scanner(f);
// One option: a for loop
for (int i = 1; fileScan.hasNext(); i++) {
String line = fileScan.nextLine();
// I prefer printf
System.out.printf("ROW %d: %d%n", i, extractMaximum(line));
}
fileScan.close();
}
// Re-written to use streams
// Even if you don't want to use stream,
// Using the regex to split the string is an improvement
static int extractMaximum(String str)
{
return Arrays.stream(str.split("\\D+"))
.map(x -> Integer.parseInt(x))
.max(Integer::compare)
.get();
}
Given String = "128+16+8+2+1"
Answer should print out 155
The code is supposed to add all numbers in the string and the answer should be printed out as a string.
I attempted to write the code for this, however the last 2 numbers will not add and my current answer is printing out 153. Looking for help to lead me to the correct solution.
import java.util.stream.*;
public class add {
static void evalA(String s) {
int n = countChar(s,'+');
System.out.println(s);
int cnt = 0;
int[] data = new int[n];
for(int i=0;i<s.length();i++) {
if (s.charAt(i)=='+') {
System.out.println(s.substring(0,i));
data [cnt] = Integer.parseInt(s.substring(0,i));
cnt++;
s = s.substring(i+1,s.length()-1);
i=0;
}
}
String sum = ""+IntStream.of(data).sum();
System.out.println(sum);
}
}
You could do something like this:
public static void main(String[] args)
{
evaluate("128+16+8+2+1");
}
public static void evaluate(String equation)
{
String[] numbers = equation.split("\\+");
int sum = 0;
for (String number : numbers)
{
//could wrap this in a check incase of exception or errors
sum += Integer.parseInt(number);
}
System.out.println(sum);
}
It just splits the string up by the + to get the individual numbers as an array and then loop through the array and add each numbers value to a sum variable.
I have a string
String s="Raymond scored 2 centuries at an average of 34 in 3 innings.";
I need to find the sum of only numbers present in the string without encountering any exceptions. Here the sum should be 2+34+3=39. How to make the compiler understand the differences between String and Integer.
You should split input string by spaces (or by regex, it's unclear from your question) to the array of String tokens, then iterate through this array. If Integer.parseInt(token) call doesn't produce the NumberFormatException exception then it returns an integer, which you should add to the numbers list for further processing (or add to the sum right away)
String inputString = "Raymond scored 2 centuries at an average of 34 in 3 innings.";
String[] stringArray = inputString.split(" ");//may change to any other splitter regex
List<Integer> numbers = new ArrayList<>();
for (String str : sArr) {
try {
numbers.add(Integer.parseInt(str)); //or may add to the sum of integers here
} catch (NumberFormatException e){
System.out.println(e);
}
}
//todo any logic you want with the list of integers
You should split the string using a regex expression. The split will be made between all non digits characters. Here is a sample code:
String text = "there are 3 ways 2 win 5 games";
String[] numbers = text.split("\\D+");
int sum = 0;
for (String number : numbers) {
try {
sum += Integer.parseInt(number);
} catch (Exception ex) {
//not an integer number
}
}
System.out.println(sum);
public void sumOfExtractedNumbersFromString(){
int sum=0;
String value="hjhhjhhj11111 2ssasasa32sas6767676776767saa4sasas";
String[] num = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0" };
for(char c : value.toCharArray())
{
for (int j = 0; j < num.length; j++) {
String val=Character.toString(c);
if (val.equals(num[j])) {
sum=sum+Integer.parseInt(val);
}
}
}
System.out.println("Sum"+sum);`
}
public class MyClass {
public int addition(String str){
String[] splitString = str.split(" ");
// The output of the obove line is given below but now if this string contain
//'centuries12' then we need to split the integer from array of string.
//[Raymond, scored, 2, centuries12, at, an, average, of, 34, in, 3, innings]
String[] splitNumberFromSplitString= str.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
// The output of above line is given below this regular exp split the integer
// number from String like 'centuries12'
// [Raymond scored,2,centuries,12, at an average of,34, in , 3, innings]
int sum=0;
for (String number : splitNumberFromSplitString) {
if(StringUtils.isNumeric(number)){
sum += Integer.parseInt(number);
}
}
return sum;
}
public static void main(String args[]) {
String str = "Raymond scored 2 centuries at an average of 34 in 3 innings";
MyClass obj = new MyClass();
int result = obj.addition(str);
System.out.println("Addition of Numbers is:"+ result);
}
}
Output :
Addition of Numbers is:39
Well there are multiple ways on how to solve your problem. I assume that you are only looking for integers (otherwise each of the solutions may be adaptable to also look for floating numbers).
Using regular expressions:
public static int sumByRegEx(final String input) {
final Pattern nrPattern = Pattern.compile("\\d+");
final Matcher m = nrPattern.matcher(input);
int sum = 0;
while (m.find()) {
sum += Integer.valueOf(m.group(0));
}
return sum;
}
Using a Scanner:
public static int sumByScanner(final String input) {
final Scanner scanner = new Scanner(input);
int sum = 0;
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
sum += scanner.nextInt();
} else {
scanner.next();
}
}
scanner.close();
return sum;
}
Using String methods:
public static int sumByString(final String input) {
return Stream.of(input.split("\\s+"))
.mapToInt(s -> {
try {
return Integer.valueOf(s);
} catch (final NumberFormatException e) {
return 0;
}
}).sum();
}
All cases return the correct results (as long as null is not passed):
public static void main(final String[] args) {
final String sample = "Raymond scored 2 centuries at an average of 34 in 3 innings.";
// get some 39:
System.out.println(sumByRegEx(sample));
System.out.println(sumByScanner(sample));
System.out.println(sumByString(sample));
// get some 0:
System.out.println(sumByRegEx(""));
System.out.println(sumByScanner(""));
System.out.println(sumByString(""));
// some "bad" examples, RegEx => 10, Scanner => 0, String => 0
System.out.println(sumByRegEx("The soccer team is playing a 4-3-3 formation."));
System.out.println(sumByScanner("The soccer team is playing a 4-3-3 formation."));
System.out.println(sumByString("The soccer team is playing a 4-3-3 formation."));
}
i think you should write a different function to check either it is a number or not for good as good practices:
public class SumOfIntegersInString {
public static void main(String[] args) throws ClassNotFoundException {
String s = "Raymond scored 2 centuries at an average of 34 in 3 innings.";
String[] splits= s.split(" ");
System.out.println(splits.length);
int sum = 0;
for (int j=0;j<splits.length;j++){
if (isNumber(splits[j]) == true){
int number = Integer.parseInt(splits[j]);
sum = sum+number;
};
};
System.out.println(sum);
};
public static boolean isNumber(String string) {
try {
Integer.parseInt(string);
} catch (Exception e) {
return false;
}
return true;
}
}
No fancy tricks: check if each character is a digit and if so parse/add it.
public static void SumString (string s)
{
int sum = 0, length = s.length();
for (int i = 0; i < length; i++)
{
char c = s.charAt(i);
if (Character.isDigit(c))
sum += Integer.parseInt(c);
}
return sum;
}
first post on this site, so, I essentially have to find a way to chop up the ints in a string, divided only by spaces, (example would be ("9 10 5 20 1 2 3") and then find the sum of all of the chopped up ints. I know i have to use chopper.nextInt(), but I am not sure how to format the totality of the code, along with summing the output after. Thanks so much!
import static java.lang.System.*;
import java.util.Scanner;
public class LineTotaller
{
private String line;
public LineTotaller()
{
setLine("");
}
public LineTotaller(String s)
{setLine(s);
}
public void setLine(String s)
{line = s;
}
public int getSum()
{
int sum = 0;
Scanner chopper = new Scanner(line);
while(chopper.hasNextInt())
{
out.print(chopper.nextInt());
sum+= //returned ints from above
}
}
public String getLine()
{
return "";
}
public String toString()
{
return getLine();
}
}
I think you want to do the following
public int getSum()
{
int sum = 0;
Scanner chopper = new Scanner(line);
while(chopper.hasNextInt())
{
int nextInt = chopper.nextInt();
System.out.print(nextInt);
sum += nextInt;
}
return sum;
}
You can only call nextInt once after you confirmed that there is something via hasNextInt. If you want to print it and add it to the sum, you have to store the value temporarily in a variable.
Consider using the string.split() method to place you numbers string into a string array then iterate through the array with a 'for loop', convert each element to a integer ( Integer.valueOf() )and maintain a ongoing total with each iteration.
Something like:
String yourString = "9 10 5 20 1 2 3";
String[] myNumbers = yourString.split(" ");
int total = 0;
for (int i = 0; i < myNumbers.length; i++) {
total+= Integer.valueOf(myNumbers[i]);
}
System.out.println("Total is: -> " + total);
That should get it done for you.
i want write a java program to return the sum of all integers found in the parameter String.
for example take a string like:" 12 hi when 8 and 9"
now the answer is 12+8+9=29.
but i really dont know even how to start can any one help in this!
You may start with replacing all non-numbers from the string with space, and spilt it based on the space
String str = "12 hi when 8 and 9";
str=str.replaceAll("[\\D]+"," ");
String[] numbers=str.split(" ");
int sum = 0;
for(int i=0;i<numbers.length;i++){
try{
sum+=Integer.parseInt(numbers[i]);
}
catch( Exception e ) {
//Just in case, the element in the array is not parse-able into Integer, Ignore it
}
}
System.out.println("The sum is:"+sum);
You shall use Scanner to read your string
Scanner s = new Scanner(your string);
And then read it using
s.nextInt();
Then add these integers.
Here is the general algorithm:
Initialize your sum to zero.
Split the string by spaces, and for each token:
Try to convert the token into an integer.
If no exception is thrown, then add the integer to your sum.
And here is a coding example:
int sumString(String input)
{
int output = 0;
for (String token : input.split(" "))
{
try
{
output += Integer.parseInt(token);
}
catch (Exception error)
{
}
}
return output;
}
private static int getSumOfIntegersInString(String string) {
/*Split the String*/
String[] stringArray = string.split(" ");
int sum=0;
int temp=0;
for(int i=0;i<stringArray.length;i++){
try{
/*Convert the numbers in string to int*/
temp = Integer.parseInt(stringArray[i]);
sum += temp;
}catch(Exception e){
/*ignore*/
}
}
return sum;
}
You could use a regular expression
Pattern p = Pattern.compile("\\d+");
String s = " 12 hi when 8 and 9" ;
Matcher m = p.matcher(s);
int start = 0;
int sum=0;
while(m.find(start)) {
String n = m.group();
sum += Integer.parseInt(n);
start = m.end();
}
System.out.println(sum);
This approach does not require the items to be separated by spaces so it would work with "12hiwhen8and9".
Assume your words are separated by whitespace(s):
Then split your input string into "tokens"(continuous characters without whitespace).
And then loop them, try to convert each of them into integer, if exception thrown, means this token doesn't represents a integer.
Code:
public static int summary(String s) {
String[] tokens = s.split("\\s+");
int sum = 0;
for(String token : tokens) {
try {
int val = Integer.parseInt(token);
sum += val;
}
catch(NumberFormatException ne){
// Do nothing
}
}
return sum;
}
String s ="12 hi when 8 and 9";
s=s.replaceAll("[^0-9]+", " ");
String[] numbersArray= s.split(" ");
Integer sum = 0;
for(int i = 0 ; i<numbersArray.length;i++){
if(numbersArray[i].trim().length() != 0){
Integer value = Integer.valueOf(numbersArray[i].trim());
sum = sum + value;
}
}
System.out.println(sum);
You can have a look on the following code :-
public class Class02
{
public static void main(String[] args)
{
String str = "12 hi when 8 and 9";
int sum = 0;
List<String> list = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(str.toLowerCase());
while(st.hasMoreElements())
{
list.add(st.nextToken());
}
for(int i =0; i< list.size();i++)
{
char [] array = list.get(i).toCharArray();
int num = array[0];
if(!(num >= 'a' && num <= 'z'))
{
int number = Integer.valueOf((list.get(i).toString()));
sum = sum + number;
}
}
System.out.println(sum);
}
}
Hope it will help you.
I understand that this does not have the Java8 tag but I will put this out there in case someone finds it interesting
String str = "12 hi when 8 and 9";
System.out.println(Arrays.stream(str.split(" "))
.filter(s -> s.matches("[0-9]+")).mapToInt(Integer::parseInt).sum());
would nicely print out 29