My question is how would I write a simple compiler ,that is like the compilers used in fax machines, that would convert something like aaaavvvvvddddddddddd to 4a5vBd.
Also, I get to "Assume" that any string entered will not contain uppercase letters and no numbers, and that any string will contain less than 61 of any type of character so, I get to assume no one will put in 64 continues a's in my program.
This is as far as I gotten
import java.util.*;
public class Program4
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int n;
char cn;
String word;
String numChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
System.out.println("Hello, please enter a string");
word = scan.nextln();
if(n <= 61)
{
int n = ?;
cn = numChars.charAt(n);
}
}
}
I assume I need to use a loop, but I don't know what I should use to count the repeating letters and then tell how many letters of that type are in a row. Now I am only asking for advice and not so much for code, because I want to do it but, as a beginner my Java "Vocabulary" isn't very big right now.
Any advice/ tips would be greatly appreciated.
Sincerely,
Mr.Trips
Well I am back and it appears my code here likes to only print out 147. No matter what I type in I will always get 147. I have tried to hand trace all my variables, but when I do it I get exactly what I want, and I must have some error in my logic. Any thoughts?
import java.util.*;
public class Program4
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int n = 0;
int s = 0;
char a;
char b;
char c;
String word;
String numChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
System.out.println("Please enter a string");
word = scan.nextLine();
while (n < word.length())
{
a = word.charAt(n);
b = a;
n = n ++;
a = word.charAt(n);
if (a == b)
{
s = (s + 1) ;
}
else if (a != b);
{
c = numChars.charAt(s);
System.out.print(b + c);
s = 0;
c = 0;
break;
}
}
}
}
Thank you again!
Since you don't want code this is logically how to do it. You are right you should loop through the string for each char. Store the last char in a variable and keep a counter variable. Compare current char to last char if it is equal then increment the counter. As soon as it is not equal to the last char then add counter + last char to result string and reset counter variable. Each iteration update last char variable.
Related
This is the instructions i got from my teacher:
Write your code in the file WordCount.java. Your code should go into a method with the following signature. You may write your own main method to test your code. The graders will ignore your main method:
public static int countWords(String original, int minLength){}
Your method should count the number of words in the sentence that meet or exceed minLength (in letters). For example, if the minimum length given is 4, your program should only count words that are at least 4 letters long.
Words will be separated by one or more spaces. Non-letter characters (spaces, punctuation, digits, etc.) may be present, but should not count towards the length of words.
Hint: write a method that counts the number of letters (and ignores punctuation) in a string that holds a single word without spaces. In your countWords method, break the input string up into words and send each one to your method.
This is my code:
public class WordCount {
public static void main(String[] args)
{
System.out.print("Enter string: ");
String input = IO.readString();
System.out.print("Enter minimum length for letter: ");
int length = IO.readInt();
IO.outputIntAnswer(countWords(input, length));
}
public static int countWords(String original, int minLegth)
{
int count = 0;
int letterCount = 0;
for(int i = 0; i < original.length(); i++)
{
char temp = original.charAt(i);
if(temp >= 'A' && temp <= 'Z' || temp >= 'a' && temp <= 'z')
{
letterCount++;
}
else if(temp == ' '|| i == original.length()-1)
{
if(letterCount >= minLegth)
{
count++;
}
letterCount = 0;
}
}
return count;
}
}
My college uses an autograder to grade project and i am keep getting one of the test case wrong. Can someone help me figure out what the problem is?
I figured the problem that your code is not able to compare the last character.It expects a space after the last character so that it can compare the last character since java doesn't use null character terminator for string termination.I have emulated the same code using Scanner class as I was having some trouble with io.So I have done the following change:
Scanner sc1,sc2;
sc1=new Scanner(System.in);
String input = sc1.nextLine()+" ";
I don't know if its possible to do:
String input = IO.readString()+" ";
but i think you should try appending blank space " " at the end of the string
Given an input string,check whether the string has char 'r' & 'g' separated be exactly 5 characters.
For the following code, the error is String index out of range error.
Can't figure out whats wrong
My code for class having function that checks for pattern:
public class classb {
String s = new String();
public int match(String str){
int counter = 0;
int j;
s=str;
for(j=0;j<(s.length()-6);j++){
if(s.charAt(j)=='r' && s.charAt(j+6)=='g') {
counter=1;
break;
}
if(s.charAt(j)=='g' && s.charAt(j+6)=='r'){
counter=1;
break;
}
while(s.charAt(j)!='r' || s.charAt(j)!='g'){
if(j<(s.length()-6))
j++;
else
break;
}
}
return counter;
}
}
Main class:
import java.util.*;
public class classa
{
public static void main(String[] args)
{
String a = new String();
int count;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string: ");
a= sc.nextLine();
classb x = new classb();
count=x.match(a);
if(count==1)
System.out.println("Pattern found ");
else if(count==0)
System.out.println("Pattern not found ");
}
}
You can use a regex for this problem, r.{5}g.
The r says that the pattern starts with r, and the g says that it ends with g. The . means any character, and the {5} means that there are exactly 5 (in this case of any character).
And to implement this, you would just use the method String#matches("r.{5}g").
The root problem in your code is this:
for(j=0;j<s.length();j++){
while(s.charAt(j)!='r' || s.charAt(j)!='g')
j++;
You have a loop for j where you increase J - but inside that loop you increase j again. Below that, you use j+6 in an index and you haven't checked to see if j+6 is too long. So you're repeatedly modifying j and checking 6 characters out without ever checking to see if those are in bounds.
I'd start by stopping your for loop at s.length()-6. If an r or g sequence starts in those last spots it can't complete, so no need to check them - and then your j+6 logic will work and not blow up.
I have tried to find guidance on this, but I keep getting solutions on an entire string, or a single character. I am in my 4th week of Java, and have hit a roadblock.
I have to ask a user to input three letters ("Enter three letters: abc"). Depending on which case they type, I have to write a program that swaps upper with lower and visa versa. For example, if the user types "aBc", my output will be "AbC".
This is what I have so far. If my code is horrible, I'm sorry. I'm learning as I go.
import java.util.Scanner;
public class LowerUpper {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter three letters: ");
String letters = input.nextLine();
for (int i = 0; i < letters.length(); i++) {
char letter1 = letters.charAt(0);
char letter2 = letters.charAt(1);
char letter3 = letters.charAt(2);
if (Character.isUpperCase(letters.charAt(0)) == true)
System.out.println(Character.toLowerCase(letter1));
else {
System.out.println(Character.toUpperCase(letter1));
}
if (Character.isUpperCase(letters.charAt(1)) == true)
System.out.println(Character.toLowerCase(letter2));
else {
System.out.println(Character.toUpperCase(letter2));
}
if (Character.isUpperCase(letters.charAt(2)) == true)
System.out.println(Character.toLowerCase(letter3));
else {
System.out.println(Character.toUpperCase(letter3));
}
}
}
}
When I typed "abc" for the input, the output was:
A
B
C
A
B
C
A
B
C
The format of the output is supposed to be "Result: ABC". I can work on that later. I'm just trying to figure out how to get this to execute correctly. My hunch is that I'm definitely going wrong on my if/else statements. I do not know how to print the changed chars all in a row (abc, AbC, ABC, etc). I thought I did it correctly at the beginning with the indexing of the string (0,1,2).
By the way, it's not showing my output correctly this forum. It is supposed to be one letter per line, not "ABCABCABC", if I made sense with that.
The reasoning for this is because it's inside of a for loop, which is essentially worthless, because you are never using the integer 'i'. If you remove the for loop, it should only execute once, thus for outputting "ABC", instead of "A B C A B C A B C". To print the chars in a row, you can simply append each character to a string, and then output that.
The biggest issue I see is that you've got a loop going over the length of the string but you're not using the loop index i to reference the individual characters. In short, you're trying too hard and overlooking the obvious.
Wouldn't this do the trick?
for (int i = 0; i < letters.length(); i++) {
char letter1 = letters.charAt(0);
if (Character.isUpperCase(letter1)) {
System.out.println(Character.toLowerCase(letter1));
} else {
System.out.println(Character.toUpperCase(letter1));
}
}
The reason why you get a redundant printing 'coz you loop the three variables which already contain all characters.
To solve your problem. just remove the for loop. 'coz you already
store each character to the three variables.
You code will look like this now:
import java.util.Scanner;
public class LowerUpper {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter three letters: ");
String letters = input.nextLine();
char letter1 = letters.charAt(0);
char letter2 = letters.charAt(1);
char letter3 = letters.charAt(2);
if (Character.isUpperCase(letters.charAt(0)) == true)
System.out.println(Character.toLowerCase(letter1));
else {
System.out.println(Character.toUpperCase(letter1));
}
if (Character.isUpperCase(letters.charAt(1)) == true)
System.out.println(Character.toLowerCase(letter2));
else {
System.out.println(Character.toUpperCase(letter2));
}
if (Character.isUpperCase(letters.charAt(2)) == true)
System.out.println(Character.toLowerCase(letter3));
else {
System.out.println(Character.toUpperCase(letter3));
}
}
}
Ok, here is my new code. It compiled with no errors and the output was just as it was supposed to be:
import java.util.Scanner;
public class LowerUpper {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter three letters: ");
String letters = input.nextLine();
char letter1 = letters.charAt(0);
char letter2 = letters.charAt(1);
char letter3 = letters.charAt(2);
if (Character.isUpperCase(letters.charAt(0)) == true)
System.out.print("Result: " + Character.toLowerCase(letter1));
else {
System.out.print("Result: " + Character.toUpperCase(letter1));
}
if (Character.isUpperCase(letters.charAt(1)) == true)
System.out.print(Character.toLowerCase(letter2));
else {
System.out.print(Character.toUpperCase(letter2));
}
if (Character.isUpperCase(letters.charAt(2)) == true)
System.out.print(Character.toLowerCase(letter3));
else {
System.out.print(Character.toUpperCase(letter3));
}
}
}
The problem is that you have a loop then do each letter individually. So get rid of the loop. It would look better if you re-wrote it with a loop but only had one if/else statement inside the loop based on i not 0,1&2.
Replace your for loop with:
System.out.println(letters.toUpperCase());
This question already has answers here:
Java compressing Strings
(21 answers)
Closed 8 years ago.
I am trying to write a Java program which takes in as input a string and counts the number of occurrences of characters in a string and then prints a new string having the character followed by the no of occurrences.
E.G.
Input String:
aaaabb
Output String:
a4b2
Input String:
aaaaabbbc
Output String:
a5b3c1
I am posting my java code.
It is throwing StringOutOfBoundException
/*Write a routine that takes as input a string such as "aabbccdef" and o/p "a2b2c2def" or "a4bd2g4" for "aaaabddgggg".*/
import java.util.Scanner;
public class CountingOccurences {
public static void main(String[] args) {
Scanner inp= new Scanner(System.in);
String str;
char ch;
int count=0;
System.out.println("Enter the string:");
str=inp.nextLine();
while(str.length()>0)
{
ch=str.charAt(0);
int i=0;
while(str.charAt(i)==ch)
{
count =count+i;
i++;
}
str.substring(count);
System.out.println(ch);
System.out.println(count);
}
}
}
This is the problem:
while(str.charAt(i)==ch)
That will keep going until it falls off the end... when i is the same as the length of the string, it will be asking for a character beyond the end of the string. You probably want:
while (i < str.length() && str.charAt(i) == ch)
You also need to set count to 0 at the start of each iteration of the bigger loop - the count resets, after all - and change
count = count + i;
to either:
count++;
... or get rid of count or i. They're always going to have the same value, after all. Personally I'd just use one variable, declared and initialized inside the loop. That's a general style point, in fact - it's cleaner to declare local variables when they're needed, rather than declaring them all at the top of the method.
However, then your program will loop forever, as this doesn't do anything useful:
str.substring(count);
Strings are immutable in Java - substring returns a new string. I think you want:
str = str.substring(count);
Note that this will still output "a2b2a2" for "aabbaa". Is that okay?
public class StringTest{
public static void main(String[] args){
String s ="aaabbbbccccccdd";
String result="";
StringBuilder sb = new StringBuilder(s);
while(sb.length() != 0){
int count = 0;
char test = sb.charAt(0);
while(sb.indexOf(test+"") != -1){
sb.deleteCharAt(sb.indexOf(test+""));
count++;
}
//System.out.println(test+" is repeated "+count+" number of times");
result=result+test+count;
}
System.out.println(result);
}
}
I don't want to give out the full code. So I want to give you the challenge and have fun with it. I encourage you to make the code simpler and with only 1 loop.
Basically, my idea is to pair up the characters comparison, side by side. For example, compare char 1 with char 2, char 2 with char 3, and so on. When char N not the same with char (N+1) then reset the character count. You can do this in one loop only! While processing this, form a new string. Don't use the same string as your input. That's confusing.
Remember, making things simple counts. Life for developers is hard enough looking at complex code.
Have fun!
Tommy "I should be a Teacher" Kwee
if this is a real program and not a study project, then look at using the Apache Commons StringUtils class - particularly the countMatches method.
If it is a study project then keep at it and learn from your exploring :)
You should be able to utilize the StringUtils class and the countMatches() method.
public static int countMatches(String str,
String sub)
Counts how many times the substring appears in the larger String.
Try the following:
int count = StringUtils.countMatches("a.b.c.d", ".");
I think what you are looking for is this:
public class Ques2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine().toLowerCase();
StringBuilder result = new StringBuilder();
char currentCharacter;
int count;
for (int i = 0; i < input.length(); i++) {
currentCharacter = input.charAt(i);
count = 1;
while (i < input.length() - 1 && input.charAt(i + 1) == currentCharacter) {
count++;
i++;
}
result.append(currentCharacter);
result.append(count);
}
System.out.println("" + result);
}
}
Try this:
import java.util.Scanner;
/* Logic: Consider first character in the string and start counting occurrence of
this character in the entire string. Now add this character to a empty
string "temp" to keep track of the already counted characters.
Next start counting from next character and start counting the character
only if it is not present in the "temp" string( which means only if it is
not counted already)
public class Counting_Occurences {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter String");
String str=input.nextLine();
int count=0;
String temp=""; // An empty string to keep track of counted
// characters
for(int i=0;i<str.length();i++)
{
char c=str.charAt(i); // take one character (c) in string
for(int j=i;j<str.length();j++)
{
char k=str.charAt(j);
// take one character (c) and compare with each character (k) in the string
// also check that character (c) is not already counted.
// if condition passes then increment the count.
if(c==k && temp.indexOf(c)==-1)
{
count=count+1;
}
}
if(temp.indexOf(c)==-1) // if it is not already counted
{
temp=temp+c; // append the character to the temp indicating
// that you have already counted it.
System.out.println("Character " + c + " occurs " + count + " times");
}
// reset the counter for next iteration
count=0;
}
}
}
I have a simple problem that says:
A password for xyz corporation is supposed to be 6 characters long and made up of a combination of letters and digits. Write a program fragment to read in a string and print out a message as to whether or not the string entered would be considered a valid password.
I need help on completing this code. I have this pseudocode that I can't workout into Java code:
print "enter new password"
input newPassword
digitCounter =0
letterCounter = 0
for I = 0 to newPassword.length() by 1
c = newPassword.charAt(i)
if c is a digit
increment digitCounter
else if c is a letter
increment letterCounter
endif
endFor
if newPassword.length() >= 6 and digitCounter > 0 and letterCounter > 0
print "the password is valid"
else
print " password rejected, must be at least 6 characters long and be a mix of letters and digits "
endif
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
So far all I have is this for the Java code:
import java.util.Scanner;
public class Password
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String thePassword;
int len, i, letterCounter = 0, digitCounter = 0;
char c;
Len = thePassword.length();
System.out.print("Enter the password: ");
thePassword = in.nextLine();
for (i = 0,i = len, )
{
c = in.charAt(1);
if ()
}
}
}
Take a look at Character.isDigit() and Character.isLetter() for checking the characters:
If you want to use String.charAt() to get the characters of your string, you could do a for loop like so:
for (int i = 0;i < s.length();i++) {
char c = s.charAt(i);
//Check things about c
}
Although Java 1.5 instroduced a For-Each loop which will loop automatically over arrays like so:
for (char c : s.toCharArray()) {
//Check things about c
}
impot javax.swing.JOptionPane;
class PasswordDemo{
public static void main(String[] agrs){
String pass = "abcdef";
String right = "Success!";
String wrong = "Failed to login";
String input = JOptionPane.showInputDialog("Enter the password to login: ");
do{
JOptionPane.showMessageDialog(null,wrong);
input = JOptionPane.showInputDialog("Enter the password to login: ");
}while(!input.equals(pass));
//when login successfully
JOptionPane.showMessageDialog(null,right);
}
}
I'd check that the Regex \d (any digit), and the Regex [a-z] (any letter) both matches the string. And then check for length.
A couple quick tips:
your pseudo code algorithm is not correct. It will correctly validate that strings must indeed be at least 6 characters in length, but won't invalidate passwords with weird characters in them (e.g. ~%). Based on the problem statement, it seems implicit that the sentence "made up of a combination of letters and digits" means made up only of those. For this part, as others have mentionned, you can use built-in methods of the String or Character classes such as String.charAt(), Character.isDigit() and Character.isLetter().
make it a habit to declare stuff at the latest possible time (i.e just before it's used). In your example, you have String thePassword, then 2 other lines, then you assign something to thePassword. Instead, write it directly as String thePassword = in.nextLine(). This will help make the code less cluttered and easier to read. Same for your other declarations (char c, int len, etc.).
try to use the enhanced for loop if you can, in order to avoid having to figure out the length and determine where to stop (potential for errors). In your example, your loop could be something like for (char c : thePassword.toCharArray()). If you haven't talked about this loop in your class yet, you don't have to use, and you should know how the simple for loop works as well, but this is just a suggestion. In your code example, your loop does not make sense, so I'd advise you to read up on loops.
I'm going to pretend that you just read in from the command line arguments, if you need it to be able to accept multiple passwords you can generalize it. Here is how I would easily do it:
public class Password {
public static void main(String[] args) {
String thePassword = args[0];
int passLength = thePassword.length();
boolean hasLetters = false;
boolean hasDigits = false;
boolean hasSomethingElse = false;
for (int i=0; i < passLength; i++) {
char c = thePassword.charAt(i);
if(Character.isLetter(c)) hasLetters = true;
else if(Character.isDigit(c)) hasDigits = true;
else hasSomethingElse = true;
}
if (hasLetters && hasDigits && !hasSomethingElse && (passLength >= 6)) {
System.out.println("Password is correctly formatted");
} else {
System.out.println("Password is not correctly formatted");
}
}
}