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));
}
Related
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 am quite new to programming and I am writing this code to count a string (length) to a point when I encounter a space. The aim is - when the user enters his/her name AND surname, the program should split the name from surname and count how many letters/characters were there in the name (and surname).
My code doesn't seem to reach/execute the "if-statement", if I enter two strings (name & surname) separated by space (output: Your name is: (empty space) and it has 0 letters. However, if I enter only one string, the if-statement, it gets executed.
What I am doing wrong?
My example code:
public class Initials {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String nameAndSurname, nameOnly;
int c = 0, count = 0;
System.out.println("Enter your full name please:");
nameAndSurname = scan.nextLine();
int space = nameAndSurname.indexOf(' ');
for(int x = 0; x<=nameAndSurname.length()-1; x++) {
c++;
if(nameAndSurname.indexOf(x) == space) //if there is a space
{
count = c; //how many characters/letters was there before space
System.out.println(count);
}
}
nameOnly = nameAndSurname.substring(0, count);
System.out.println("Your name is: " + nameOnly.toUpperCase() + " and it has " + count + " letters");
scan.close();
}
Why bother with all that code? Just skip the for-loop, have an
if (space != -1) nameOnly = nameAndSurname.substring(0,space);
and if you really want to know the amount of letters, it is
space+1
No need for all that complicated stuff.
if(nameAndSurname.indexOf(x) == space)
This line isn't doing what you think it is doing.
It's getting a char (character) from the index of x, and comparing it to the value of space. Space is an integer, so you are comparing the character at position x to the integer position of the first space. In this case, the letter at position x is cast into an integer, and then compared to the actual number value of the first space!
To fix the program, replace your entire if statement with this.
if (nameAndSurname.charAt(x) == ' ') //if there is a space
{
count = c-1; //how many characters/letters was there before space
System.out.println(count);
}
Extra:
Since the way you've solved this problem is a bit overkill, I've posted another solution below which solves it in a way that is easier to read. Also it won't break if you put in more or less than 1 space.
Scanner scan = new Scanner(System.in);
String nameAndSurname;
System.out.println("Enter your full name please:");
nameAndSurname = scan.nextLine().trim();
int indexOfFirstSpace = nameAndSurname.indexOf(' ');
if (indexOfFirstSpace > -1) {
String firstName = nameAndSurname.substring(0, indexOfFirstSpace);
System.out.println("Your first name is " + firstName.toUpperCase());
System.out.println("It is " + firstName.length() + " characters long.");
}
You can verify if your string has space before start the loop, something like this:
public class Initials {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String nameAndSurname, nameOnly;
int c = 0, count = 0;
System.out.println("Enter your full name please:");
nameAndSurname = scan.nextLine();
int space = nameAndSurname.indexOf(' ');
if(space == -1) {
System.out.println("Your name has no spaces");
} else {
for(int x = 0; x<nameAndSurname.length(); x++) {
c++;
if(nameAndSurname.indexOf(x) == space) //if there is a space
{
count = c; //how many characters/letters was there before space
System.out.println(count);
}
}
nameOnly = nameAndSurname.substring(0, count);
System.out.println("Your name is: " + nameOnly.toUpperCase() + " and it has " + count + " letters");
}
scan.close();
}
I am stumped on how to go about completing this. The script needs to Ask the user for a sentence, tell them the length, return the character at that index, than ask them for a character and give the first location it appears. I just cant figure out how to use the numerical input to find return the character at that index. (I know its probably a simple answer).Everything else works.
public class Sentence
{
Scanner scan = new Scanner (System.in);
int sentlength;
int letterenter;
int lowerinput;
int letterloc;
String enterletter;
public void sentence()
{
System.out.print("Please enter a sentence");
String originalsent = scan.nextLine();
sentlength=originalsent.length();
System.out.println("The sentence is "+sentlength+" charecters long");
System.out.println("Please enter a number less than the length of the sentence");
lowerinput = scan.nextInt();
System.out.println("Please enter a charecter");
enterletter = scan.next();
letterloc = originalsent.indexOf(""+enterletter+"");
System.out.println(""+letterloc+"");
}
public static void main(String[] args)
{
Sentence worksheet= new Sentence();
worksheet.sentence();
}
}
I believe you are looking for something like this from your question
System.out.print("Please enter a sentence: ");
String originalsent = scan.nextLine();
sentlength=originalsent.length();
System.out.println("The sentence is "+ sentlength +" characters long");
System.out.println("Please enter a number less than the length of the sentence: ");
lowerinput = scan.nextInt();
System.out.println("The character at index " + lowerinput + " is " + originalsent.charAt(lowerinput));
System.out.println("Please enter a character: ");
enterletter = scan.next();
System.out.println("The first index " + enterletter + " shows up is at " + originalsent.indexOf(enterletter));
When run outputs the following
Please enter a sentence: the cow flew over the moon
The sentence is 26 charecters long
Please enter a number less than the length of the sentence:
5
The character at index 5 is o
Please enter a charecter:
o
The first indext o shows up is at 5
It's very easy :
System.out.println(originalsent.charAt(lowerinput));
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
public static void main (String[] args)
{
do {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a string: ");
String sentence = keyboard.nextLine();
System.out.print("Enter a letter: ");
String fullLetter = keyboard.nextLine();
char letter = fullLetter.charAt(0);
keyboard.nextLine();
int amount = 0;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (ch == letter) {
amount++;
}
}
System.out.println(letter + " appears " + amount + " times in " + sentence);
System.out.print("Continue? ");
String decide = keyboard.nextLine();
} while (decide.equals("yes"));
}
}
I want the user to input either "yes" or "no" at the end of the loop, then I want that input to determine whether or not the program will loop again. As it stands right now, the the last line of my code isn't working. I've looked around and I'm not sure what I should do to fix this.
You need to declare your variable decide outside the loop and initialize inside:
String decide;
do {
//do something ...
decide = keyboard.nextLine();
} while (decide.equals("yes"));
You should use keyboard.next() to read a String instead of keyboard.nextLine()
next() only reads a word, nextLine() reads the whole line including Enter so it will never be equal to "yes"
You must declare declare the string describe outside of the do/while loop, otherwise it is a local variable of the do/while loop, and cannot be accessed by the do testing portion. Simply using
public static void main(String[] args) {
String decide;
do {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a string: ");
String sentence = keyboard.nextLine();
System.out.print("Enter a letter: ");
String fullLetter = keyboard.nextLine();
char letter = fullLetter.charAt(0);
keyboard.nextLine();
int amount = 0;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (ch == letter) {
amount++;
}
}
System.out.println(letter + " appears " + amount + " times in "
+ sentence);
System.out.print("Continue? ");
decide = keyboard.nextLine();
} while (decide.equals("yes"));
}
will solve your problem.
You has to define your variable decide outside of the loop:
String decide = null
do {
....
decide = keyboard.nextLine();
} while (decide.equals("yes"));