Write a program that asks the user to enter two Strings, and prints the number of times that the second String appears within the first String. For example, if the first String is "banana" and the second is "an", the program prints 2.
Below is my code so far
public class Assignment4 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner answer = new Scanner(System.in);
//Prompt the user to enter a string
System.out.println("Enter a word:");
String input = answer.nextLine();
//Ask the user to enter a second String
//look at index method of string
System.out.println("Enter another word:");
String input2nd = answer.nextLine();
int counter = 0;
for(int i=0; i<input.length(); i++) {
if(input.charAt(i) == input2nd.charAt(0)) {
counter++;
}
}
System.out.println(input2nd + " appears " + counter + " times.");
When I type banana into first string, and second string is "an", the only thing come up is number 3, and it is for character a which appear 3 time, but not two as it suppose to only be 2 "an"
Consider this trick I learned years ago:
replace the searched word in the original word by emptychars...
get the diff between the length of both... searched chars and the original with replaced
divide that by the len of the searched word...
private static void searchString() {
Scanner answer = new Scanner(System.in);
// Prompt the user to enter a string
System.out.println("Enter a word:");
String input = answer.nextLine();
// Ask the user to enter a second String
// look at index method of string
System.out.println("Enter another word:");
String input2nd = answer.nextLine();
String a = input.replace(input2nd, "");
int counter = (input.length() - a.length()) / input2nd.length();
System.out.println(input2nd + " appears " + counter + " times.");
}
with the input banana and an will print 2
Related
I try to check if characters in a firstname String contain at least 1 digit, if yes ask to the user to input it again and then going back to the loop and check again but with a GoTo break it only works the first time and won't loop it again. Oh and I do this from a method with a String array of more than only a first name in it. Isn't the break GoTo supposed to bring me back to my label and then do the loop over again looking for a digit?
public static void main(String[] args) {
infoInputGathering();
}
public static String[] infoInputGathering(){
String[] infos = new String[3]; // Declaration of the infos String array
boolean isStringOnly;
char[] characterChecker;
Scanner input = new Scanner(System.in); // Creation of the Scanner object input
// Asking the user to input their first name and stores it in a String Array info[0]
System.out.print("Enter your first name: ");
infos[0] = input.next();
characterChecker = infos[0].toCharArray();
firstname:
for (int c = 0 ; c<=characterChecker.length ; ++c ) {
if (Character.isDigit(characterChecker[c])) {
System.out.println("A first name should not contain any number...");
System.out.print("Enter your first name without a number: ");
infos[0] = input.next();
characterChecker = infos[0].toCharArray();
Break firstname;
}
}
Final Full Code I came up with with Ali's help on this part
import java.util.Scanner;
import java.util.ArrayList;
public class InfiniteInfoGatheringUntilStop {
public static void main(String[] args) {
int iterationsCounter = 0; // Declares/Initiate a counter for the loops
Scanner input = new Scanner(System.in); // Creation of the Scanner object input
ArrayList<String> names = new ArrayList<String>(); // Creates an ArrayList for the names inputs
ArrayList<String> birth = new ArrayList<String>(); // Creates an ArrayList for the date of birth inputs
ArrayList<String> gpa = new ArrayList<String>(); // Creates an ArrayList for the GPA inputs
while(true){ // Always true loop unless break out on if conditions
System.out.print("Enter your name: ");
names.add(input.next());
//Code to check if there are numerical character in the String of the listArray inputted
char[] characterChecker = names.get(iterationsCounter).toCharArray(); //Declare and initiates an array of character from the ArrayList names(iterationsCounter)
int c = 0;
while(true){ // Loop to check every character and asks for a retype if detects one character as numerical
if(Character.isDigit(characterChecker[c])){
System.out.println("A first name should not contain any number...");
System.out.print("Enter your first name without a number: ");
names.set(iterationsCounter,input.next());
characterChecker = names.get(iterationsCounter).toCharArray();
c = 0;
}
else {
c++;
}
if(c == characterChecker.length){
break;
}
}
if(names.get(iterationsCounter).equalsIgnoreCase("stop")){ //Checks if stop has been typed, breaks in that case but erases previous ArrayLists of this cycle
names.remove(iterationsCounter);
break;
}
System.out.print("Enter your date of birth in this format AAAAmmdd: ");
birth.add(input.next());
characterChecker = birth.get(iterationsCounter).toCharArray(); //Declare and initiates an array of character from the ArrayList names(iterationsCounter)
c = 0;
while(true){ // Loop to check every character and asks for a retype if detects one character as letter
if(characterChecker.length != 8){ // Checks for a maximum length of 8 characters
System.out.println("A date of birth in the right format (AAAAmmdd) please...");
System.out.print("Reenter your date of birth again (AAAAmmdd): ");
birth.set(iterationsCounter,input.next());
characterChecker = birth.get(iterationsCounter).toCharArray();
}
else if(Character.isLetter(characterChecker[c])){ //checkes if there are letters in the characters
System.out.println("A date of birth in the right format (AAAAmmdd) please...");
System.out.print("Reenter your date of birth again (AAAAmmdd): ");
birth.set(iterationsCounter,input.next());
characterChecker = birth.get(iterationsCounter).toCharArray();
c = 0;
}
else {
c++;
}
if(c == characterChecker.length){ //breaks when c = to the length meaning all characters have been checked through the loop
break;
}
}
if(birth.get(iterationsCounter).equalsIgnoreCase("stop")){ //Checks if stop has been typed, breaks in that case but erases previous ArrayLists of this cycle
names.remove(iterationsCounter);
birth.remove(iterationsCounter);
break;
}
System.out.print("Enter your GPA in 0.0 format: ");
gpa.add(input.next());
characterChecker = gpa.get(iterationsCounter).toCharArray(); //Declare and initiates an array of character from the ArrayList names(iterationsCounter)
c = 0;
while(true){ // Loop to check every character and asks for a retype if detects one character as letter
if(characterChecker.length != 3){ // Checkes for a maximum length of 8 characters
System.out.println("A GPA in the right format please (0.0)...");
System.out.print("Reenter your GPA please: ");
gpa.set(iterationsCounter,input.next());
characterChecker = gpa.get(iterationsCounter).toCharArray();
}
else if(Character.isLetter(characterChecker[c])){ //checks if there are digits in the characters
System.out.println("A GPA in the right format please (0.0)...");
System.out.print("Reenter your GPA: ");
gpa.set(iterationsCounter,input.next());
characterChecker = gpa.get(iterationsCounter).toCharArray();
c = 0;
}
else {
c++;
}
if(c == characterChecker.length){ //breaks when c = to the length meaning all characters have been checked through the loop
break;
}
}
if(gpa.get(iterationsCounter).equalsIgnoreCase("stop")){ //Checks if stop has been typed, breaks in that case but erases previous ArrayLists of this cycle
names.remove(iterationsCounter);
birth.remove(iterationsCounter);
gpa.remove(iterationsCounter);
break;
}
iterationsCounter++; // Incrementes the counter if a full loop is done
}
// Prints the results
System.out.println("Number of valid inputs before you got exhausted: " + iterationsCounter);
System.out.println("====================================================================================");
//A loop to print the content of the 3 ListArrays
for(int arrayLoc = 0; arrayLoc < iterationsCounter; arrayLoc++){
System.out.println((arrayLoc+1) + "-\t" + names.get(arrayLoc) +
"\t\t" + birth.get(arrayLoc) +
"\t\t" + gpa.get(arrayLoc));
}
}
}
You can write your code with while loop like this:
import java.util.Scanner;
public class Test{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] infos = new String[3];
char[] characterChecker;
System.out.print("Enter your first name: ");
infos[0] = input.next();
characterChecker = infos[0].toCharArray();
int c = 0;
while(true){
if (Character.isDigit(characterChecker[c])){
System.out.println("A first name should not contain any number...");
System.out.print("Enter your first name without a number: ");
infos[0] = input.next();
characterChecker = infos[0].toCharArray();
c = 0;
}
else
c++;
if(c == characterChecker.length)
break;
}
System.out.println("Correct Name");
}
}
If c is equal to characterChecker.length, ie in the name, there is no number, then it is correct and we break loop and print Correct Name.
I'm trying to figure out if I can count the characters of each token and display that information such as:
day is tokenized and my output would be: "Day has 3 characters." and continue to do that for each token.
My last loop to print out the # of characters in each token never prints:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> tokenizedInput = new ArrayList<>();
String sentenceRetrieved;
// getting the sentence from the user
System.out.println("Please type a sentence containing at least 4 words, with a maximum of 8 words: ");
sentenceRetrieved = sc.nextLine();
StringTokenizer strTokenizer = new StringTokenizer(sentenceRetrieved);
// checking to ensure the string has 4-8 words
while (strTokenizer.hasMoreTokens()) {
if (strTokenizer.countTokens() > 8) {
System.out.println("Please re-enter a sentence with at least 4 words, and a maximum of 8");
break;
} else {
while (strTokenizer.hasMoreTokens()) {
tokenizedInput.add(strTokenizer.nextToken());
}
System.out.println("Thank you.");
break;
}
}
// printing out the sentence
System.out.println("You entered: ");
System.out.println(sentenceRetrieved);
// print out each word given
System.out.println("Each word in your sentence is: " + tokenizedInput);
// count the characters in each word
// doesn't seem to run
int totalLength = 0;
while (strTokenizer.hasMoreTokens()) {
String token;
token = sentenceRetrieved;
token = strTokenizer.nextToken();
totalLength += token.length();
System.out.println("Word: " + token + " Length:" + token.length());
}
}
}
Example of Console:
Please type a sentence containing at least 4 words, with a maximum of 8 words:
Hello there this is a test
Thank you.
You entered:
Hello there this is a test
Each word in your sentence is: [Hello, there, this, is, a, test]
First off, I have added the necessary imports and built a class around this main method. This should compile.
import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;
public class SOQ_20200913_1
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> tokenizedInput = new ArrayList<>();
String sentenceRetrieved;
// getting the sentence from the user
System.out.println("Please type a sentence containing at least 4 words, with a maximum of 8 words: ");
sentenceRetrieved = sc.nextLine();
StringTokenizer strTokenizer = new StringTokenizer(sentenceRetrieved);
// checking to ensure the string has 4-8 words
while (strTokenizer.hasMoreTokens()) {
if (strTokenizer.countTokens() > 8) {
System.out.println("Please re-enter a sentence with at least 4 words, and a maximum of 8");
break;
} else {
while (strTokenizer.hasMoreTokens()) {
tokenizedInput.add(strTokenizer.nextToken());
}
System.out.println("Thank you.");
break;
}
}
// printing out the sentence
System.out.println("You entered: ");
System.out.println(sentenceRetrieved);
// print out each word given
System.out.println("Each word in your sentence is: " + tokenizedInput);
// count the characters in each word
// doesn't seem to run
int totalLength = 0;
while (strTokenizer.hasMoreTokens()) {
String token;
token = sentenceRetrieved;
token = strTokenizer.nextToken();
totalLength += token.length();
System.out.println("Word: " + token + " Length:" + token.length());
}
}
}
Next, let's look at this working example. It seems like everything up until your final while loop (the one that counts character length) works just fine. But if you notice, the while loop before the final one will continue looping until it has no more tokens to fetch. So, after it has finished gathering all of the tokens and has no more tokens to gather, you try and create the final while loop, asking it to gather more tokens. It would not have reached the while loop until it ran out of tokens to gather!
Finally, in order to solve this, you can simply go through the list that you added to in the second to last while loop, and simply cycle through that for your final loop!
For example:
int totalLength = 0;
for (String each : tokenizedInput) {
totalLength += each.length();
System.out.println("Word: " + each + " Length:" + each.length());
}
I want to print a letter instead of the index position using the indexOf(); method.
The requirement is that: Inputs a second string from the user. Outputs the character after the first instance of the string in the phrase. If the string is not in the phrase, outputs a statement to that effect. For example, the input is 3, upside down, d. The output should be "e", I got part of it working where it inputs an integer rather than a string of that particular position. How would I output a string?
else if (option == 3){
int first = 0;
String letter = keyboard.next();
first = phrase.indexOf(letter,1);
if (first == -1){
System.out.print("'"+letter+"' is not in '"+phrase+"'");
}
else {
System.out.print(first + 1);
}
}
String.charAt(index)
You can access a single character, or a letter, by caling método charAt() from String class
Example
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String phrase = keyboard.nextLine();
char firstLetter = phrase.charAt(0);
System.out.println("First Letter : " + firstLetter);
}
So, running this code, assuming the input is StackOverFlow, the output will be S
In your code I think doing the follow will work:
Your Code
String letter = keyboard.next();
first = letter.charAt(0);
That might help!
Based on those comments
So, what you want is print the first letter based on a letter the user
has input? For example, for the word Keyboard, and user inputs letter
'a' the first letter might be 'R'. Is that it? – Guerino Rodella
Yes, I have to combine both the indexOf(): method and the charAt():
method – Hussain123
The idea is get next letter based on user input letter.
I'm not sure I wunderstood it, but this is my shot
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String phrase = "keyboard";
String userInput = keyboard.nextLine();
boolean notContainsInputValue = !phrase.contains(userInput);
if (notContainsInputValue) {
System.out.println("The input value doesn't exists");
return;
}
char firstLetter = userInput.charAt(0);
int desiredIndex = 0;
for (int i = 0; i < phrase.length(); i++) {
if (phrase.charAt(i) == firstLetter) {
desiredIndex = i;
break;
}
}
System.out.println("The index for your input letter is: " + desiredIndex);
System.out.println("Next letter based on input value is: " + phrase.charAt(desiredIndex + 1));
}
The Output
The index for your input letter is: 5
Next letter based on input value is: r
Hope that helps you.
Im writing a program that first takes input from the user as an int then constructs an array that the user then types in individual characters that builds a string from that. i've written some code but I've come up with a form of writer's block and i don't know where to go from here. any help is greatly appreciated.
EDIT: im stuck on getting the string from the input into the array im getting an error where a method is not applicable. ill make in the code where the error is happening.
Example:
How many strings? 2
Enter string #1:
Enter an alphabetic string followed by enter: t
Enter an alphabetic string followed by enter: e
Enter an alphabetic string followed by enter: s
Enter an alphabetic string followed by enter: t
Enter an alphabetic string followed by enter: %
Enter string #2:
Enter an alphabetic string followed by enter: one
Enter an alphabetic string followed by enter: two
The strings you entered are:
test onetwo
code is below:
package workfiles;
//George Flamburis
import java.util.*;
public class Hw3 {
private static Scanner numScan;
public static void main(String[] args) {
int numstring=0;
numScan = new Scanner(System.in);
while (numstring <= 0 ){
System.out.print("How many strings? ");
numstring = numScan.nextInt();
if (numstring<1){
System.out.print("Please enter a positive (> 0) number.");
}
}
String[] stringarray = new String[numstring];
for (int i = 0; i < numstring; i++) {
//ERROR HAPPENING IN THIS CODE BELOW!!!
stringarray[i] = inputAlphaString();
}
numScan.close();
}
public static String inputAlphaString(Scanner aScan) {
Scanner strScan = new Scanner(System.in);
String t = "a";
String hold = "";
while(t.matches("[a-zA-Z]+")){
System.out.println("Enter an alphabetic string followed by enter: ");
t = strScan.nextLine();
hold = hold + t;
}
strScan.close();
return hold;
}
//added [] into the method name and int to i
public static void printSArray(String[] sArray) {
for (int i = 0; i <= sArray.length; i++)
System.out.print(sArray[i] + " ");
System.out.println();
}
}
I was hoping that SO could help me with my issue. I have this code:
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.print("Enter a string:\t");
String word = scanner.nextLine();
System.out.print("Enter a character:\t");
String character = scanner.nextLine();
char charVar = 0;
if (character.length() > 1) {
System.err.println("Please input only one character.");
} else {
charVar = character.charAt(0);
}
int count = 0;
for (char x : word.toCharArray()) {
if (x == charVar) {
count++;
}
}
System.out.println("Character " + charVar + " appears " + count +
(count == 1 ? " time" : " times"));
}
So this code asks the user to enter a string, then it asks the user to enter a character, the program will then tell the user how many times that specific character appears. My problem is that I need to convert this code so it will still ask the user for the string, but wont ask for a character. It will instead ask for the user to enter a number. The program will then show what character is at that position in the string. Example: lets say they enter "string" and then 2 for the number, the program will display the character "r". So my question is basically if any one can give me an idea as how to accomplish this. Any help would be great.
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.print("Enter a string:\t");
String word = scanner.nextLine();
System.out.print("Enter an integer:\t");
int index = scanner.nextInt();
System.out.println("Character at position " + index + ": " + word.charAt(index));
}