I'm a newbie in java and I was doing this exercise, to search the second word in a string, for example, if a string is "I love java" the program should return "love".
Here is my code:
import java.util.*;
// This program returns the second word of a string
public class SecondWord{
public static void main(String[]args){
Scanner in = new Scanner(System.in);
System.out.println("String: ");
String x = in.nextLine();
int pos = x.indexOf(" ");
int pos1 = x.indexOf(" ", pos);
String second = x.substring(pos, pos1);
System.out.println(second);
}
}
It compiles, but it returns nothing. What's wrong?
When you are getting the next index of " " you should increase 1 in last index.
Change this
int pos1 = x.indexOf(" ", pos);
to
int pos1 = x.indexOf(" ", pos+1);
Note
You should increase the position by 1 when taking the substring to remove extra space in starting or trim it.
String second = x.substring(pos+1, pos1);
Alternate Solution
One better way would be of doing same thing
String x = in.nextLine();
System.out.println(x.split(" ")[1]);
Split the string by " " and print the second element.
I know this thread is pretty old, but I had run into the same question. Thank you for the solution using the split method, it was very helpful. However, I noticed a comment that said that the original code, with the pos + 1 fix, would not work if you entered only two words, and I also discovered that it would not work with only one word. This made me wonder if it was possible to find the second word using this approach without any errors when there were only one or two words. Here is what I came up with:
//For keyboard input
import java.util.Scanner;
// This program returns the second word of a string
public class SecondWord {
public static void main(String[]args) {
//Creates a scanner object for keyboard input
Scanner in = new Scanner(System.in);
//Gets a string from the user
System.out.print("String: ");
String x = in.nextLine();
//If the string contains more than one word
if (x.contains(" ")) {
//Finds the position of the first space, adds one to it to find the position of the first character of the second word
int pos = x.indexOf(" ") + 1;
//Replace the first space with a different character so the program can test if it has a second space
char[] chars = x.toCharArray();
chars[pos - 1] = 'a';
x = String.valueOf(chars);
//If there is a space after the second word
if (x.contains(" ")) {
//Finds the position of the space after the second word
int pos1 = x.indexOf(" ", pos);
//Gets the second word
String second = x.substring(pos, pos1);
//Displays the second word
System.out.println(second);
//If there is not a space after the second word
} else {
//Add a space to the end
x += " ";
//Finds the position of the space after the second word
int pos1 = x.indexOf(" ", pos);
//Gets the second word
String second = x.substring(pos, pos1);
//Displays the second word
System.out.println(second);
}
}
}
}
Related
The Java task is to have the user type a sentence/phrase and then print out how many characters the sentence has. My .length() method is only counting the first word and space as characters. I've read previous questions and answers involving nextLine() but if I use that instead of next() it only lets the user type it's question and waits, doesn't print anything else immediately anymore. I'm brand new to Java and I think this can be fixed with a delimiter but I'm not sure how or what I'm missing. TIA!!
Update: Here's my code.
import java.util.Scanner;
class StringStuff{
public static void main( String [] args){
Scanner keyboard = new Scanner(System.in);
int number;
System.out.print("Welcome! Please enter a phrase or sentence: ");
System.out.println();
String sentence = keyboard.next();
System.out.println();
int sentenceLength = keyboard.next().length();
System.out.println("Your sentence has " + sentenceLength + " characters.");
System.out.println("The first character of your sentence is " + sentence.substring(0,1) + ".");
System.out.println("The index of the first space is " + sentence.indexOf(" ") + ".");
}
}
when I type "Hello world." as the sentence it prints:
Your sentence has 6 characters.
The first character of your sentence is H.
The index of the first space is -1.
keyboard.next call is waiting for user input. You're calling it twice, so your program expects the user to enter two words.
So, when you type in "Hello world." it reads "Hello" and "world." separately:
//Here, the sentence is "Hello"
String sentence = keyboard.next();
System.out.println();
//Here, keyboard.next() returns "World."
int sentenceLength = keyboard.next().length();
And when you use nextLine your code is waiting for the user to enter two lines.
To fix this you need to:
Read the whole line with nextLine.
Use sentence instead of requesting user input the second time.
Something like this should work:
String sentence = keyboard.nextLine();
System.out.println();
int sentenceLength = sentence.length();
import java.util.Scanner;
public Stringcount
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("enter the sentence:");
String str=s.nextLine();
int count = 0;
System.out.println("The entered string is: "+str);
for(int i = 0; i < str.length(); i++)
{
if(str.charAt(i) != ' ')
count++;
}
System.out.println("Total number of characters in the string: " + count);
System.out.println("The first character of your sentence is " + str.substring(0,1) + ".");
System.out.println("The index of the first space is " + str.indexOf(" ") + ".");
}
}
I've searched about everywhere but I just can't find anything very concrete. I've been working on this code for awhile now but it keeps stumping me.
public static void main(String[] args) {
System.out.println(palindrome("word"));
}
public static boolean palindrome(String myPString) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a word:");
String word = in.nextLine();
String reverse = "";
int startIndex = 0;
int str = word.length() -1;
while(str >= 0) {
reverse = reverse + word.charAt(i);
}
}
There's a lot of ways to accomplish this using a while loop.
Thinking about simplicity, you can imagine how could you do this if you had a set of plastic separated character in a table in front of you.
Probably you'll think about get the second character and move it to the begin, then get the third and move to begin, and so on until reach the last one, right?
0123 1023 2103 3210
WORD -> OWRD -> ROWD -> DROW
So, you'll just need two code:
init a variable i with 1 (the first moved character)
while the value of i is smaller than total string size do
replace the string with
char at i plus
substring from 0 to i plus
substring from i+1 to end
increment i
print the string
The process should be:
o + w + rd
r + ow + d
d + row +
drow
Hope it helps
Here is an piece of code I write a while back that uses almost the same process. Hope it helps!
String original;
String reverse = "";
System.out.print("Enter a string: ");
original = input.nextLine();
for(int x = original.length(); x > 0; x--)
{
reverse += original.charAt(x - 1);
}
System.out.println("The reversed string is " +reverse);
I am taking an intro class to Java and we have a project that deals with a hangman game. I have most of the code worked out but there is a bug that I can't seem to resolve.
First, the program prompts the user for a letter and one space where they think the letter goes, then the program displays a word in a series of hyphens and, if the user makes a correct guess, the letter in the corresponding hyphen is replaced with said letter.
For testing purposes, the word has been defaulted to narrow.
So if I were to guess the letter r and for space, I were to guess index 2, the program would give me:
Guess a letter: r
Guess a space: 2
Guess: --r---
The problem I am having is that when I guess the index 3 for space and try to guess the next r, the program just gives me the same output as before.
We are not allowed to use arrays or string builder because we have not talked about them yet.
Here are my variables:
// default word for testing
String blank = "narrow";
// variables to manipulate the string
String start = "";
String end = "";
String word = "";
// variables for input and output
// input is used for the user's letter guess
String input;
// space is used for the user's index guess
String space = "";
// guess is used at the end to display the word to the user and set equal to word after
// it has been manipulated
String guess = "";
Here is the code where the string is being manipulated.
for (int i = 0; i < blank.length(); i++) {
if (i == blank.indexOf(input)) {
start = guess.substring(0, i);
end = guess.substring(i + 1);
word = start.concat(input).concat(end);
}
}
I think it has to do with the if statement, but I have tried some other things and they have not worked. Any help would be appreciated.
Thank you.
The problem with your code is that everytime the blank.indexOf(input) returns 2 everytime (indexOf returns the first occurance of 'r' which is 2)
You can change the condition to check if the character at the space that the user guessed is the contains the letter that the user guessed.
You can do this as follows:
Maintain the pattern to be printed. Make a variable for this.
update the pattern everytime the user guesses correctly.
Note: In the below code guess is the variable I am talking about which is initially set to "------" for the word "narrow"
// check if the space has the letter you guessed
if (blank.charAt(space) == input.charAt(0)) {
// if it has just update the pattern string to also contain the new letter
guess = guess.substring(0, space) + input + guess.substring (space + 1)
You can just print or return (if it is a method) the pattern string.
I think blank.indexOf(input) returns only the first occurrence index of that input character. So you need to use this indexOf(int ch, int fromIndex).
In your case, store index of last occurrence of the input char in some int variable, then use that as fromIndex.
int lastOccurrence = 0;
for (int i = 0; i < blank.length(); i++) {
if (i == blank.indexOf(input, lastOccurrence)) {
lastOccurrence = i;
start = guess.substring(0, i);
end = guess.substring(i + 1);
word = start.concat(input).concat(end);
}
}
I would write it like this:
//set up variables
Scanner keyboard = new Scanner(System.in);
String word = "narrow";
String display = "";
for (int i = 0; i < word.length(); i++) {
display = display + "-";
}
//loop until the word is guessed
while (display.contains("-")) {
//show the user flow, take input
System.out.println("Guess: " + display);
System.out.print("Guess a letter: ");
String letter = keyboard.nextLine();
System.out.print("Guess a space: ");
String spaceStr = keyboard.nextLine();
int space = Integer.parseInt(spaceStr);
//check if the guess is right
if (letter.equals(word.charAt(space) + "")) {
//modify the string shown to the user
String temp = display.substring(space + 1);
display = display.substring(0, space);
display = display + letter + temp;
}
}
The key is to have one variable that is shown to the user and one which holds the real word. When they make a correct guess, you can modify the string which is shown to the user.
indexOf(String str) returns the index within this string of the FIRST OCCURENCE of the specified substring. More of this here
Best way I would suggest to do, is to change the output ONLY if the user got it right. Hence, for every guess I would do:
if(blank.charAt(space) == input.charAt(0))
{
start = guess.substring(0, space);
end = guess.substring(space + 1);
word = start.concat(input).concat(end);
}
So I've been making a small piece of code in Java that takes input from the user counts the uppercase, lowercase and other parts (such as spaces, numbers, even brackets) and then returns how much there are of each to the user.
The problem I have is that say I put in "Hello There" it stops counting spots after the "o" in Hello. So after the first word.
Code
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int upper = 0;
int lower = 0;
int other = -1;
int total = 0;
String input;
System.out.println("Enter the phrase: ");
input = scan.next();
for (int i = 0; i < input.length(); i++) {
if (Character.isUpperCase(input.charAt(i))) upper++;
if (Character.isLowerCase(input.charAt(i))) lower++;
else other++;
total = upper + lower + other;
}
System.out.println("The total number of letters is " + total);
System.out.println("The number of upper case letters is " + upper);
System.out.println("The number of lower case letters is " + lower);
System.out.println("The number of other letters is " + other);
}
}
Scanner#next:
Finds and returns the next complete token from this scanner. A
complete token is preceded and followed by input that matches the
delimiter pattern.
The problem is that next doesn't see the word "There" since "Hello World" is not a complete token.
Change next to nextLine.
Advice: Use the debugger and you'll find the problem quickly, and when you have doubts refer to the docs, they're there for you.
Problem is that next() only returns the line before a space but nextLine() will read the whole line.
So Change
scan.next();
to
scan.nextLine();
You need to change next() to nextLine()- it will read all the line
As others have said. You should change from scn.next to scn.nextLine(). But why? This is because scn.next() only read until it encounters a space, and it stops reading. So whatever input after a space will not be read.
scn.nextLine() reads until a newline (i.e. enter) is encountered.
You can try with regular expressions:
public static void main(String[] args) {
String input = "Hello There";
int lowerCase = countMatches(Pattern.compile("[a-z]+"), input);
int upperCase = countMatches(Pattern.compile("[A-Z]+"), input);
int other = input.length() - lowerCase - upperCase;
System.out.printf("lowerCase:%s, upperCase:%s, other:%s%n", lowerCase, upperCase, other);
}
private static int countMatches(Pattern pattern, String input) {
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
}
return count;
}
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");
}
}
}