Here is the problem that I'm working on.
We have to ask the user to enter a string, and then enter a character (any character would be fine). And then count the number of times that character appears in the scanner.
I cannot figure out how to add character to scanner. We haven't done arrays yet so I don't wanna go there but this is what I have done so far:
import java.util.Scanner;
public class Counter {
public static void main (String args[]){
String a;
char b;
int count;
int i;
Scanner s = new Scanner (System.in);
System.out.println("Enter a string");
a = s.nextLine();
System.out.println("Enter a character");
b = s.next().charAt(0);
count = 0;
for (i = 0; i <= a.length(); i++){
if (b == s.next().charAt(b)){
count += 1;
System.out.println(" Number of times the character appears in the string is " + count);
else if{
System.out.println("The character appears 0 times in this string");
}
}
}
I know this is incorrect but I cannot figure this out right now.
Any help would be highly appreciated.
To verify your inputs [String, char] use a while loop for getting the character from the user. Basically you will check whether user enters a string of length 1 for character input.
Here is the compiling and running version of your code:
import java.util.Scanner;
public class Counter
{
public static void main ( String args[] )
{
String a = "", b = "";
Scanner s = new Scanner( System.in );
System.out.println( "Enter a string: " );
a = s.nextLine();
while ( b.length() != 1 )
{
System.out.println( "Enter a single character: " );
b = s.next();
}
int counter = 0;
for ( int i = 0; i < a.length(); i++ )
{
if ( b.equals(a.charAt( i ) +"") )
counter++;
}
System.out.println( "Number of occurrences: " + counter );
}
}
First, the for loop condition should be changed to :
for (i = 0; i < a.length(); i++)
The index starts from 0, but when you count length you start from 1. Therefore you don't need '='.
Second, in the for loop, you only need to do one thing: compare each character of a with b:
if (b == a.charAt(i))
count += 1;
Here, compared with the other solution, char is cheaper than String to be compared.
Third, after the for loop, output depends on count:
if (count > 0)
System.out.println(" Number of times the character appears in the string is "
+ count);
else // must be count == 0
System.out.println("The character appears 0 times in this string");
Related
The following Java program is supposed to manipulate a string input by the user in such a way that the user will decide which character needs to be replaced with another and just the last character from the string should be replaced. Example if the user enters the string "OYOVESTER" and decides to replace "O" with "L", the program should output the following result: "OYLVESTER" (notice that only the last "O" was replaced with "L")
NOTE: YOU CANNOT USE BREAK COMMAND TO STOP THE LOOP. IT IS PROHIBITED.
import java.util.Scanner;
public class StringFun {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
String inString = keyboard.nextLine();
String outString = "";
//Replace Last
System.out.println("Enter the character to replace");
char oldCharF = keyboard.next().charAt(0);
System.out.println("Enter the new character");
char newCharF = keyboard.next().charAt(0);
int count = 0; // variable that tracks number of letter occurrences
for(int index = inString.length() - 1;index >= 0;index--) {
if(inString.charAt(index) == oldCharF && count < 1){
outString = newCharF + outString;
outString = outString + inString.substring(0,index);
count++;
}
if (count < 1) {
outString = outString + inString.charAt(index);
}
}
System.out.print("The new sentence is: "+outString);
}
}
I keep getting the following output which is incorrect:
Enter the string to be manipulated
OYOVESTER
Enter the character to replace
O
Enter the new character
L
The new sentence is: LRETSEVOY
There are many simpler ways to achieve your requirement but I hope you have to demonstrate this with loops (without breaks)
Then you can use some thing like this :
boolean skip = false;
for (int index = inString.length() - 1; index >= 0; index--) {
if (!skip && inString.charAt(index) == oldCharF) {
outString = newCharF + outString;
skip = true;
}
else {
outString = inString.charAt(index) + outString;
}
}
PS : Using String concatenation inside loops is not recommended since
every String concatenation copies the whole String, usually it is preferable to
replace it with explicit calls to StringBuilder.append() or StringBuffer.append()
No break command seems like a weird condition. You could just a boolean value, and other methods, to break the loop when you need. Why not do something like this?
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
String word = keyboard.nextLine();
//Replace Last
System.out.println("Enter the character to replace");
char oldCharF = keyboard.next().charAt(0);
System.out.println("Enter the new character");
char newCharF = keyboard.next().charAt(0);
int index = word.lastIndexOf(oldCharF);
if(index > 1){
word = word.substring(0,index) + newCharF + word.substring(index+1);
}
System.out.println("The new sentence is: " + word);
}
I wanted to make a program in which only repeats words that has 3 of the same letters back to back. eg the mooonkey raaan through the mounnntains. the program should only repeat mooonkey, raaan
public class Triplets2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("write a sentence");
String in = input.nextLine();
String [] sentence = in.split(" ");
for (int i = 0; i < sentence.length; i++) {
char [] word = sentence[i].toCharArray();
int counter =0;
for (int s = 0; s < word.length; s++) {
char letter = word[s];
for (int x = 0; x<word.length; x++) {
if (letter == word[x]) {
counter++;
}
else {
counter = 0;
}
}
}
if (counter >=3) {
System.out.print(sentence[i] + ", ");
}
}
}
the program instead just repeats nothing.
Your code is almost correct, the only logical error you made is inside your inner loop you keep resetting your counter variable as soon as you find a letter that is different:
if (letter == word[x]) {
counter++;
} else {
counter = 0;
}
So when you iterate over a word like "raaan" your counter will reset when it reaches the very end of the String, because "n" only exists once.
What this means is that you will only be able to detect words that have 3 consecutive letters at the very end (like "Hooo").
The solution is simple:
Once you found 3 consecutive letters in a word you can just stop iterating and checking the rest of your word. At that point you already know that it fits your criteria:
if (letter == word[x]) {
counter++;
if(counter >= 3) break; // stop inner loop checking once we found 3 letters
} else {
counter = 0;
}
Since you are looking for consecutive letters you want to start at char i and then compare the char at i to char at i+1 and at i+2. If they are all equal then we have a match and can continue.
You can simplify the whole function such as:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("write a sentence");
String in = input.nextLine();
List<String> tripleLetter = new ArrayList<>();
for (String s : in.split(" ")) {
char[] word = s.toCharArray();
for (int i = 0; i < word.length - 2; i++) {
if ((word[i] == word[i+1]) && (word[i] == word[i+2])) {
tripleLetter.add(s);
break;
}
}
}
System.out.println(tripleLetter.stream().collect(Collectors.joining(", ")));
}
Allow me to suggest a solution that differs slightly from yours and doesn't use a counter.
Scanner input = new Scanner(System.in);
System.out.println("write a sentence");
String in = input.nextLine();
String[] sentence = in.split(" ");
for (int i = 0; i < sentence.length; i++) {
char[] word = sentence[i].toCharArray();
for (int s = 0; s < word.length - 2; s++) {
if (word[s] == word[s + 1] && word[s] == word[s + 2]) {
System.out.print(sentence[i] + ", ");
break;
}
}
}
Check whether the current letter, in the current word, is the same as the next letter and the same as the letter after the next letter. If the condition holds, then print the current word and proceed to the next word in the sentence.
Well, if you're just looking for a shorter version of doing this then try this.
first, split the sentence on one or more white space characters (you should be doing that regardless).
stream the array and filter on a single character, followed by the same two characters via a back reference to the capture group (see regular expressions for that).
And print them.
String str =
"Thiiis is aaaa tesssst of finding worrrrds with more than threeeeee letteeeeers";
Arrays.stream(str.split("\\s+"))
.filter(s -> s.matches(".*(.)\\1\\1.*"))
.forEach(System.out::println);
Prints
Thiiis
aaaa
tesssst
worrrrds
threeeeee
letteeeeers
For example i want to find how many times 1 repeated in number 123900148
It must be write 2 times but i get wrong values for everytime
Scanner input = new Scanner(System.in);
#author Başar Ballıöz
int counter = 0;
int repeat;
int tmp;
System.out.print("Enter A Number: ");
tmp = input.nextInt();
String number = Integer.toString(tmp);
System.out.print("Enter A Number You Want To Find: ");
repeat = input.nextInt();
for (int i = 0; i < number.length() - 1 ; i++) {
if (number.substring(i , i+1).equals(repeat))
counter++;
}
System.out.println(repeat + " number " + counter + " repeated.");
i would like to see my output like:
number : 134211
number i want to find how many times repeated: 1
your number has repeated 3 times
You are comparing a String (returned by number.substring(i , i+1) to an Integer, so of course it will always return false.
Either compare two ints or two Strings. Since you are essentially comparing two digits, comparing ints would be more efficient.
for (int i = 0; i < number.length(); i++) {
if (Character.getNumericValue(number.charAt(i)) == repeat) {
counter++;
}
}
Scanner input = new Scanner(System.in);
int counter = 0;
int repeat;
int tmp;
System.out.print("Enter A Number: ");
tmp = input.nextInt();
String number = Integer.toString(tmp);
System.out.print("Enter A Number You Want To Find: ");
repeat = input.nextInt();
while (tmp > 0) {
if (tmp % 10 == repeat) {
counter++;
}
tmp = tmp/10;
}
System.out.println(number + " number " + counter + " repeated.");
You're comparing a String against an Integer via equals hence you're not getting the expected result. instead convert the integer to a string prior to comparison:
if (number.substring(i , i+1).equals(String.valueOf(repeat)))
Further, you could cache the result of String.valueOf(repeat) into a variable before the for loop to prevent a string object construction in each iteration of the loop.
Try this. I added some helpful output so you can see how it's indexed.
import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
public class CountChars {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter A String: ");
Map<String, Integer> map = indexString(input.nextLine());
while (true) {
System.out.print("Enter A Character You Want To Count (ENTER to exit): ");
String repeat = input.nextLine();
if (repeat == null || repeat.isEmpty()) {
break;
}
System.out.println(String.format("'%s' was repeated %d time(s).", repeat, (map.containsKey(repeat)) ? map.get(repeat):Integer.valueOf(0)));
}
}
private static Map<String, Integer> indexString(String s) {
Map<String, Integer> map = new HashMap<>();
System.out.println(String.format("'%s' has %d characters. Indexing now.", s, s.length()));
for (int i = 0; i < s.length() ; i++) {
String c = String.valueOf(s.charAt(i));
if (!map.containsKey(c)) {
map.put(c, 0);
System.out.println(String.format("Indexing %s", c));
}
System.out.print(String.format("Incrementing '%s' from %d ", c, map.get(c)));
map.put(c, map.get(c) + 1);
System.out.println(String.format("to %d.", map.get(c)));
}
return map;
}
}
I have an assignment, it looks pretty easy however I cannot figure it out how to solve it.
It says:
a) Ask the user: How many words/sentences do you want to write (at
least 5) ? (Use while loop)
b) Use for loop to make the user write the words/sentences
c) After the user's written the words/sentences, output which
word/sentence comes last alphabetically (using .compareTo() method )
This is what I came up with:
import java.util.Scanner;
import java.lang.String;
import java.util.Arrays;
public class LastString {
public static void main (String [] args){
Scanner input = new Scanner (System.in);
final short MIN_NUM = 2;
int num = 0;
int count = 0;
String [] sentence = new String [0];
String last = "";
while (num < MIN_NUM){
System.out.println("How many words/sentences do you want to put? " + "\t\t\t\t\t\t\t\t --- at least " + MIN_NUM);
num = input.nextInt();
sentence = new String [num];
}
for (int i = 0; i < num ; i++ ) {
System.out.println("\nWrite a word/sentence" + "\t\t\t\t\t\t\t\t\t --- (Time: " + (i+1) + " )");
sentence [i] = input.nextLine();
System.out.println("The word/sentence is: " + sentence[i]);
}
int i = 0;
int max;
for (i=0;i<num-1 ;i++ ) {
if(sentence[i].compareTo(sentence[i+1]) > 0){
last = sentence[i];
count ++;
}else if (sentence[i].compareTo(sentence[i+1]) < 0) {
last = sentence[i+1];
count++;
}
}
System.out.println("\n\n------------" +
"\nLast word/sentence is: " + last);
System.out.println(Arrays.toString(sentence));
}
}
I compiles and runs. I have two problems:
nextLine >>> it is skiping the first Sentence
I don't know how to make the algorithm to calculate which word/sentence has the biggest value or, using the compareTo() method which word/sentence has the value > 0 compared to each and every other value on the array.
Thank you.
Answer to Q1 : num = input.nextInt(); takes a number as the input but doesn't also consume the new-line, and hence the nextLine consumes the empty new line ... you could use input.nextLine also to get the first number instead of num = input.nextInt(); by reading a line, then parsing the int value as num = Integer.parseInt(input.nextLine());
Answer to Q2 :
You re-set the value of last everytime but you don't compare the value of the next biggest candidate with the last before re-assigning last ...
for example, look at the following :
for (int i = 0; i < num - 1; i++) {
String thisLast = "";
if (sentence[i].compareTo(sentence[i + 1]) > 0) {
thisLast = sentence[i];
count++;
} else if (sentence[i].compareTo(sentence[i + 1]) < 0) {
thisLast = sentence[i + 1];
count++;
}
if (thisLast.compareTo(last) > 0)
last = thisLast;
}
it will solve your problem....
int count = 0;
String [] sentence = new String[6];
String last = "";
for (int i = 0; i < num ; i++ ) {
System.out.println("\nWrite a word/sentence" + "\t\t\t\t\t\t\t\t\t --- (Time: " + (i+1) + " )");
sentence [i] = input.nextLine();
count++;
if(count >= 2){
if(sentence[i].compareTo(last) > 0){
last = sentence [i] ;
}
}else{
last = sentence [i];
}
System.out.println("The word/sentence is: " + sentence[i]);
}
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");
}
}
}