First off I want to start by saying I'm not just looking for someone to give me the answer to this problem, I am a beginner programmer and am just trying to learn as much as possible. A critique of my code and a friendly nudge in the right direction would be most appreciated! What is really confusing me is my stringParser method. I use this method to loop through the string, picking out the numbers and storing them in a new string to be parsed. What confuses me is how I would be able to add these numbers together? Here is the code:
public static int stringParser(String parsee,int parsed)
{
int indexOfString = parsee.indexOf("="); //Searches for an = sign since there has to be one
String parsee2 = "";
int [] newArray;
String subStringParse = parsee.substring(0,indexOfString); //Substring made to divide string, this one is from 0 index to 1st occurence of =
for(int i = 0;i<subStringParse.length();i++)
{
if(Character.isDigit(subStringParse.charAt(i))) //if the value is a number it is stored in a new string then parsed.
{
parsee2+= subStringParse.charAt(i);
parsed = Integer.parseInt(parsee2);
}
} return parsed;
}
public static int sumInts(int a,int storedSums)
{
//a = new int[20];
for(int i=0;i<a;i++) //loops through parsed string from stringParser
{
storedSums += a; //creates a new value calculating sum
}
return storedSums;
}
As per my guess, you want to parse something like this `12 + 34 = '.
If I'm right, then your for loop is completely wrong. It will return only 34 as integer value. You can debug your code for that.
I suggest you something like this :
int index = 0;
for(int i = 0;i<subStringParse.length();i++)
{
if(Character.isDigit(subStringParse.charAt(i))) //if the value is a number it is stored in a new string then parsed.
{
parsee2+= subStringParse.charAt(i);
parsed = Integer.parseInt(parsee2);
}
newArray[index++] = parsed; //make sure you initialize newArray.
}
return newArray;
Try,
String parsee = "12+13 = 34+45 = 45+-45";
int value = 0;
String parsed = "";
for(String exp : parsee.split("=")){
for(String val : exp.trim().split("\\+")){
value+=Integer.parseInt(val);
}
parsed+=" SUM = "+value;
value = 0;
}
System.out.println(parsed);
Output
SUM = 25 SUM = 79 SUM = 0
Related
Hi biologist here with a little bit of coding background. my goal is to be able to input a string of characters and the code to be able to tell me how many times they occur and at what location in the string.
so ill be entering a string and i want the location and abundance of sq and tq within the string. with the location being the first character e.g njnsqjjfl sq would be located at postition 4.
This is what ive come up with so far (probably very wrong)
string S = "...";
int counter =0;
for(int i=0; i<s.length; i++){
if(s.charAt (i) == 'sq')}
counter++;})
string S = "...";
int counter =0;
for(int i=0; i<s.length; i++){
if(s.charAt (i) == 'tq')}
counter++;})
any input will help, thankyou
So , you can have multiple occurrences of "sq" and "tq" in your code, so you can have 2 arraylists to save these two separately(or one to save them together).
ArrayList<Integer>sqLocation = new ArrayList<>();
ArrayList<Integer>tqLocation = new ArrayList<>();
for(int i =0;i<s.length()-1;i++){
if(s.charAt(i)=='s' && s.charAt(i+1)=='q'){
sqLocation.add(i);
}
else if(s.charAt(i)=='t' && s.charAt(i+1)=='q'){
tqLocation.add(i);
}
}
System.out.println("No. of times sq occurs = "+sqLocation.size());
System.out.println("Locations ="+sqLocation);
System.out.println("No. of times tq occurs = "+tqLocation.size());
System.out.println("Locations ="+tqLocation);
This can be achieved using regex. Your use case is to count occurrences and position of those occurrences. The method match returns an integer list which is position and count is size of list
Exmaple code
public class RegexTest {
public static List<Integer> match(String text, String regex) {
List<Integer> matchedPos = new ArrayList<>();
Matcher m = Pattern.compile("(?=(" + regex + "))").matcher(text);
while(m.find()) {
matchedPos.add(m.start());
}
return matchedPos;
}
public static void main(String[] args) {
System.out.println(match("sadfsagsqltrtwrttqsqsqsqsqsqs", "sq"));
System.out.println(match("sadfsagsqltrtwrttqksdfngjfngjntqtqtqtqtqtq", "tq"));
}
}
what you want is a HashMap <String, List <Integer>>
this will hold, the String that you are looking for e.g. sq or tq, and a List of the positions that they are at.
You want to loop around using String.indexOf see https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java.lang.String,%20int)
psuedocode being
String contents = "sadfsagsqltrtwrttqksdfngjfngjntqtqtqtqtqtq";
map.add (lookFor, new ArrayList ());
int index = 0;
while ((index = contents.indexOf (lookFor, index)) != -1) {
list = map.get (lookFor);
list.add (index);
}
You should use not charAt but substring to get a part of String.
int count(String s, String target) {
int counter = 0;
int tlen = target.length();
for (int i = tlen; i < s.length(); i++) {
if (s.substring(i - tlen, i).equals(target)) {
counter++;
}
}
return counter;
}
// in some method
count("...", "sq");
count("...", "tq");
I am taking characters from a string and its values are added still I am getting a particular value.. suppose my value to get is 50 .. i need to take character each from a string and add its values
for example the value I need to get is 10
and value for letters a=1,b=2,c-3;
and the string is abca so its total value is 1+2+3+1 = 7
so 10 didn't reached so I need to add once agin from start like abca 7 + 1 + 2. So at the place of b we got the 10 value.. so the result is 2.
I know how to take the value for once but the second time calculation an dthird time I am not getting if anyone can help..pls help
The code so far I completed..
long currentValueFN = 0;
long value = 0;
char[] currentFN = new char[text.length()];
currentFN = text.toCharArray();
Long l = Long.parseLong(String.valueOf(currentAge));
for(int i=0; i<text.length(); i++)
{
currentValueFN += valueLetters( currentFN[i] );
if(currentValueFN >= l)
{
value = valueLetters( currentFN[i] );
}
}
return value;
long currentValueFN = 0;
long value = 0;
char[] currentFN = new char[text.length()];
currentFN = text.toCharArray();
Long l = Long.parseLong(String.valueOf(currentAge));
while(currentValueFN < l ) //check if current value is enough
{
for(int i=0; i<text.length(); i++)
{
currentValueFN += valueLetters( currentFN[i] );
if(currentValueFN >= l)
{
value = valueLetters( currentFN[i] );
break;
}
}
}
return value;
1) if there are enough characters in "text": will escape from for by break and then from while by expression;
2) if there aren't enough characters in "text": will finish for and start it again by while expression. until 1)
please forgive me if my answer is wrong.
1)I have taken a string variable called "variable" and converted it to character array called "character_array"(array name).
2)Then i converted the character array elements to its equivalent ascii code and it is stored in an integer array called "value_array"(array name).
3)Then i checked the condition that the givenvalue is less than the addedvalue.
public class Stack {
public static void main(String args[])
{
long addedvalue=0;
long requiredvalue=600;
String variable="ravi";
char characterarray[]=new char[variable.length()];
for(int i=0;i<variable.length();i++)
{
characterarray[i]=variable.charAt(i);
System.out.println(characterarray[i]);
}
int valuearray[]=new int[variable.length()];
for(int j=0;j<variable.length();j++)
{
valuearray[j]=(int)(variable.charAt(j));
System.out.println(valuearray[j]);
}
while(addedvalue<=requiredvalue)
{
for(int j=0;j<variable.length();j++)
{
valuearray[j]=(int)(variable.charAt(j));
if(addedvalue>=requiredvalue)
break;
addedvalue=addedvalue+valuearray[j];
System.out.println(j);
}
}
}
}
This should help you.
currentValueFN =0;
a=0;
while(currentValueFN !=l){
a=valueLetters( currentFN[i] );
currentValueFN +=a;
if(currentValueFN >= l)
{
value = a;
break;
}
}
return value;
I need a String array with the following attributes:
4 digits numbers
No repeating digits ("1214" is invalid)
No 0's
Is there an easier way to do this than manually type it? Like:
String[] s = {"1234","1235",1236",1237",1238",1239","1243","1245"};
Sorry for my English!
The following code will generate an array with your specifications.
public class Test {
public static void main(String[] args) {
List<String> result = new ArrayList<>();
Set<Character> set = new HashSet<>();
for (int i = 1234; i <= 9876; i++) {
set.clear();
String iAsString = Integer.toString(i);
char[] chars = iAsString.toCharArray();
boolean valid = true;
for (char c : chars) {
if (c == '0' || !set.add(c)) {
valid = false;
break;
}
}
if (valid) {
result.add(iAsString);
}
}
String[] yourStringArray = result.toArray(new String[result.size()]);
System.out.println(Arrays.toString(yourStringArray));
}
}
****edit****
Just saw that it is in Java. So use this function: String.valueOf(number) to convert integer to string if none of the digits are repeats in the loop.
Not sure what language you are doing but I am assuming no repeats not replies.
So what you can do is have a loop from 0 to 9999 and then run through all the numbers while checking if each digit has repeats if so discard number (do not store it into array).
You can convert integers to strings in many languages in their function so you can do that then store it into array.
Good luck.
Hope this helped (fastest solution from my head...there could be more efficient ones)
Try this method for creating Random number with your structure :
ArrayList<Integer> rawNumbers = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5,6,7,8,9));
public String createRandomNumberSring()
{
String result = "";
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.addAll(rawNumbers);
for(int i = 0; i < 4; i++)
{
int index = (int)(Math.random() * (numbers.size() + 1));
result += numbers.get(index).toString();
numbers.remove(index);
}
return result;
}
This is my first post so go easy on me. This IS a homework question, but I have spent about 7 hours working through various means to complete this goal and have had no success. I am building various methods for an assignment, and I need to figure out how to split a String into several int variables.
Ex: given the String "100 200 300" I need to change it to three int of 100, 200, 300. I have to use indexOf(), and cannot use split() or arrays.
String scores="100 200 300";
int n=scores.indexOf(" ");
String sub=scores.substring(0,n);
Integer.parseInt(sub);
This lets me get the first string "100" and parse it. However, I do not know how to continue the code so it will get the next ones. For my method, I will need the new int variables for later arguments.
EDIT: I think I need to use a for loop: something like:
for(int i=0; i<=scores.length; i++)
{//I do not know what to put here}
Joe, indexOf() is overloaded, check out this version:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(int,%20int)
You need two things:
a loop;
being able to run indexOf() from where it left off (hint: read the Javadoc).
public static void main(String[] args) {
String scores = "100 200 300";
ArrayList<Integer> numbers = new ArrayList<Integer>();
int n = 0;
while (n != -1) {
String sub = "";
n = scores.indexOf(" ");
if (n != -1) {
sub = scores.substring(0, n);
scores = scores.substring((n + 1));
} else {
sub = scores;
}
numbers.add(Integer.parseInt(sub));
}
for (int i : numbers) {
System.out.println("" + i);
}
}
Try something like this to loop through and add numbers to arraylist. The arraylist numbers will contain all your numbers.
try this:
String scores="100 200 300";
int offset = 0;
int space;
int score;
scores = scores.trim(); //clean the string
do
{
space= scores.indexOf(" ", offset);
if(space > -1)
{
score = Integer.parseInt(scores.substring(offset , space));
}
else
{
score = Integer.parseInt(scores.substring(offset));
}
System.out.println(score);
offset = space + 1;
}while(space > -1);
Your 'n' variable is the important part. You get your first String by slicing from 0 to 'n', so your next string starts not at 0, but at
n + " ".size()
Ok, so here is what I have come up with:
Since I needed to compare the newly parsed ints with a different variable, as well as ensure that the amount of ints was equal to a different variable, I created this while loop:
public boolean isValid()
{
int index=0;
int initialindex=0;
int ntotal=0;
int ncount=0;
boolean flag=false;
while (index!=-1)
{
index=scores.indexOf(" ");
String temp=scores.substring(initialindex,index);
int num=Integer.parseInt(temp);
ntotal+=num;
ncount++;
initialindex=index;
}
if (ntotal==total && ncount==count)
{
flag=true;
}
return flag;
}
I've got this bit of code here:
public class Project1 {
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Input a binary number");
String binary = input.nextLine();
System.out.println(Conversion(binary));
}
public static int Conversion(String binary)
{
StringTokenizer st = new StringTokenizer(binary, " ");
int n = st.countTokens() - 1; // Used as the power number in b^n for conversion
int result = 0;
while(st.hasMoreTokens()){
int binaryInt = Integer.parseInt(st.nextToken());
result += binaryInt * (1 << n);
n--;
}
return result;
}
}
And it works beautifully... if the input has spaces in between the binary numbers. For example, if the input is 1 1 1 1, then it will rightfully return 15. Cool, but how do I change the tokenizer to not require spaces to split each digit? I tried doing StringTokenizer(binary, ""); and StringTokenizer(binary);, but neither properly split each digit into it's own token.
You will notice that, while StringTokenizer obviously only works with Strings, I've converted the Strings into ints inside my conversion method before returning the result.
# Tony I think you tried to add the ascii values of the digits here
for input value 10
for first run
int binaryInt = binary.char(i) ; so binaryInt would get the value = 49(aski value of char '1')
hence result = 49*2 = 98
in second run
result = 98 + 48 *1 = 146
following function will serve your purpose, for input String "1101" , it returns 13
public int getDecimal(String binaryString){
//binaryString = "1101";
int result = 0;
int n = binaryString.length()-1;
for(int i=0;i<binaryString.length();i++)
{
int num = binaryString.charAt(i);
if(num>=48 && num <=57){
result+=(num-48) * Math.pow(2, n) ;
n --;
}
}
return result;
}
}
How about something like this:
// remove everything that is not a digit
String digitsOnly = binary.replaceAll("[^\\d]","");
//iterate over every digit
for(char digit:digitsOnly.toCharArray()) {
int n = Character.getNumericValue(digit);
// do stuff...
}
If you get a string like "10011010", you don't need a tokenizer, you can just iterate over the string and use charAt:
for (int i = 0; i < s.length(); i++) {
char currentDigit = s.charAt(i);
// Do stuff with the digit
}