Summing the ints in a string using scanner.chopper: java - java

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.

Related

How can I make this application properly convert these numbers and sum them?

I'm creating an application for my professor that takes several numbers entered from the user and sums them. I can't seem to figure out what I'm doing wrong. Any help will be appreciated. I tried different solutions, but I only got this far.
import java.util.*;
public class DebugSeven2
{
public static void main(String[] args)
{
String str;
int x;
int length;
int start;
int num;
int lastSpace = -1;
int sum = 0;
String partStr;
Scanner in = new Scanner(System.in);
System.out.print("Enter a series of integers separated by spaces >> ");
str = in.nextLine();
length = str.length();
for(x = 0; x <= length; ++x)
{
if(str.charAt(x) == ' ')
{
partStr = str.substring(lastSpace);
num = Integer.parseInt(partStr);
System.out.println(" " + num);
sum += num;
lastSpace = x;
}
}
partStr = str.substring(lastSpace + 1, length);
num = Integer.parseInt(partStr);
System.out.println(" " + num);
sum += num;
System.out.println(" -------------------" + "\nThe sum of the integers is " + sum);
}
}
First of all, this is homework and SO isn't a place where people do other's homework. That said, I'll help you with the high level overview of the solution and more didactic rather efficient solution.
Instead of spaggetti code, create several functions that do the several steps that you need to solve. This will produce a 'longer' code but it'll be easier to read and understand.
This implementation below is not the most efficient but you can read the code, starting by main() and understand what's being done line by line. If there's any issue you can debug and test each function separately and make sure it covers all you use-cases.
Also, this implementation contains several advanced topics such as java 8 streams, intStreams, splitting string using regex. Some basic error handling to skip whatever the user inputs if is not parseable to Integer.
And it's important to remember: it's better to write readable and maintainable code rather than high-performing obfuscated code. If you need to iterate a list twice but it'll make the code clear, do it. If you know the list might have +1K elements, optimise.
public class Exercise {
public String getUserInput() {
//Implementation is left to you.
return myString;
}
// https://stackoverflow.com/questions/7899525/how-to-split-a-string-by-space
private List<String> splitStringBySpace(String input) {
return Arrays.asList(input.split("\\s+"));
}
private List<Integer> convertListToIntegers(List<String> input) {
return input.stream().map(str -> {
try {
return Integer.parseInt(str);
} catch (NumberFormatException ex) {
//Skip whatever is not parseable as a number
return null;
}
}).filter(Objects::nonNull)
.collect(Collectors.toList());
}
private Integer sumList(List<Integer> input) {
/* Alternative solution
int acum = 0;
for (int i = 0; i < input.size(); i++) {
acum += input.get(i);
}
return acum;
*/
return input.stream().mapToInt(i -> i).sum();
}
public static void main() {
String inputText = getUserInput();
System.out.println("User has entered: " + inputText);
List<String> listOfNumbersAsString = splitStringBySpace(inputText);
List<Integer> listOfNumbers = convertListToIntegers(listOfNumbersAsString);
Integer myResult = sumList(listOfNumbers);
System.out.println("Total = " + myResult);
}
}

Finding the Sum of a String of numbers seperated by operators

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.

String Filtering .. Any one..Contains only either of the selected characters or both

I have a array from 0 to 10000.
problem
And i need to filter only the numbers containing either 3 or 4 or both and none other than that...
eg., 3,4,33,44,333,444,343,434,334
I tried the do while technique but I have made some mistake in the code..\
I'm not getting the output still..:(
the improved code is
import java.util.*;
import static java.lang.System.*;
public class numb {
public static void main(String[] args) {
int num,c,cum;
int i;
Scanner in = new Scanner(System.in);
out.println(3/10);
out.println("How many elements u need to put in this array?");
num=in.nextInt();
int[] ray1 = new int[num];
List<String> l1 = new LinkedList<String>();
for (c=0;c<num;c++)
{
ray1[c]=c;
}
for(i=1;i<num;i++)
{
boolean baabu=true;
do {
cum=ray1[i];
int lastdig = cum%10;
if(lastdig!=3||lastdig!=4)
{
baabu=false;
}
cum=cum/10;
}
while(cum>0&&baabu);
if(baabu)
{
String ad = String.valueOf(ray1[i]);
l1.add(ad);
}
}
printme(l1);
}
public static void print (int[] array)
{
for(int xc:array)
out.println(xc);
}
public static void printme (List<String> l1)
{
for(String yc:l1)
out.println(yc);
}
}
Check if the last digit is a 3 or a 4: if it is, divide the number by 10 and check the next digit; otherwise, discard the number.
boolean add = true;
do {
int lastDigit = num % 10;
if (lastDigit != 3 && lastDigit != 4) {
add = false;
}
num /= 10;
} while (add && num > 0);
if (add) {
// Add to list.
}
Think of the string as a list of characters, eg 3435 is 3,4,3,5 and 39 is 3,9. You need to iterate over the characters in the string and check that each one is a 3 or 4. Your code checks for specific combinations of 3 and 4 but cannot handle all possible enumerations.
Since you're treating the numbers as Strings already, the simplest way to find {3,4} strings is by matching the Regex "^[34]+$"
Pattern threeFourStrings = Pattern.compile("^[34]+$");
...
if (threeFourStrings.matcher(ad).matches()) {
l1.add(ad);
}
However, since you want all {3,4} strings up to 10000 (i.e. up to 4 digits), it would be far more efficient to construct them. You might start looking here: How to get all possible n-digit numbers that can be formed using given digits?
(Of course since you only have 2 digits, "3" and "4", it might be even more efficient to just list the binary numbers from 0 to 1111 and transpose "0" to "3" and "1" to "4".)
Use this method for every int in the array (it worked for me):
public static String myMethod(int num){
String str = String.valueOf(num);
String ns ="";
for (int i=0; i<str.length(); i++) {
if (str.substring(i, i+1).equals("3"))
{
ns += 3;
}
if (str.substring(i, i+1).equals("4"))
{
ns += 4;
}
}
return ns;
}

How to differentiate numbers and strings

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;
}

java program to return the sum of all integers found in the parameter String

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

Categories

Resources