In an interview they asked me this question.There is a string like "12 computer 5 7". You need to add integers within that string and answer should be 24.How can i solve this can anyone help me please.
string s="12 computer 5 7"
output should be:24
Can i use sub-string or some other process to solve it
Try this,
String input = "12 computer 5 7";
String[] splittedValue = input.split(" "); // splitted the values by space
int result = 0;
for (String s : splittedValue)
{
if (s.matches("\\d+")) // check while the input is number or not
{
result = result + Integer.parseInt(s); // parse it and add it to the count
}
}
System.out.println("Result : "+result);
Use split("[ ]") to convert the string into an array of strings separated by space and then add the integers present in each position of the array. Add it to sum if it is an integer like :-
String ar[] = s.split("[ ]");
int sum = 0;
for(int i=0;i<ar.length;i++){
try{
sum += Integer.parseInt(ar[i]);
}catch(NumberFormatException){
//not an integer.
}
}
System.out.println("Sum of integers : "+sum);
public class Main{
public static void main(String []args){
String s="12 computer 5 7";
String [] candidateNumbers = s.split(" ");
int sum = 0;
for (String num:candidateNumbers) {
try {
sum+=Integer.parseInt(num);
} catch (Exception e) {
//
}
}
System.out.println(sum);
}
}
Using Java 8 you could also write:
int sum = Arrays.stream(s.split("\\D+"))
.mapToInt(Integer::parseInt)
.sum();
Splitting on non digit characters returns an array containing the 3 numbers as strings. Note that this assumes that the input string is well formed.
Related
I am supposed to evaluate a string by splitting the string in tokens using the StringTokenizer class. After that I am supposed to convert these tokens to int values, using "Integer.parseInt".
What I don't get is how I am supposed to work with the tokens after splitting them.
public class Tester {
public static void main(String[] args) {
String i = ("2+5");
StringTokenizer st = new StringTokenizer(i, "+-", true);
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
int x = Integer.parseInt();
//what exactly do I have to type in here, do convert the token(s) to an int value?
}
}
So if I understand this right I now have three tokens. That would be: "2", "+" and "5".
How exactly do I convert these tokens to int values?
Do I have to convert each of them seperatly?
Any help is appreciated.
Maybe you can use this:
String i = ("2+5");
StringTokenizer st = new StringTokenizer(i, "+-", true);
while (st.hasMoreTokens()) {
String tok=st.nextToken();
System.out.println(tok);
//what exactly do I have to type in here, do convert the token(s) to an int value?
if ("+-".contains(tok)) {
//tok is an operand
}
else {
int x = Integer.parseInt(tok);
}
}
To have a possibility to make some calculations with the Integers extracted from the String, you have to put them into an ArrayList. And you have to use try/catch operation to avoid a NumberFormatException. Further you can take the values directly from the ArrayList and do with them what you'd like. For example:
public static void main(String[] args) {
ArrayList <Integer> myArray = new ArrayList <>();
String i = ("2+5");
StringTokenizer st = new StringTokenizer(i, "+-/*=", true);
while (st.hasMoreTokens()) {
try {
Integer stg = Integer.parseInt(st.nextToken(i));
myArray.add(stg);
}
catch (NumberFormatException nfe) {};
}
System.out.println("This is an array of Integers: " + myArray);
for (int a : myArray) {
int x = a;
System.out.println("This is an Integer: " + x);
}
int b = myArray.get(0);
int c = myArray.get(1);
System.out.println("This is b: " + b);
System.out.println("This is c: " + c);
System.out.println("This is a sum of b + c: " + (b + c));
}
As a result you'll get:
This is an array of Integers: [2, 5]
This is an Integer: 2
This is an Integer: 5
This is b: 2
This is c: 5
This is a sum of b + c: 7
When I can't use the 'list', but need to store the inputs from the scanner, how can I deal with it?
I want to make the program counting the frequencies of the inputs appearing in the inputs from scanner.
For example, if the input is
"I like apple but I like banana too"
The result is
I: 2
like: 2
apple: 1
banana: 1
but: 1
too: 1
At first I thought of making the arrays of string, and every time input comes, I put them in the array. After then, although it would require n^2 time complexity, run the for loop for each element and then check if it has the same word.
for (String str in arr){
for(String str_2 in arr){
if(strr.equals(str_2)){
count[i]++;
} // count is the array storing the frequencies.
But problem here is... when declaring the arr, I should know the input size. Other people told me to use "list" , but the usage of the "list" is restricted.
In this situation, what would be the way?
Can you use Java streams?
String[] array = {"i", "like", "apple", "but", "i", "like", "banana", "too"};
Or to get the input from the user, something like:
Scanner sc = new Scanner(System.in);
int numberOfEntries = sc.nextInt(); // defines how big the array should be
String[] array = new String[numberOfEntries];
for (int i = 0; i < numberOfEntries; i++) {
System.out.println("Enter value " + (i+1));
String word = sc.next();
array[i] = word;
}
Arrays.stream(array).collect(Collectors.groupingBy(p -> p, Collectors.counting()))
.entrySet().stream().forEach(key -> System.out.println(key.getKey() + ": " + key.getValue()));
Output:
banana: 1
but: 1
apple: 1
too: 1
like: 2
i: 2
You can do something like this by using a HashMap and iterating over the input array in a for loop and checking if the map already contains the key or not. If it contains then just increase the count in the value. If the key is not already in the map, just add it alongwith value 1.
for (String str : inputArray) {
if (map.containsKey(str)) {
map.put(str, map.get(str) + 1);
} else {
map.put(str, 1);
}
}
Finally, just iterate over the map and print with key and value pairs.
String input = "I like apple but I like banana too";
String[] words = input.split(" ");
int countfre=0;
HashMap<String,Integer> map = new HashMap<String, Integer>();
for(int i=0;i<words.length;i++){
if(!map.containsKey(words[i])){
for (int j=0;j<words.length;j++){
if(words[i].equalsIgnoreCase(words[j])){
countfre++;
}
map.put(words[i],countfre);
}
countfre=0;
System.out.println(words[i] + " = " +map.get(words[i]));
}
}
//Without java stream api.
//Stored output in Map.
Output:
banana = 1
but = 1
apple = 1
too = 1
like = 2
i = 2
Try something like,
public static void main(String[] args) {
//input
String s = "I like apple but I like banana too";
//desired output
//I: 2 like: 2 apple: 1 banana: 1 but: 1 too: 1
String[] str = s.split(" ");
String[] result = new String[str.length];
int temp = 0;
test:
for (String str1 : str) {
for (String str2 : result) {
if(str1.equals(str2)){
continue test;
}
}
result[temp++] = str1;
int count = 0;
for (String str2 : str) {
if(str1.equals(str2)){
count++;
}
}
System.out.print(str1 + ": " + count + " ");
}
so far i have no problem in getting the length but the recognizing the numbers from letters is hard can any one help me here Thanks for the helps heres the new code my new problem is in counting the elements in the string in will not count the numbers inputted like a Address Example 99 San pedro st philippines ..... it will only count San pedro st philippines .........
import java.util.Scanner;
public class Exercise3
{
public static void main(String [] args)
{
Scanner scan= new Scanner(System.in);
System.out.println("Enter String:");
String s=scan.nextLine();
s = s.replace(" ","");
System.out.println("Total of Elements is: " + s.length());
int nDigits =0,nLetters =0,sum =0;
for(int i =0;i<s.length();i++)
{
Character ch = s.charAt(i);
if(Character.isDigit(ch)){
nDigits++;
sum += Integer.parseInt(ch.toString());
}
else if (Character.isLetter(ch)){
nLetters++;
}
}
System.out.println("The sum of numbers in the string: " + sum);
}
}
}
It looks like your problem is with the line sum += Integer.parseInt(s.toString());. You're taking the string value of the entire InputStream, which is almost certainly what you don't want. I assume you intended to do sum += Integer.parseInt(s.charAt(i).toString());, which will give you just the value of each individual digit. Take in mind in the string hello43world, it would return 7 (4+3), not 43.
EDIT: To do what you actually want - which is the number of letters in the string, try
public static int getSum(String s)
{
int sum = 0;
for(int i = 0; i < s.length(); i++)
{
if(Character.isLetter(s.charAt(i)))
{
sum ++;
}
}
return sum;
}
This will only count the characters in the string - much easier than trying to not count everything that isn't a character.
I am making a program that takes the user his 3 number input and then compares these individual numbers to numbers I have.
How do I split and save these use input numbers to individual integers?
String.split() and Integer.parseInt() are your friends.
String input = "1 2 3";
String[] spl = input.split(" "); //Or another regex depending on the input format
for (String s : spl) {
System.out.println(Integer.parseInt(s)); // or store them as you like
}
String input = "12 23 12";
String[] split = input.split(" "); // or "\t" according to need
int[] arr = new int[split.length];
int count = 0;
for(String s:split)
{
arr[count] = Integer.parseInt(s).intValue();
count++;
}
There is very convenient class added to Java 1.5 called Scanner.
Here is my sample program that reads String, finds all decimal numbers and prints them to console. Delimiter by default is whitespace.
public static void main(String[] args) {
String userInput = "1 2 3 4 5 6";
try (Scanner scanner = new Scanner(userInput)) {
scanner.useRadix(10);
while (scanner.hasNextInt()) {
int i = scanner.nextInt();
System.out.println(i);
}
}
}
E.g. String userInput = "1 2 3 4 5 df 6"; // output 1 2 3 4 5
There are couple of advantages:
There is no need to call parseInt method, that can throw unchecked exception NumberFormatException if user input was incorrect.
Returns value of primitive type int (or any other on your choice)
Input source can be easily changed to File, InputStream, Readable, ReadableByteChannel, Path.
Hello I'm trying to fix a bug in my code. When reading an incoming phrase this code doesn't seems to count integers. It counts the number of non integer words no problem.
For example if I have the following sentence :
"I love my 4 cats"
It should show that I have 4 Non integer words an 1 integer. But this is not the case with the integer, it seems to identify it as a word
Any ideas?
String[] stra = phrase.split(" ");
int numInts = 0;
int numNonInts = 0;
for (String s : stra) {
try {
Integer.parseInt(s);
}
catch(NumberFormatException nfe) {
numNonInts++;
continue;
}
numInts++;
}
String[] stra = phrase.split("\\W+"); // + for sequences
int numInts = 0;
int numNonInts = 0;
for (String s : stra) {
try {
Integer.parseInt(s);
numInts++;
}
catch (NumberFormatException nfe) {
numNonInts++;
}
}
Two spaces would have counted as one word.
Also \\W includes all non-word chars.
Try using:
Integer.valueOf(s);
instead of
Integer.parseInt(s);
To avoid unexpected separators (like tabs, double spaces or line break), replace you split by:
phrase.split("\\s+");
And maybe you got numbers that exceed the limit of Integer.
Replace your loop by:
for (String s : stra) {
if(s.matches("\\d+"))
numInts++;
else
numNonInts++;
}