Help with Morse Code Java assignment! - java

The value for the Morse Code translation keeps returning null and I've done everything I can think of to fix it. We are restricted to using arrays on this assignment. What can I do to correct it?
import javax.swing.JOptionPane;
import java.util.*;
import java.io.*;
public class morseCodeTest
{
public static void main(String[] args)throws IOException
{
String userInput;
final String SENTINEL = "0";//for exiting program when entered
//object creation
Translate text = new Translate();
//getting user input to be translated
do
{
userInput = JOptionPane.showInputDialog("Please enter what you wish to translte to Morse code (no punctuation).");
String compare = userInput.toUpperCase();
String[] codedText = new String[compare.length()];
codedText = text.translateHere(compare);
text.toString(userInput, codedText);
}while(!userInput.equals(SENTINEL));
}//end main
}//end class
class Translate
{
public Translate()
{
}//end default constructor
public String[] translateHere(String s)throws IOException
{
String compare = s, codedLine = ""; //userInput toUpperCase
int length = compare.length(); //length of userInput
String line, file = "Morse.txt";// variable holding file name and variable for each letter/number
char code;
//Constants
final int MAX = 36;
//Arrays
char[] morseLetter = new char[MAX];
String[] morseCode = new String[MAX];
String[] newMessage = new String[length];
//putting user input in a character array;
char[] userLetters = compare.toCharArray();
//object creation
File openFile = new File(file);
Scanner inFile = new Scanner(openFile);
//for loop that will read data from the Morse.txt file
for(int i = 0; i < MAX; i++)
{
while(inFile.hasNext())
{
line = inFile.next();
code = (char)line.charAt(0);
morseLetter[i] = code;
morseCode[i] = inFile.next();
}//end nested while loop
}//end for loop
for(int j = 0; j < length; j++)
{
for(int k = 0; k < MAX; k++)
{
if(userLetters[j] == morseLetter[k])
{
newMessage[j] = morseCode[k];
}
}//end nested for loop
}//end for loop
return newMessage;
}//end method that completes translateion
public String toString(String a, String[] b)
{
String input = a;
String[] coded = b;
String[] encoded = new String[input.length()];
//JOptionPane.showMessageDialog(null, "Original Text: " + input + "\nCoded Text: " + coded);
for(int l = 0; l <input.length(); l++)
{
encoded[l] = coded[l];
}
String str = "";
System.out.print(Arrays.toString(encoded));
return str;
}//end toString method
}//end Translate Class
The Morse code text file contains the following:
1 .----
2 ..---
3 ...--
4 ....-
5 .....
6 -....
7 --...
8 ---..
9 ----.
0 -----
A .-
B -...
C -.-.
D -..
E .
F ..-.
G --.
H ....
I ..
J .---
K -.-
L .-..
M --
N -.
O ---
P .--.
Q --.-
R .-.
S ...
T -
U ..-
V ...-
W .--
X -..-
Y -.--
Z --..

Your Translate.toString method will always return an empty string because that's the only thing you assign to the str variable.

public String toString(String a, String[] b)
{
System.out.println("Input: " + a);
System.out.println("Output:");
String output = "";
for(int i = 0; i < b.length; i++)
{
output = output + b[i];
}
return output;
}//end toString method
But the real problem is this loop:
for(int i = 0; i < MAX; i++)
{
while(inFile.hasNext())
{
line = inFile.next();
code = (char)line.charAt(0);
//System.out.println(code);
morseLetter[i] = code;
morseCode[i] = inFile.next();
}//end nested while loop
}//end for loop
There you try parsing the morse code letters into a file, but the problem is the for loop is in the first iteration and then, the whole while loop is executed, therefore you're always placing the morsecode in the first position of the array.
So it should look like that:
int counter = 0;
while(inFile.hasNext())
{
line = inFile.next();
code = (char)line.charAt(0);
//System.out.println(code);
morseLetter[counter] = code;
morseCode[counter] = inFile.next();
counter++;
}//end nested while loop
As an additional note: Did you noticed that if the user clicks cancel in your OptionsDialog that there is a NullPointer? Proper exception handling is part of the assignment I think ;)
Therefore I would write the loop like this:
do
{
userInput = JOptionPane.showInputDialog("Please enter what you wish to translte to Morse code (no punctuation).");
if (userInput != null && !userInput.equals("")) {
String compare = userInput.toUpperCase();
String[] codedText = new String[compare.length()];
codedText = text.translateHere(compare);
text.toString(userInput, codedText);
}
}while(userInput != null && !userInput.equals(SENTINEL));

Related

Print user inputs from 2D array using another class in Java?

I am trying to print user inputs in another class in Java. I have made a chessboard which asks the user to input strings on the board, and then, when these strings are printed on screen, I would like the output to be "You have placed piece [name] at coordinate [coordinate]". I am trying to do this in another class rather in the main method, but what I have tried so far doesn't seem to work. Here's my code.
import java.util.Arrays;
import java.util.Scanner;
public class ChessBoard
{
public static void main(String[] args)
{
char rows = 'a';
String spot;
Scanner scanner = new Scanner(System.in);
String[][] grid = new String [8][8];
for(int i = 0; i < grid.length; i++, rows++)
{
for(int col = 0; col < grid[i].length; col++);
String input = null; // will be changed to a valid position
boolean validCoordinate = false; // will be true if position is valid
while ( ! validCoordinate) {
System.out.println("Enter a coordinate (for example, a5): ");
input = scanner.next();
validCoordinate = input.matches("[a-h][1-8]");
};
// now we now that the input is valid
int row = input.charAt(0) - 'a';
int col = input.charAt(1) - '1';
String temp = input + " - ";
System.out.println("Insert your piece:");
input = scanner.next();
grid[row][col] = temp + input;
}
System.out.println(Arrays.deepToString(grid));
}
}
So what I'd like to do is have a new class that uses that last print line to instead print the desired output that I mentioned earlier. Any help would be appreciated, thanks!
EDIT:
import java.util.Arrays;
import java.util.Scanner;
public class ChessBoard1
{
public static void main(String[] args)
{
userInputs input = new userInputs();
showInput show = new showInput();
String grid[][] = input.takeInput();
show.show(grid);
}
}
public class userInputs
{
public String[][] takeInput()
{
char rows = 'a';
String spot;
Scanner scanner = new Scanner(System.in);
String[][] grid = new String [8][8];
for(int i = 0; i < grid.length; i++, rows++) {
for (int col = 0; col < grid[i].length; col++) ;
String input = null; // will be changed to a valid position
boolean validCoordinate = false; // will be true if position is valid
while (!validCoordinate) {
System.out.println("Enter a coordinate (for example, a5): ");
input = scanner.next();
validCoordinate = input.matches("[a-h][1-8]");
}
;
// now we now that the input is valid
int row = input.charAt(0) - 'a';
int col = input.charAt(1) - '1';
String temp = input + " - ";
System.out.println("Insert your piece:");
input = scanner.next();
grid[row][col] = temp + input;
}
return grid;
}
}
public class showInput {
public void show(String [][] inputs)
{
for(int i=0 ; i<inputs.length ; i++){
for(int j=0 ; j < inputs[0].length ; j++)
{
System.out.println(Arrays.deepToString(grid));
}
}
}
}
I have 2 separate files userInputs and showInput but they it says that they should still be declared in a separate file?
It's wrong to write main Function in every class, the program uses the main function to start from it, So you should write it only in the main project class and call inside it the other classes.
Your code should be:
package com.company;
public class ChessBoard
{
public static void main(String[] args)
{
userInputs input = new userInputs();
showInput show = new showInput();
String grid[][] = input.takeInput();
show.show(grid);
}
}
and other classes in separate files like:
package com.company;
import java.util.Scanner;
public class userInputs
{
public String[][] takeInput()
{
char rows = 'a';
String spot;
Scanner scanner = new Scanner(System.in);
String[][] grid = new String [8][8];
for(int i = 0; i < grid.length; i++, rows++) {
for (int col = 0; col < grid[i].length; col++) ;
String input = null; // will be changed to a valid position
boolean validCoordinate = false; // will be true if position is valid
while (!validCoordinate) {
System.out.println("Enter a coordinate (for example, a5): ");
input = scanner.next();
validCoordinate = input.matches("[a-h][1-8]");
}
;
// now we now that the input is valid
int row = input.charAt(0) - 'a';
int col = input.charAt(1) - '1';
String temp = input + " - ";
System.out.println("Insert your piece:");
input = scanner.next();
grid[row][col] = temp + input;
}
return grid;
}
}
and another class to output:
package com.company;
public class showInput {
public void show(String [][] inputs)
{
for(int i=0 ; i<inputs.length ; i++){
for(int j=0 ; j < inputs[0].length ; j++)
{
//Print Your Data
}
}
}
}
Like #Atef Magdy said, You should have one class which holds all the data and functions
and a main class which executes the functions.
and the explanation for this error ( it states that using public int is an "illegal start" to the expression, and that it needs a ";" after it?) I have seen that you made the 2d Array of Type String?
String[] [] grid = new String [8][8];
and then returning it as a 1D Array of Type int?
public int[] getGrid(){
return grid.clone();
}
I should say that this is the source of this error. You should change the 'int[]' to 'string[][]'
if there is any error please reply to this answer!

Reverse String characters in java

Am trying to reverse a string using a method in java, I can fetch all the elements of the string and print them out in order via a loop, my problem is reversing the string such that the first comes last and the last comes first, I tried to find a reverse function to no avail... Here is what I have so far...
private static void palindrome() {
char[] name = new char[]{};
String name1;
System.out.println("Enter your name");
Scanner tim = new Scanner(System.in);
name1 = tim.next();
int len = name1.length();
for (int i = 0; i <= len; ++i) {
char b = name1.charAt(i);
System.out.println(b + " ");
}
}
That loop succeeds in printing out the single characters from the string.
You can use StringBuilder like this:
import java.lang.*;
import java.io.*;
import java.util.*;
class ReverseString {
public static void main(String[] args) {
String input = "Geeks for Geeks";
StringBuilder input1 = new StringBuilder();
// append a string into StringBuilder input1
input1.append(input);
// reverse StringBuilder input1
input1 = input1.reverse();
// print reversed String
System.out.println(input1);
}
}
You can also modify your code to do this:
1 -
for (int i = 0; i <= len; ++i) {
char b = name1[len - i];
System.out.println(b + " ");
}
2 -
for (int i = len; i >= 0; --i) {
char b = name1.charAt(i);
System.out.println(b + " ");
}
Using Java 9 codePoints stream you can reverse a string as follows. This example shows the reversal of a string containing surrogate pairs. It works with regular characters as well.
String str = "𝕙𝕖𝕝𝕝𝕠 𝕨𝕠𝕣𝕝𝕕";
String reversed = str.codePoints()
// Stream<String>
.mapToObj(Character::toString)
// concatenate in reverse order
.reduce((a, b) -> b + a)
.get();
System.out.println(reversed); // 𝕕𝕝𝕣𝕠𝕨 𝕠𝕝𝕝𝕖𝕙
See also: Reverse string printing method
You simply need to loop through the array backwards:
for (int i = len - 1; i >= 0; i--) {
char b = name1.charAt(i);
System.out.println(b + " ");
}
You start at the last element which has its index at the position length - 1 and iterate down to the first element (with index zero).
This concept is not specific to Java and also applies to other data structures that provide index based access (such as lists).
Use the built-in reverse() method of the StringBuilder class.
private static void palindrome() {
String name1;
StringBuilder input = new StringBuilder();
System.out.println("Enter your name");
Scanner tim = new Scanner(System.in);
name1 = tim.next();
input.append(name1);
input.reverse();
System.out.println(input);
}
Added reverse() function for your understanding
import java.util.Scanner;
public class P3 {
public static void main(String[] args) {
palindrome();
}
private static void palindrome() {
char[] name = new char[]{};
String name1;
System.out.println("Enter your name");
Scanner tim = new Scanner(System.in);
name1 = tim.next();
String nameReversed = reverse(name1);
int len = name1.length();
for (int i = 0; i < len; ++i) {
char b = name1.charAt(i);
System.out.println(b + " ");
}
}
private static String reverse(String name1) {
char[] arr = name1.toCharArray();
int left = 0, right = arr.length - 1;
while (left < right) {
//swap characters first and last positions
char temp = arr[left];
arr[left++] = arr[right];
arr[right--] = temp;
}
return new String(arr);
}
}
you can try the build-in function charAt()
private String reverseString2(String str) {
if (str == null) {
return null;
}
String result = "";
for (int i = str.length() - 1; i >= 0; i--) {
result = result + str.charAt(i);
}
return result;
}
public void test(){
System.out.println(reverseString2("abcd"));
}
see also rever a string in java
String reversed = new StringBuilder(originalString).reverse().toString();

Using for-loop, iterate through 2D array in order to pass those values into parameter

I am opening a text file that looks like this:
1;Rani;Hockey;BMW;1 Series;2011;WAUGFAFR4CA952133;2003;
2;Ranice;Dodge;Hyundai;Sonata;2005;WAUMF78PX6A683500;2013;
(has 90 more lines similar to the above)
I have already split each words into a 2D array such that positions
[0][0] = 1
[0][1] = Rani
[0][2] = Hockey
[1][0] = 2
[1][1] = Ranice
[1][7] = 2013
I setup a for-loop to iterate through my 2D Array where (eventually) each index will be passed as a parameter to a constructor that I have. During the loop I keep getting:
Exception in thread "main" java.lang.NumberFormatException:
For input string: "2"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Test4.main(Test4.java:53)
Below are my code for my CarData class:
public CarData() {}
public CarData(int i, String fn, String ln, String cMake, String cMdl,
int cYear, String vin, int p)
{
this.customerID = i;
this.ownerFirstName = fn;
this.ownerLastName = ln;
this.carMake = cMake;
this.carModel = cMdl;
this.carYear = cYear;
this.carVin = vin;
this.yearCarPurchased = p;
}
public class CarDataDriver {
public static void main(String [] args)
{
final int col = 8;
final int row = 100;
int id = 0;
String fn = null;
String ln = null;
String cMake = null;
String cMdl = null;
int cYear = 0;
String vin = null;
int p = 0;
CarData [] data = new CarData[row];
// Open file
File file = new File("CarData.txt");
// Use scanner to scan new File
Scanner scanner;
try {
scanner = new Scanner(file);
// useDelimiter to separate String
String text = scanner.useDelimiter("\\A").next();
// Use split method to split String
String [] array = text.split(";");
String[][] array2D = new String[row][col];
//iterate through array to create 2D array
for (int i = 0, k=0; i < array2D.length; i++)
{
for (int j = 0; j < col; j++)
{
array2D[i][j] = array[k++];
}
}
for (int i = 0, k=0; i < array2D.length; i++)
{
for (int j = 0; j < col; j++)
{
if(j==0){
id = Integer.parseInt(array2D[i][j]); //first iteration where i = 0 runs fine, when i=1 and j=0 I get the error
continue;
}
if(j==1){
fn = array2D[i][j];
continue;
}
if(j==2) {
ln = array2D[i][j];
continue;
}
if(j==3){
cMake = array2D[i][j];
continue;
}
if(j==4){
cMdl = array2D[i][j];
continue;
}
if(j==5){
cYear = Integer.parseInt(array2D[i][j]);
continue;
}
if(j==6){
vin = array2D[i][j];
continue;
}
if(j==7){
p = Integer.parseInt(array2D[i][j]);
}
data[k] = new CarData(id, fn, ln, cMake, cMdl, cYear, vin, p);
k++;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Your looping alone is fine - what is causing an error is an invalid character (a whitespace) parsed together with proper integer. You may simply remove all whitespaces from your string with:
array2D[i][j].replaceAll("\\s+","")
(note, that this not modifies a string in array, but returns new one with removed spaces)
Where strange "\\s+" string just means "any space character" (it's so called regular expression, but you don't need to understand it fully for now)
However, note, that you have some more issues in your code, for example absolutely unnecessary inner loop with so numerous ifs, where every of them would execute just once - instead of this you can simply access array2D[i][1], array2D[i][2] and so on. Also keeping additional index k and incrementing it by hand seems to be redundant.
Anyway, keep coding and good luck!
P.S. Using BufferedReader and its readLine() seems to be a much better (and simpler!) way to read a file. Take a glimpse on https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html

Morse to English

So the object of the program is in the title. I've managed to successfully convert English to Morse Code but going the opposite way is proving to be difficult. I've looked all over the forums and have not been able to solve my issue here. It seems that it can convert, it just converts the last character of the morse code. I also can't come up with a way to distinguish words from each other using spaces. Any help would be greatly appreciated.
/******
* This program will prompt the user to specify the desired type of translation,
* input a string of Morse code characters or English characters,
* then display the translated results
*
* Pre-Conditions:
*
* Post-Conditions:
*
* #author: PC
******/
import java.util.Scanner;
import java.util.Arrays;
public class MorseCode
{
public static void main( String [] args )
{
Scanner input = new Scanner(System.in);
String userInput;
System.out.println( "This is a Translator." );
System.out.println( "Would you like to translate sentence to Morse code or English? (MC or E):" );
String choice = input.nextLine();
choice = choice.toLowerCase();
if(choice.equals("e")){
System.out.println( "Enter sentence (puncuation not needed):" );
userInput = input.nextLine();
userInput = userInput.toLowerCase();
String [] morseWords = userInput.split(" ");
convertToEnglish(morseWords);
}
else if(choice.equals("mc")){
System.out.println( "Enter sentence (puncuation not needed):" );
userInput = input.nextLine();
convertToMorse(userInput);
}
}
public static void convertToMorse(String text)
{
int i, j;
String [] morseAns = new String[text.length()];
text = text.toLowerCase();
String alphabet = ("abcdefghijklmnopqrstuvwxyz1234567890 ");
String [] morse = new String[] { ".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--",
"-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--..",
".----","..---","...--","....-",".....","-....","--...","---..","----.","-----", "|" };
char selectedChar, convertedChar, alphabetChar;
for(i = 0; i < text.length(); i++)
{
selectedChar = text.charAt(i);
for(j = 0; j < alphabet.length(); j++)
{
alphabetChar = alphabet.charAt(j);
if(selectedChar == alphabetChar)
{
morseAns[i] = morse[j];
}
}
}
for(i = 0; i < text.length(); i++)
{
System.out.print(morseAns[i] + " ");
}
}
public static void convertToEnglish(String [] multiMorseWords)
{
int i, j;
String multipleMorseWords;
String alphabet = ("abcdefghijklmnopqrstuvwxyz1234567890 ");
String [] morse = new String[] { ".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--",
"-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--..",
".----","..---","...--","....-",".....","-....","--...","---..","----.","-----", "|" };
char [] englishAns = new char[multiMorseWords.length];
for(i = 0; i < multiMorseWords.length; i++)
{
multipleMorseWords = multiMorseWords[i];
String [] morseChars = multipleMorseWords.split(" ");
for(j = 0; j < morseChars.length; j++)
{
if(morseChars[j].equals(morse[j]))
{
englishAns[i] = alphabet.charAt(j);
}
}
}
for(i = 0; i < multiMorseWords.length; i++)
{
System.out.println(englishAns[i]);
}
}
}
You can just create a map and add all the keys as the morse string and the value as the letter and then iterate over the words and get from map. There is some things you have to handle such as each morse code should be delimited by something, and then word should be different. Like you current have 3 spaces for a word, you would have to delimit the spacing the morse values otherwise I dont see a way to distinguish.
here is an example:
public static void convertToEnglish(String[] multiMorseWords) {
Map<String, String> morse = new HashMap<String, String>();
morse.put(".-", "a");
morse.put("-...", "b");
// etc.. add all the morse code inputs
for (String word : multiMorseWords) {
System.out.println(morse.get(word));
}
}
Fixed my code! Didn't need to call to split() in the main method, just needed to split in the convertToEnglish method. Here is my revised method:
public static void convertToEnglish(String morseSentence)
{
int i, j;
String alphabet = ("abcdefghijklmnopqrstuvwxyz1234567890 ");
String [] morse = new String[] { ".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--",
"-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--..",
".----","..---","...--","....-",".....","-....","--...","---..","----.","-----", "|" };
String [] morseChars = morseSentence.split(" ");
String selectedMorse;
char [] englishAns = new char[morseChars.length];
for(i = 0; i < morseChars.length; i++)
{
selectedMorse = morseChars[i];
for(j = 0; j < morse.length; j++)
{
if(selectedMorse.equals(morse[j]))
{
englishAns[i] = alphabet.charAt(j);
}
}
}
for(i = 0; i < englishAns.length; i++)
{
System.out.print(englishAns[i]);
}
}

Java words reverse

I am new to Java and I found a interesting problem which I wanted to solve. I am trying to code a program that reverses the position of each word of a string. For example, the input string = "HERE AM I", the output string will be "I AM HERE". I have got into it, but it's not working out for me. Could anyone kindly point out the error, and how to fix it, because I am really curious to know what's going wrong. Thanks!
import java.util.Scanner;
public class Count{
static Scanner sc = new Scanner(System.in);
static String in = ""; static String ar[];
void accept(){
System.out.println("Enter the string: ");
in = sc.nextLine();
}
void intArray(int words){
ar = new String[words];
}
static int Words(String in){
in = in.trim(); //Rm space
int wc = 1;
char c;
for (int i = 0; i<in.length()-1;i++){
if (in.charAt(i)==' '&&in.charAt(i+1)!=' ') wc++;
}
return wc;
}
void generate(){
char c; String w = ""; int n = 0;
for (int i = 0; i<in.length(); i++){
c = in.charAt(i);
if (c!=' '){
w += c;
}
else {
ar[n] = w; n++;
}
}
}
void printOut(){
String finale = "";
for (int i = ar.length-1; i>=0;i--){
finale = finale + (ar[i]);
}
System.out.println("Reversed words: " + finale);
}
public static void main(String[] args){
Count a = new Count();
a.accept();
int words = Words(in);
a.intArray(words);
a.generate();
a.printOut();
}
}
Got it. Here is my code that implements split and reverse from scratch.
The split function is implemented through iterating through the string, and keeping track of start and end indexes. Once one of the indexes in the string is equivalent to a " ", the program sets the end index to the element behind the space, and adds the previous substring to an ArrayList, then creating a new start index to begin with.
Reverse is very straightforward - you simply iterate from the end of the string to the first element of the string.
Example:
Input: df gf sd
Output: sd gf df
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class Count{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter string to reverse: ");
String unreversed = scan.nextLine();
System.out.println("Reversed String: " + reverse(unreversed));
}
public static String reverse(String unreversed)
{
ArrayList<String> parts = new ArrayList<String>();
String reversed = "";
int start = 0;
int end = 0;
for (int i = 0; i < unreversed.length(); i++)
{
if (unreversed.charAt(i) == ' ')
{
end = i;
parts.add(unreversed.substring(start, end));
start = i + 1;
}
}
parts.add(unreversed.substring(start, unreversed.length()));
for (int i = parts.size()-1; i >= 0; i--)
{
reversed += parts.get(i);
reversed += " ";
}
return reversed;
}
}
There is my suggestion :
String s = " HERE AM I ";
s = s.trim();
int j = s.length() - 1;
int index = 0;
StringBuilder builder = new StringBuilder();
for (int i = j; i >= 0; i--) {
Character c = s.charAt(i);
if (c.isWhitespace(c)) {
index = i;
String r = s.substring(index+1, j+1);
j = index - 1;
builder.append(r);
builder.append(" ");
}
}
String r=s.substring(0, index);
builder.append(r);
System.out.println(builder.toString());
From adding debug output between each method call it's easy to determine that you're successfully reading the input, counting the words, and initializing the array. That means that the problem is in generate().
Problem 1 in generate() (why "HERE" is duplicated in the output): after you add w to your array (when the word is complete) you don't reset w to "", meaning every word has the previous word(s) prepended to it. This is easily seen by adding debug output (or using a debugger) to print the state of ar and w each iteration of the loop.
Problem 2 in generate() (why "I" isn't in the output): there isn't a trailing space in the string, so the condition that adds a word to the array is never met for the last word before the loop terminates at the end of the string. The easy fix is to just add ar[n] = w; after the end of the loop to cover the last word.
I would use the split function and then print from the end of the list to the front.
String[] splitString = str.split(" ");
for(int i = splitString.length() - 1; i >= 0; i--){
System.out.print(splitString[i]);
if(i != 0) System.out.print(' ');
}
Oops read your comment. Disregard this if it is not what you want.
This has a function that does the same as split, but not the predefined split function
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string : ");
String input = sc.nextLine();
// This splits the string into array of words separated with " "
String arr[] = myOwnSplit(input.trim(), ' '); // ["I", "AM", "HERE"]
// This ll contain the reverse string
String rev = "";
// Reading the array from the back
for(int i = (arr.length - 1) ; i >= 0 ; i --) {
// putting the words into the reverse string with a space to it's end
rev += (arr[i] + " ");
}
// Getting rid of the last extra space
rev.trim();
System.out.println("The reverse of the given string is : " + rev);
}
// The is my own version of the split function
public static String[] myOwnSplit(String str, char regex) {
char[] arr = str.toCharArray();
ArrayList<String> spltedArrayList = new ArrayList<String>();
String word = "";
// splitting the string based on the regex and bulding an arraylist
for(int i = 0 ; i < arr.length ; i ++) {
char c = arr[i];
if(c == regex) {
spltedArrayList.add(word);
word = "";
} else {
word += c;
}
if(i == (arr.length - 1)) {
spltedArrayList.add(word);
}
}
String[] splitedArray = new String[spltedArrayList.size()];
// Converting the arraylist to string array
for(int i = 0 ; i < spltedArrayList.size() ; i++) {
splitedArray[i] = spltedArrayList.get(i);
}
return splitedArray;
}

Categories