Can not figure out Javas strings? - java

I am a student at the moment so I am still learning. I picked up VB pretty quick and it was simple Java on the other hand I am pretty confused on.
The Assignment I have been given this time has me confused "Write a method to determine the number of positions that two strings differ by. For Example,"Peace" and "Piece" differ in two positions. The method is declared int compare(String word1, String word2); if the strings are identical, the method returns 0. It returns -1 if the two strings have different lengths."
Additional "Write a main method to test the method. The main method should tell how many, positions the strings differ, or that they are identical, or if they are different lengths, state the lengths. Get the strings from the console.
So far this is where I am at and I am looking for someone to help break this down in I DUMDUM terms if they can I don't need a solution only help understanding it.
package arraysandstrings;
import java.util.Scanner;
public class differStrings {
public static void main (String agrs[]){
Scanner scanner = new Scanner (System.in);
System.out.print("Enter a word");
String word1;
String word2;
word1 = scanner.next();
System.out.print("Enter another word");
word2 = scanner.next();
int count = 0;
int length = word1.length();
for(int x = 0; x >= length; x = x+1) {
if (word1.charAt(x) == word2.charAt(x)) {
count = count + 1;
System.out.print (count);
}
}
}
}
Additional Question
package arraysandstrings;
import java.util.Scanner;
public class differStrings {
public static void main (String agrs[]){
Scanner scanner = new Scanner (System.in);
System.out.println("Enter a word");
String word1 = scanner.next();
System.out.println("Enter another word");
String word2 = scanner.next();
int count = 0;
int word1Length = word1.length();
int word2Length = word2.length();
if (word1Length != word2Length) {
System.out.println ("Words are a diffrent length");
System.out.println (word1 + "Has" + word1.length() + " chars");
System.out.println (word2 + "Has" + word2.length() + " chars");
}
for(int x = 0; x < word1Length; x = x+1) {
if (word1.charAt(x) != word2.charAt(x)) {
count = count + 1;
}}}
System.out.println (count+" different chars");
}
After implementing the knowledge Iv gained from your responses I have ran in to a problem with the last line:
System.out.println (count+" different chars");
It says Error expected however it worked before I added the next part of my assignment which was this:
if (word1Length != word2Length) {
System.out.println ("Words are a diffrent length");
System.out.println (word1 + "Has" + word1.length() + " chars");
System.out.println (word2 + "Has" + word2.length() + " chars");
}

for(int x = 0; x >= length; x = x+1) {
You probably mean
for(int x = 0; x < length; x = x+1) {

Shifting around some code, adding some line breaks and making 2 small tweaks to the logic produces a program that is closer to what you are trying to build.
package arraysandstrings;
import java.util.Scanner;
public class differStrings {
public static void main (String agrs[]){
Scanner scanner = new Scanner (System.in);
System.out.println("Enter a word");
String word1 = scanner.next();
System.out.println("Enter another word");
String word2 = scanner.next();
int count = 0;
int length = word1.length();
for(int x = 0; x < length; x = x+1) {
if (word1.charAt(x) != word2.charAt(x)) {
count = count + 1;
}
}
System.out.println (count+" different chars");
}
}
It looks like in addition to the for loop that #LouisWasserman pointed out you had code that was trying to find characters that are the same.

What you need is a loop which compares the two strings and counts the places where they are not equal.
Your logic counts the number of places where the two characters are the same. You are also printing the count each time the two characters are equal.
What it sounds like you need is a loop that iterates over the characters in the two strings comparing each character and incrementing the count of mis-matched or different characters. Then after getting a count of different characters by comparing all of the characters, you would print out the count of different characters.
So the basics would be: (1) read each of the strings, (2) check that the lengths are the same, (3) if same length then loop over the string comparing each character and incrementing the count of mis-matched characters each time there is a difference, (4) print out the count. If the string lengths are different then just set the count to negative one (-1) and do not bother to compare the two strings.
What would be kind of neat to do is to create a string of underscores and asterisk, in which each matching character position is represented by an underscore and each mis-matching character position is represented by an asterisk or perhaps the string would contain all of the matching characters and the mis-matching characters would be replaced by an asterisk.
Edit: adding example program
The example below is an annotated rewrite of your program. One change that I made was to use a function to perform the counting of the non-matching characters. The function, countNonMatchChars () is a static function in order to work around the object oriented nature of Java. This function is a utility type function and not really part of a class. It should be available to anyone who wants to use it.
Also rather than incrementing variables with the syntax of var = var + 1; I instead use the postincrement operator of ++ as in var++;.
package arraysandstrings;
import java.util.Scanner;
public class so_strings_main {
// function to compare two strings and count the number
// of characters that do not match.
//
// this function returns an integer indicating the number
// of characters that did not match or a negative one if the
// strings are not equal in length.
//
// "john" "john" returns 0
// "john1" "john2" returns 1
// "mary1" "john1" returns 4
// "john" "john1" returns -1 (lengths are not equal)
public static int countNonMatchChars (String s1, String s2)
{
// initialize the count to negative one indicating strings unequal in length
// get the lengths of the two strings to see if any comparison is needed
int count = -1;
int word1Length = s1.length();
int word2Length = s2.length();
if (word1Length == word2Length) {
// the lengths of the two strings are equal so we now do our comparison
// we start count off at zero. as we find unmatched characters, we
// will increment our count. if no unmatched characters found then
// we will return a count of zero.
count = 0;
for(int iLoop = 0; iLoop < word1Length; iLoop++) {
if (s1.charAt(iLoop) != s2.charAt(iLoop)) {
// the characters at this position in the string do not match
// increment our count of non-matching characters
count++;
}
}
}
// return the count of non-matching characters we have found.
return count;
}
public static void main (String agrs[]){
Scanner scanner = new Scanner (System.in);
System.out.println("Count non-matching characters in two strings.");
System.out.println("Enter first word");
String word1 = scanner.next();
System.out.println("Enter second word");
String word2 = scanner.next();
int count = countNonMatchChars (word1, word2);
if (count < 0) {
System.out.println ("Words are a diffrent length");
System.out.println (" " + word1 + " Has " + word1.length() + " chars");
System.out.println (" " + word2 + " Has " + word2.length() + " chars");
} else {
System.out.println (count + " different chars");
}
}
}

Related

Method to check if the string contains certain elements that accepts a parameter String

I am a student and kind of new to Java. For my homework I have to:
Ask the user to input a number (at least 7) using a do while loop.
Using a for loop I am required to ask the user to input that number of words.
Then I have to check if one of the words fulfills the given conditions:
The word must:
Start with an uppercase letter
End with a number
Contain the word "cse".
I am asked to create a method inside some code homework that does a specific task, the method should check all the required conditions, the name of the method should be countTest and it accepts the String as a parameter.
I will show you my code but I don't know how to create this specific method.
Output format
System.out.println("There as a total number of words " + count + " and
the ones that fulfill the condition are: " + condition);
The problem is, I dont know how to create the method or constructor or whatever it is called that calls all of the 3 methods inside it, and then connect that particular method to the main method!
I hope you guys can understand I am new to this, thank you in advance!
public class D6_6 {
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do{
if(number<7){
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while(number<7);
sc.nextLine();
String str;
for(int i =0; i<number; i++){
System.out.println("Type a word");
str = sc.nextLine();
count++;
}
}
public boolean countTest(String str) {
}```
To check if the word start with an uppercase:
You can do that by first selecting the character you want to check by str.charAt(0). This will return a char that is the first letter of the input str.
To check if this char is an uppercase letter, you can easily use char.isUppercase(). This will return a boolean. You have to replace char by the name of the variable were you put the char of str.charAt(0) in.
To check if the last character is a number:
You can do that again by first selecting the last character by str.charAt(str.length()-1), were string.length-1 is the number of the last character.
To check if this character is a number, you can use the ascii table. Every character has it's own number. So if you want to check if your character is between 0 and 9, you can use char >= 48 || char <= 57 (look up in the ascii table). Again, char is the name of the variable were you put the char of str.charAt(str.length()-1) in.
To check if the word contains "cse":
There is a very easy method for that: str.contains("cse") will return a boolean that is true when "cse" is in the word and false when the word does not contain "cse".
I hope it is clear for you now!
I think I did it, thank you guys very much, I appreciate it!
public class D6_6 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do {
if (number < 7) {
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while (number < 7);
sc.nextLine();
String str;
for (int i = 0; i < number; i++) {
System.out.println("Type a word");
str = sc.nextLine();
count++;
if((countTest(str))){
condition++;
}
}
if(count == 0){
System.out.println("No words typed");
} else {
System.out.println("Total number of words typed: " + count + ", which fulfill the condition: "+ condition);
}
}
public static boolean countTest(String str) {
return Character.isUpperCase(str.charAt(0)) && str.charAt(str.length() - 1) >= 48 || str.charAt(str.length() - 1) <= 57 || str.contains("cse");
}
}```

Creating a program that tests for palindrome without building the reversal (Java)

I am trying to create a Java program for my AP Computer Science class that asks the user for a string and tests whether or not the string is a palindrome or not. The teacher specifically told us to not do the project by building the reversal of the string and testing it to see if it matches. I know how to do it while building the reversal but I can't think of another way to do it.
import java.util.*;
public class mondayassignment
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter a String: ");
String s = scan.nextLine();
while(s.indexOf(" ") >= 0)
{
s = s.substring(0, s.indexOf(" ")) +
s.substring(s.indexOf(" ") + 1);
}
System.out.println("Spaces Removed:");
System.out.println(s);
String reverse="";
for(int pos = 0; pos < s.length(); pos++)
{
reverse = s.substring(pos, pos + 1) + reverse ;
}
System.out.println("Reverse Of The String You Inputed Is:" );
System.out.println(reverse);
System.out.println("Testing For Palindrome:");
if (reverse.equals(s))
{
System.out.println(s + " " + "is a palindrome" );
}
else {
System.out.println(s + " " + "is not a palindrome" );
}
}
}
Can someone help me create a code that does it without building the reversal of the string? Many solutions I've found online uses boolean and char but the thing is, is that I haven't learn those yet. I've only learned double int and string. SO would there be a way without using boolean and char? I don't think my teacher wants us using boolean and char either because we have never discussed them.
When you visually confirm whether a word is a palindrome or not, usually you would just check the characters from either end and start moving inwards.
So really that's two steps:
Check the end bits of the char if they're the same. If they aren't, it's not a palindrome, otherwise, next step
Move inwards from both ends, and repeat #1 till there are 1 or 0 characters left to be checked. (Hint: If you can't use chars, maybe try using a single character string :) )
Compare the string char starting from head and tail. If all the letters are equal till the middle of the string it's palindrome.
boolean palindrome(string str){
for(int i = 0 ; i < str.lenght()/2 ; i++) {
if (str.charAt(i) != str.charAt(str.lenght() - i )
return false;
}
return true;
}
package paintadvance;
import java.util.Scanner;
class Palindrome_without_reverse{
public static void main(String[] ishan_vimukthi_is_my_name) {
Scanner scan= new Scanner(System.in);
String string="";
/*while loop to keep running the programme unlit user need it to end*/
while (true) {
System.out.println("Enter string for palindrome check");
string=scan.nextLine();
/*this is for exiting the programme. If needed for user just type
"exit".It's not casesensitive that means "EXIT" is also ok.*/
if (string.equalsIgnoreCase("exit")) {System.out.println("Programme closed"); System.exit(0); }
/*get the length of string to a int variable */
int length=string.length();
/*get mid point of string in eg:- "aasaa" midpoint is letter "s" that means 2 when count from 0 .
We can get it from dividing string length from 2.Because we use int we will get 2 as the answer. */
int midpoint=length/2;
boolean ispalindrome=true;
String x="";
String y="";
/*check length is odd or even eg:- "aasaa" is odd "aassaa" is even*/
if (length%2==1) {
/*if you want to see the method. uncomment this and understand it.
System.out.println("odd string");
System.out.println(string.substring(midpoint,string.length())+" X part");
System.out.println(string.substring(0, midpoint+1)+" Y part");*/
x =string.substring(midpoint,string.length());
y=string.substring(0, midpoint+1);
}else{
/*if you want to see the method. uncomment this and understand it.
System.out.println("even string");
System.out.println(string.substring(midpoint,string.length())+" X part");
System.out.println(string.substring(0, midpoint)+" Y part");*/
x=string.substring(midpoint,string.length());
y=string.substring(0, midpoint);
}
int ylength=y.length()-1;
int ylength_end=y.length();
aa: for (int i = 0; i < x.length(); i++) {
/* by this code we compare each
string part of both x and y strings
in eg:- aasaa x=saa y=aas
we compair 0,1 of x and 2,3 of y
and keep going.this is not a reversal but this is comparing x and y parts
if its not equal we assign ispalindrome false if its equal it will be in true state
*/
if ( !(x.substring(i, i+1).equals( y.substring(ylength--, ylength_end--)))) {
ispalindrome=false;
}
}
/* after for loop We check string is a palindrome or not */
if (ispalindrome) { System.out.println("This is a palindrome");}else{ System.out.println("Not a palindrome");}
}
}
}

Java - Program that checks if the user's serial code format is valid or not

I'm trying to create program that will ask the user to enter serial numbers in a specific format and the program will verify if the codes are valid or not.
The format should be 2 numbers, followed by a dash, 4 numbers, a dot, then 4 numbers and 2 letters (note: letters accepted are only a,b,c).
Example of valid format:
31-0001.2341ac
00-9999.0001cb
If the length of the string is longer/shorter than the format (14 characters total length) it should display invalid. Same thing, if other characters were used it will also say invalid.
This is the code that I have done so far. Im not sure how I can achieve the exact specified format. Hopefully someone can help..
import java.util.Scanner;
public class SerialCheck{
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("How many serial numbers would you like to check: ");
int length = sc.nextInt();
int valid = 0;
String[] sSerials = new String[length];
for (int nCtr = 0; nCtr < length; nCtr++){
System.out.print ("Enter Serial " + (nCtr+1) + ": ");
sSerials[nCtr] = sc.next();
}
System.out.println();
System.out.println("The following were added: ");
for(int nCtr = 0; nCtr < length; nCtr++){
System.out.println(sSerials[nCtr]);
}
System.out.println();
for(int nCtr = 0; nCtr < length; nCtr++){
for (int x = 0; x < sSerials[nCtr].length(); x++){
char c = sSerials[nCtr].charAt(x);
if((sSerials[nCtr].charAt(x)!='a') ||
(sSerials[nCtr].charAt(x)!='b') ||
(sSerials[nCtr].charAt(x)!='c') ||
(sSerials[nCtr].charAt(x)!='-') ||
(sSerials[nCtr].charAt(x)!='.')){
valid--;
}
else{
valid++;
}
}
if (valid < 0 && sSerials[nCtr].length() != 14){
System.out.println("The address is invalid.");
}
else{
System.out.println("The address is valid.");
}
}
}
}
I frequently post answers saying "don't use regular expressions". But in this case: use regular expressions. They are the right tool for this job.
boolean isValid = sSerials[nCtr].matches(
"[0-9]{2}" // Match 2 digits
+ "-" // Then a dash
+ "[0-9]{4}" // Then 4 digits
+ "\\." // Then a dot (which must be escaped)
+ "[0-9]{4}" // Then 4 digits
+ "[abc]{2}" // Then 2 a, b or c.
This regex is split up simply to explain the parts of it. You can write the string literal on one line:
boolean isValid =
sSerials[nCtr].matches("[0-9]{2}-[0-9]{4}\\.[0-9]{4}[abc]{2}");
You can use some websites or utility like regexr.com which helps building you regular expression for required string(Seqial number for your product).
Then use java.util.regex package for identifying them,
The linkjava.util.regex given will expose you all the functions using which you can filter perticular type of string.

How to create a program that uses an array to count vowels?

I am having some trouble creating a program that uses an array to count vowels in names entered by a user. The user should be able to enter up to 1000 names or say "Done" to end the program. Once the user gets to 1000 names or says done, it is supposed to display the total amount of vowels in each name combined.
Here is what I have so far:
import java.util.Scanner;
import java.lang.String;
import java.lang.Math;
public class Countvowels
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
final int LOW ='A';
final int HIGH = 'Z';
int[] letterCounts = new int[HIGH-LOW+1];
String[] word = new String[1000];
char[] wordLetter;
int offset;
System.out.println("Enter a name: ");
for(int letter = 0; letter < wordLetter.length; letter++){
word[letter] = input.nextLine();
wordLetter = word.toCharArray();
}
}
}
Help is much appreciated!
Never mind all that code. You only need one line:
String[] word = new String[1000]; // given this
int vowels = Arrays.toString(word).replaceAll("(?i)[^aeiou]", "").length();
This first converts the array to a string (basically a csv), then replaces all non-vowels (fyi (?i) is the case-insensitive flag) with nothing (ie deleting them), then with only vowels left just take the length.
If you need a total for all vowels #Bohemian has an excellent answer. If you need them seperate it might be easier to do the following:
Just create 1 big string with all the user input.
Then for example when you end up with:
String userInput = 'JohnMaryLisaPeter';
for(int x = 0; x <= userInput.length() - 1; x++) {
if(userInput.charAt(x) == 97)
vowelA++;
else if(userInput.charAt(x) == 101)
vowelE++;
else if(userInput.charAt(x) == 105)
vowelI++;
else if(userInput.charAt(x) == 111)
vowelO++;
else if(userInput.charAt(x) == 117)
vowelU++;
}
System.out.println("There were " + vowelA + " A's in all your names.");
System.out.println("There were " + vowelE + " E's in all your names.");
System.out.println("There were " + vowelI + " I's in all your names.");
System.out.println("There were " + vowelO + " O's in all your names.");
System.out.println("There were " + vowelU + " U's in all your names.");
Three errors I see:
You have the array-of-characters
char[] wordLetter;
in which the vowels will go, yet you're using it as the for-loop termination. There's nothing in the array yet--there is no array at all, just a marker in memory where it will be created--so you are comparing letter against nothingness!
for(int letter = 0; letter < wordLetter.length; letter++){
It should be
for(int letter = 0; letter < [some_number_here]; letter++){
In the for-loop, you are attempting to change the entire array of words to a character array, which makes no sense. Naming the array of words word is confusing you. Try aWords or something.
wordLetter = word.toCharArray();
Fix:
wordLetter = word[letter].toCharArray();
And letter is another bad choice of variable names. Try iIndex.
I hope this helps!

out of bounds error with word count

I'm trying to write my own Java word count program. I know there may already be a method for this, but I'd like to get it work. I'm getting an out of bounds error at line 14. I'm trying to use an input word to count how many times it appears in an input string. So I'm looping up to stringlength - wordlength, but that's where the problem is.
Here is the code:
import java.util.Scanner;
public class wordcount {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print( "Enter word : " );
String word = s.nextLine();
Scanner t = new Scanner(System.in);
System.out.print("Enter string: ");
String string = t.nextLine();
int count = 0;
for (int i = 0; i < string.length()-word.length(); i = i+1){
String substring = string.substring(i,i+word.length());
if (match(substring, word)==true){
count += 1;
}
}
System.out.println("There are "+count+ " repetitions of the word "+word);
}
public static boolean match(String string1, String string2){
for (int i=0; i<string1.length(); i+=1){
if (string1.charAt(i)!=string2.charAt(i)){
return false;
}
}
return true;
}
}
First of all, two Scanners are not necessary, you can do many inputs with the same Scanner object.
Also, this if condition
if (match(substring, word) == true)
can be rewritten like
if (math(substring, word))
I would also recommend you to use i++ to increase the loop variable. Is not strictly necessary but is "almost" a convention. You can read more about that here.
Now, about theIndexOutOfBoundsException, I've tested the code and I don't find any input samples to get it.
Besides, there is an issue, you are missing one iteration in the for:
for (int i = 0; i < string.length() - word.length() + 1; i++) { // Add '+ 1'
String substring = string.substring(i, i + word.length());
// System.out.println(substring);
if (match(substring, word)) {
count++;
}
}
You can test it by putting a print statement inside the loop, to print each substring.
I'm not getting an out of bounds error, can you tell me what values you were using for word and string?
I have identified a bug with your program. If word is equal to string, it still returns count 0. I suggest adding one more iteration and using regionMatches instead. RegionMatches makes your match method obsolete and will return false if word.length() + i is equal or greater than string.length(), avoiding out of bounds issues.
As you can see I also moved the calculations to a seperate method, this will make your code more readable and testable.
And as Christian pointed out; you indeed do only need one Scanner object. I've adapted the code below to reflect it.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter word : ");
String word = sc.nextLine();
System.out.print("Enter string: ");
String string = sc.nextLine();
int count = calculateWordCount(word, string);
System.out.println("There are " + count + " repetitions of the word " + word);
}
private static int calculateWordCount(String word, String string) {
int count = 0;
for (int i = 0; i < string.length() - word.length() + 1; i++) {
if (word.regionMatches(0, string, i, word.length())) {
count++;
}
}
return count;
}

Categories

Resources