this was the solution to my homework and the purpose was to reverse each word in a string based on user inputting a sentence. I have completed this on my own, but I'm just wondering how the iterator worked in this piece of code. I don't understand the delcaration of tempword = ""; and how he printed out each word delimited by spaces.
import java.util.Scanner;
public class StringReverser
{
public static void main(String args[])
{
String sentence;
String word;
String tempWord = "";
Scanner scan = new Scanner(System.in);
Scanner wordScan;
System.out.print("Enter a sentence: ");
sentence = scan.nextLine();
wordScan = new Scanner(sentence);
while(wordScan.hasNext())
{
word = wordScan.next();
for(int numLetters = word.length() - 1; numLetters >= 0; numLetters--)
tempWord += word.charAt(numLetters);
System.out.print(tempWord + " ");
tempWord = "";
}
System.out.println();
}
}
this bit adds in the spaces
System.out.print(tempWord + " ");
this bit reverses it
for(int numLetters = word.length() - 1; numLetters >= 0; numLetters--)
tempWord += word.charAt(numLetters);
this bit sets it up for the next word
tempWord = "";
The for loop counts backwards, from the index of the last character in the word to the first (in zero based notation)
The print prints the reversed word + a space (" "), the fact it uses print in place of println is because println would add a carriage return putting each word in a different line.
The tempWord = ""; at the end of each iteration reset the variable so it can be reused.
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 have written code to prompt user to input a sentence which will be displayed reversed by the system. I have managed it with a bit of help, but I now struggle to comment my codes to explain each piece of it. I somewhat understand what I have done, but I feel like I do not master the "whys" of each line.
Anyone able to help with my comments ?
public static void main(String[] args) {
// TODO Auto-generated method stub
String original = "", reverse = ""; // Setting the strings values
Scanner in = new Scanner(System.in); // Scanner is equal to input from user
while(!original.contains("exit"))
// As long as user does not input "exit", user will be prompt to enter a sentence
{
original = "";
reverse = "";
System.out.println("Enter a sentence to be reversed: ");
original = in.nextLine(); // Setting "original" to be equal to user's input
int length = original.length(); // Getting user's input character length (original)
for (int i = length - 1; i >= 0; i--) // Getting input from the last character to be reversed
reverse = reverse + original.charAt(i); //Setting "reverse" to the input "original" characters
System.out.println(reverse); // Printing the input reversely
}
}
Most blurry parts being the:
for (int i = length - 1; i >= 0; i--)
and the:
reverse = reverse + original.charAt(i);
Here's an explanation of what's happening.
public static void main(String[] args) {
String original = "", reverse = ""; // Create empty variables to hold the input and output
Scanner in = new Scanner(System.in); // Create an object to read from StdIn
while(!original.contains("exit"))
// Read from StdIn as long as user does not input "exit"
{
original = "";
reverse = "";
System.out.println("Enter a sentence to be reversed: ");
original = in.nextLine(); // Save the user's input as "original"
int length = original.length(); // Get the length of the input
for (int i = length - 1; i >= 0; i--) // Iterate over each character of the input, starting from the end until you reach the beginning and add the character to the "reverse" string
reverse = reverse + original.charAt(i);
System.out.println(reverse); // Output the result
}
}
Having two separate comments to explain the for loop doesn't make much sense as each of the two lines are meaningless without the other.
Well, let's look at it with the word 'HELLO' as input. You can tell, that the length of the string is 5, and the first letter (H) has the index 0, the second letter 1, ... and the last one has the index 4, which btw. is length -i.
The loop for (int i = length - 1; i >= 0; i--) starts with the last letter, then it takes the second last, and so on, and appends every letter in a reverse order to the reverse string. In general in the loop you will do following:
reverse = reverse + original.CharAt(4) => reverse='O'
reverse = reverse + original.CharAt(3) => reverse='OL'
reverse = reverse + original.CharAt(2) => reverse='OLL'
reverse = reverse + original.CharAt(1) => reverse='OLLE'
reverse = reverse + original.CharAt(0) => reverse='OLLEH'
Understanding
for (int i = length - 1; i >= 0; i--)
reverse = reverse + original.charAt(i);
Which you should reformat to look like
for (int i = length - 1; i >= 0; i--)
reverse = reverse + original.charAt(i);
or
for (int i = length - 1; i >= 0; i--) {
reverse = reverse + original.charAt(i);
}
means to take what is currently stored in the reverse variable and adding a new character at the end + original.charAt(i). This produces a new String which gets assigned back to the reverse variable, overriding what was in it before like #agim mentioned in his answer.
Here are some other alternatives you could consider. Especially with using StringBuilder because it has a reverse() function built into it, if you're wanting to reverse the sentence by character.
import java.util.*;
public class JavaFiddle
{
public static void main(String[] args)
{
String sentence = "The quick brown fox jumps over the lazy dog";
// Print sentence forward
System.out.println(sentence);
// Print sentence backwards by words
String[] words = sentence.split(" ");
for (int i = words.length - 1; i >= 0; i--) {
System.out.print(words[i] + " ");
}
System.out.println();
// Print sentence backwards by character
for (int i = sentence.length() - 1; i >= 0; i--) {
System.out.print(sentence.charAt(i));
}
System.out.println();
// Print sentence backwards by character using StringBuilder;
StringBuilder reverseSentence = new StringBuilder(sentence);
System.out.println(reverseSentence.reverse());
}
}
RESULT
The quick brown fox jumps over the lazy dog
dog lazy the over jumps fox brown quick The
god yzal eht revo spmuj xof nworb kciuq ehT
god yzal eht revo spmuj xof nworb kciuq ehT
I made a simple program to spell-check words. The program has 2 inputs, an array of String that works as a dictionary and a String that is a sentence. The program checks the sentence (word to word) and checks the dictionary to find a simmilar word, then it asks the user if they meant to write the word in the dictionary.
Requirements:
The first 2 characters need to be the same.
The word in the dictionary can only have 2 more characters than the sentence word.
The word in the dictionary can only have 2 different characters than the word in the sentence. (The only characters that count are the ones with index between 0 and the length of the sentence word. E.g. efg and egg|s)
public static String SpellCheck(String[] dictionary, String sentence){
Scanner sc = new Scanner(System.in);
String newSentence = "";
StringTokenizer divisor = new StringTokenizer(sentence);
while(divisor.hasMoreElements()){
String word = divisor.nextToken();
String a = "";
for(int i = 0; i<dictionary.length; ++i){
int n = 0;
if(word.length()>2 && dictionary[i].length()-word.length()<=2 && word.substring(0,2).indexOf(dictionary[i].substring(0,2))==0){
String s1 = word.substring(2,word.length());
String s2 = dictionary[i].substring(2,dictionary[i].length());
for(int k = 0; k<s1.length(); ++k){
String l1 = s1.substring(k,k+1);
String l2 = s2.substring(k,k+1);
if(l1.indexOf(l2)!=0)++n;
}
if(n<=2){
System.out.print(dictionary[i] + "?");
a = sc.nextLine();
if("yes".indexOf(a)==0){
newSentence += dictionary[i] + " ";
break;
}
}
}
}
if("yes".indexOf(a)!=0)newSentence += word + " ";
}
return newSentence;
}
The problem is at the line
String s2 = dictionary[i].substring(2,dictionary[i].length());
It works for the first word in the sentence but in the second time I get an error saying "String index is out of range" and I can't figure out why since I'm using .length() to find the index of the last letter. I hope someone can help me figuring out what's wrong with this program. Thank you!
I believe your error is in the for loop just below where you've said the error is
String s2 = dictionary[i].substring(2,dictionary[i].length());
for(int k = 0; k<s1.length(); ++k){ //HERE
String l1 = s1.substring(k,k+1);
String l2 = s2.substring(k,k+1);
}
When setting l1 and l2, you will be exceeding the bounds of your string index. the for loop should read
for(int k = 0; k < s1.length()-1; ++k){
What if the length is less than 2? Your starting index is 2.
I'm working my way through a java learning book and at the moment I'm learning about arrays and vectors. I've been doing ok up until now I've been stuck on this question for ages and have no idea how to tackle it, my head is about to explode!
The questions for this certain program I have to tackle are:
Elementary error checking is introduced, specifically check that the array Tokens has two elements, if there is a problem with the format of the data inform the user but carry on accepting input.
It will accept input of either
quit
put name mark
get name
The quit scenario works as before, the second scenario stores the student and their mark at the next
available array index; whilst get just returns the mark of any student who matched to the name ( there
may be more than one such student, there many be none).
The program reads in the mark as an integer not a String (you can find examples of the structure you
need by searching for Integer.parseInt on Google).
Upon typing quit, the mean mark, and the highest mark are also displayed.
The java code is as follows:
import java.util.Scanner;
public class ArrayInput {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
String b;
String student[] = new String[50];
String mark[] = new String[50];
int i = 0;
while ((b = s.nextLine()) != null) {
if (b.equals("quit")) break;
String Tokens[] = b.split(' ');
// System.out.println(Tokens[0] + ' ' + Tokens[1]);
student[i] = Tokens[0];
mark[i] = Tokens[1];
i++;
}
for (int j = 0; j < i; j++) {
System.out.println(student[j] + ' ' + mark[j]);
}
}
}
It also throws out on error on this line:
String Tokens[] = b.split(' ');
use:
b.split("\\s+");
to split on whitespaces.
This will cause any number of consecutive spaces to split your string into tokens as the split() method in java is constructed to be used with regular expressions anyway
I would've written it like this (tried it on IDEONE):
import java.util.Scanner;
public class ArrayInput {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
String b;
String[] student = new String[50]; // changed here
String[] mark = new String[50]; // Changed here
int i = 0;
b = s.nextLine(); // Get the next line here first
while (b != null) { // Evalaute b as for while loop here
if (b.equals("quit")) break;
String[] Tokens = b.split(" "); // Changed to use " ", not ' '
// System.out.println(Tokens[0] + ' ' + Tokens[1]);
student[i] = Tokens[0];
mark[i] = Tokens[1];
i++;
b = s.nextLine(); // get the next line here before looping again.
}
for (int j = 0; j < i; j++) {
System.out.println(student[j] + ' ' + mark[j]);
}
}
}
The Scannerclass has a method called hasNext() which you can use quite helpfully for the while() loops. If you use that the following snippet is improved:
// b = s.nextLine() not needed anymore
while(s.hasNext()){
...
...
...
}
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;
}