Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Hey guys i'm trying to write a code that will count the characters in a text file.
ex : AAABBbbcC
3A 2B 2b 1c 2C
but i don't know how to count the characters like (AAA) if they are not separated.
i'm trying this but it doesn't work like a recursion
String s = "aasjkkk";
int count1 = 0;
int count2 = 0;
char karakter1 = 0;
char karakter2 = 0;
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) == s.charAt(i+1)) {
karakter1 = s.charAt(i);
count1 += 1;
System.out.print(count1 + " " + karakter1 + " ");
}
else if(s.charAt(i) != s.charAt(i+1)) {
karakter1 = s.charAt(i);
karakter1 = 1;
karakter2 = s.charAt(i+1);
karakter2 = 1;
System.out.print(count1 + " " + karakter1 + " " + count2 + " " + karakter2 + " ");
}
}
Since this looks like a homework, I can suggest a way for you to do this:
Create a HashMap
Loop from the beginning to the end of the file. If you have a new character, then set a new key to the HashMap with 1 as the value; if not, just plus one to the current value of the old character
Have fun !!
It's true that you should and must show what you've tried before.
I think that you could have already thought about taking the String into a char array, iterating, etc...
Well, #bubuzz advise is a good one, here it comes an implementation:
public class ClasesObjetos {
public static void main(String[] args) {
String s = "This is a single String";
HashMap<Character, Integer> m = new HashMap();
for (Character c : s.toCharArray()) {
if (!c.equals(" ")) {
if (m.get(c) == null )
m.put(c, 1);
else {
int i = (int) m.get(c) + 1;
m.put(c, i);
}
}
}
for (Character c : m.keySet()) {
System.out.println(c + " ---> " + m.get(c));
}
}
}
Try it out you'll see it ignores spaces. It will count any symbols though, you should you add up if checks.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Following is the google interview question, Can someone please solve or provide the logic to find the answer. Operators [+,-,*]
Output should be the list of all the possible strings which generates the target number.
Ex1:
Input = 1234
Desired number = 6
Expected Output = [2+4,3+4-1,2*3,1+2+3... etc]
Ex2:
Input = 105
Desired number = 5
Expected Output = [10-5,1*5... etc]
Here is quick fix for you.
Please check following code.
public static void main(String arg[]) {
String num = "105";
int target = 5;
getValue(num, target);
}
static void check(double sum, double previous, String digits, double target, String expr) {
if (digits.length() == 0) {
if (sum + previous == target) {
System.out.println(expr + " = " + target);
}
} else {
for (int i = 1; i <= digits.length(); i++) {
double current = Double.parseDouble(digits.substring(0, i));
String remaining = digits.substring(i);
check(sum + previous, current, remaining, target, expr + " + " + current);
check(sum, previous * current, remaining, target, expr + " * " + current);
check(sum, previous / current, remaining, target, expr + " / " + current);
check(sum + previous, -current, remaining, target, expr + " - " + current);
}
}
}
static void getValue(String digits, double target) {
for (int i = 1; i <= digits.length(); i++) {
String currentValue = digits.substring(0, i);
check(0, Double.parseDouble(currentValue), digits.substring(i), target, currentValue);
}
}
Output :
1 * 0.0 + 5.0 = 5.0
1 * 5.0 = 5.0
10 - 5.0 = 5.0
Hope this example is help you to understand the concept.
I wish to put the raw questions(rawQuestions) as inputted in this way in command prompt:
java Hangman Hello test 123, into the array (questions). I know rawQuestion will not work down in the "store valid questions into an array" part because of
"error: ';' expected " and "error: not a statement"
in the line
" questions[vCount] = String rawQuestion; "
Therefore how should I rewrite it?
public class Hangman {
//Validation of raw questions
public static boolean isValidQuestion(String rawQuestion){
rawQuestion = rawQuestion.toUpperCase();
boolean vQuestion = true;
for(int i=0; i<rawQuestion.length(); i++){
char c = rawQuestion.charAt(i);
if(!(c>='A' && c<='Z'))
vQuestion = false;
}
return vQuestion;
}
public static void main(String args[]){
boolean vQs[] = new boolean[args.length];
for(int i=0; i<args.length; i++){
String rawQuestion = args[i];
boolean b = isValidQuestion(rawQuestion);
if(b)
System.out.println(rawQuestion + " is a valid question!");
else
System.out.println("Error: " + rawQuestion + ", input must be a word consist of a-z or A-Z");
vQs[i] = b;
}
//count the number of valid questions
int vCount = 0;
for(int i=0; i<vQs.length; i++){
System.out.println(i + " " + vQs[i] );
if(vQs[i])
vCount++;
}
System.out.println("There are " + vCount + " valid questions");
//store valid questions into an array
String questions[] = new String[vCount];
for(vCount=0; vCount<args.length; vCount++){
questions[vCount] = String rawQuestion;
System.out.println( questions[vCount] );
}
}
}
Try this:
String[] validQuestions = Arrays.stream(args)
.filter(Hangman::isValidQuestion)
.toArray(String[]::new);
int validQuestionCount = validQuestions.length;
But even without Streams, your whole method could be done in one for loop, counting and collecting the valid questions in one go instead of having three separate steps:
List<String> validQuestions = new ArrayList<>();
for (int i = 0; i < args.length; i++)
{
String rawQuestion = args[i];
boolean b = isValidQuestion(rawQuestion);
if (b)
{
validQuestions.add(rawQuestion);
System.out.println(rawQuestion + " is a valid question!");
}
else
{
System.out.println("Error: " + rawQuestion + ", input must be a word consist of a-z or A-Z");
}
}
// count the number of valid questions
System.out.println("There are " + validQuestions.size() + " valid questions");
// store valid questions into an array
String questions[] = validQuestions.toArray(new String[validQuestions.size()]);
This way, you do not have to juggle the index variables yourself, which is hard to understand, especially if somebody else tries to read it. (Especially the re-use of vCount is kinda scary to me)
I fixed something and commented, not sure if it works, i haven't compiled it.
public static void main(String args[]){
boolean vQs[] = new boolean[args.length];
int vCount=0;
for(int i=0; i<args.length; i++){
String rawQuestion = args[i];
if(isValidQuestion(rawQuestion)){
System.out.println(rawQuestion + " is a valid question!");
//Here you have enough data to count the valid questions, three loops are not needed.
++vCount;
vQs[i]=true;
}else{
System.out.println("Error: " + rawQuestion + ", input must be a word consist of a-z or A-Z");
vQs[i]=false;
}
}
System.out.println("There are " + vCount + " valid questions");
//store valid questions into an array
String questions[] = new String[vCount];
int j=0;
for(int i=0; i<args.length; i++){
//You need to iterate for all strings, because vQs[] is long args.length
if(vQs[i]){
//Ok the i-th question was valid, let's move it and print it
questions[j] = args[i];
System.out.println( questions[j] );
++j;
}
}
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
so this is the case.
I'm doing an excercise where I have to compare each random number with all my static numbers from an external file lotto.dat
I have to make a method doCompare() which returns either true or false. My question will appear after my code:
public static void drawNumbers()throws Exception{
Random rnd = new Random();
int rndN1 = rnd.nextInt(19)+1;
int rndN2 = rnd.nextInt(19)+1;
int rndN3 = rnd.nextInt(19)+1;
int rndN4 = rnd.nextInt(19)+1;
int rndN5 = rnd.nextInt(19)+1;
int rndN6 = rnd.nextInt(19)+1;
System.out.println();
System.out.println("Winner numbers: " + rndN1 + " " + rndN2 + " " + rndN3 + " " + rndN4 + " " + rndN5 + " " + rndN6);
String match = doCompare(rndN1);
if(match.equals("true")){
System.out.println("Match on the number: " + rndN1);
}
}
So is it possible somehow loop the "doCompare" with parameters "doCompare(rndN1)" then rndN2, rndN3 and so on or what else should I do to make this work?
Use a proper data structure, like an array or a List to store the random numbers and loop over them:
List<Integer> numbers = new ArrayList<>();
for(int cout = 0 ; count < 6 ; ++count) {
numbers.add(rnd.nextInt(19)+1);
}
// ...
for(int n : numbers) { // go through all the numbers in the list
doCompare(n);
}
Create a List which can collect your integers. Create a loop which create the integers and add them to a list. While creating the random integers, you can create the output string in the loop too. And at the end use another loop for the method call doComapre() and pealse change the return value of doCompare() method to boolean. Then you can use it in the if statement and have not to check if the return value is equals "true".
Random rnd = new Random();
List<Integer> rndNumbers = new ArrayList<>();
String outputString = "Winner numbers:";
for(int i = 0; i < 6; i++)
{
rndNumbers.add(rnd.nextInt(19) + 1);
outputString = outputString + " " + rndNumbers.get(i);
}
System.out.println();
System.out.println(outputString);
for(Integer curNumb : rndNumbers)
{
String match = doCompare(curNumb );
if (match.equals("true"))
{
System.out.println("Match on the number: " + curNumb );
}
}
Maybee you can use an array because you are always want to generate six numbers. And for the String creation you can replace the String with a Stringbuilder.
The simplest solution would be to create array or list and store rnd number and then loop over it
Yes, you can, but not as you want to do it.
you have to create a list of your rndNX values
Like so:
List<Integer> rndList = new ArrayList<Integer>();
fill it like so :
rndList.add(rnd.nextInt(19)+1);
rndList.add(rnd.nextInt(19)+1);
...
And use the list :
for(final Integer rndI : rndList)
{
String match = doCompare(rndI );
}
Random rnd = new Random();
System.out.println();
for(int i = 0; i < 6; i++)
{
int rndN = rnd.nextInt(19)+1;
String match = doCompare(rndN);
if(match.equals("true")){
System.out.println("Match on the number: " + rndN1);
}
}
You could do something like this. Instead of initializing all your random numbers first initialize them in a loop as needed.
Store the int values into the array or a list and loop through it.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
i have a little missbehaviour in my program.
One of his methods should build an string and then return it to be displayed in an Java Swing GUI.
In some parts of it, it needs to store a "line break" (i dont know the proper name) "/n".
But when i display this string in the gui it contains /n instead of jumping the line properly.
Its a little confusing but with the code i think you can figure it out:
public String draw(Robot robot, MapClass mapa) {
map = mapa.getMapa();
String mapBuffer = "";
for (int i = 0; i < mapa.getLinhas(); i++) {
for (int j = 0; j < mapa.getColunas(); j++) {
if ((i == robot.getPosX()) & (j == robot.getPosY())){
System.out.print(robot.convertToChar() + " ");
mapBuffer = mapBuffer + robot.convertToChar() + " ";
}
else{
System.out.print(map[i][j] + " ");
mapBuffer = mapBuffer + map[i][j] + " ";
}
}
mapBuffer = mapBuffer + "/n";
System.out.println();
}
return mapBuffer;
}
This string is shown in a swing textArea with:
textArea.append(drawer.draw(robot, map));
Thanks.
The problem is here mapBuffer = mapBuffer + "/n"; You are appending to mapBuffer the /n literal. If you want a line break you should replace it with \n
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to do some program and need of some help. For example, I entered this number on a textbox: 00669253, then for each number i want to multiply it with the number 87654321 so for example
(0x8) + (0x7) + (6x6).... and so on and then get the sum of all the number and do a mod of 11. How can I do this?
Thanks for your advance help.
You can first convert the number into String and then you can do it like this :
String no1="00669253";
String no2="87654321";
int sum=0;
for(int i=0;i<no1.length();i++){
sum+=Integer.parseInt(""+no1.charAt(i))*Integer.parseInt(""+no2.charAt(i));
}
After that you can do any operation on sum
You can try something like that:
public class TestMult {
public static void main(String[] args) {
String first = "00669253";
String second = "87654321";
long sum = 0L;
if (first.length() == second.length()) {
for (int i = 0; i < first.length(); i++) {
int firstInt = Character.getNumericValue(first.charAt(i));
int secondInt = Character.getNumericValue(second.charAt(i));
sum += firstInt * secondInt;
}
System.out.println("result: " + sum % 11);
} else {
System.err.println("lengths are not equal.");
}
}
}
try this,
public class Dummy {
public static void main(String[] args) {
String s = "112211";
String s2 = "010101";
char[] sDummy = s.toCharArray();
char[] s2Dummy = s2.toCharArray();
int sum = 0;
for (int i = 0; i < sDummy.length; i++) {
System.out.println("multiplying..." + sDummy[i] + "with " + s2Dummy[i] + "and adding prev sum " + sum + " to it");
sum = sum + (Integer.parseInt(sDummy[i] + "") * Integer.parseInt(s2Dummy[i] + ""));
}
sum = sum % 11;
System.out.println("sum with mod is = " + sum);
}
}
You need to add some checks in case if length of both string differs
Try this,
String inputValue = "00669253";
String multipleValue="87654321";
int result = 0;
for (int i = 0; i < inputValue.length(); i++)
{
result += Integer.parseInt(Character.toString(inputValue.charAt(i))) *
Integer.parseInt(Character.toString(multipleValue.charAt(i)));
}