How do i access each character individually in a string array? - java

In this i need to take in a user imputed sentence and print it out in pig-latin.
(also i have several imports that aren't needed but I left them in when i copied the class and main lines from another program)
import static java.lang.System.*;
import java.util.*;
import java.lang.Math;
public class Pig_latin
{
public static void main(String[]args)
{
String sentence;
out.print("Enter a complete sentence: ");
Scanner sc = new Scanner(System.in);
sentence=sc.nextLine();
Here i am creating the string array and splitting at the spaces.
The only problem with this is that now each word is in its own object.
String s1[]=sentence.split(" ");
Because I've separated the words I don't know of a way to access each character to move them to the end or add "ay".
for(int x=0;x<s1.length;x++)
{
}
}
}

Heres a simple way of how you can get each character in a string in java. String.charAt(index) gets the current character at the index specified.
public static void main(String[] args) {
String getMyCharacters = "Hello World";
for(int i = 0; i < getMyCharacters.length();i++)
{
System.out.print(getMyCharacters.charAt(i));
}
}
output: Hello World
And this is one way of how you get the characters when you split each word into its own string.
String[] splitted = getMyCharacters.split(" ");
for(int j = 0; j < splitted.length; j++)
{
System.out.println("\nCurrent word:" + splitted[j]);
for(int y = 0; y < splitted[j].length(); y++)
{
System.out.println(splitted[j].charAt(y));
}
}
output:
Current word:Hello
H
e
l
l
o
Current word:World
W
o
r
l
d

You can refer each element of the array with s1[x], x is the index of the array s1, thereby saying you are looking up the xth element of the array.
for(int x=0;x<s1.length;x++)
{
System.out.println(s1[x]);
}

Related

How do I make this output happen in java?

I'm a beginner and I want to output the following using a for loop and subscript and I'm not sure.
output:
Jamaica
amaica
maica
aica
ica
ca
a
What can I do, in order to achieve this output?
First: You need to loop for generating n line which is the length of array.
Second: You need to print the spaces with is same value as row - 1 number of times.
Second: You need to print character start from row - 1 number to the length of the string.
And the final solution will be:
public class MyClass {
public static void printStr(String str) {
int i,j;
for (i = 0; i < str.length();i++) {
for(j = 0; j < i; j++) {
System.out.print(" ");
}
for(j = i; j < str.length();j++) {
System.out.print(str.charAt(j));
}
System.out.println("");
}
}
public static void main(String args[]) {
MyClass.printStr("Jamaica");
}
}
I would use two regular expressions, the first to terminate the loop when the String is filled with white space. The second to replace the first non-white space character with a white space in the loop body (after printing the current String value). And, if it's possible the String might be empty you should guard against that. Like,
String s = "Jamaica";
if (!s.isEmpty()) {
while (!s.matches("\\s+")) {
System.out.println(s);
s = s.replaceFirst("\\S", " ");
}
}
Outputs (as requested)
Jamaica
amaica
maica
aica
ica
ca
a
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.next(); //input through scanner class
int len = s.length();
for(int i=0;i<len;i++){
for(int j=0;j<i;j++){
System.out.print(" ");
}
for(int j=i;j<len;j++){
System.out.print(s.charAt(j));
}
System.out.println("");
}
}
Hopefully that helps
Try following code:
StringBuilder country = new StringBuilder("Jamaica");
for(int i=0; i< country.length();i++){
if(i > 0)
{
for(int j=0;j<i;j++){
country.setCharAt(j,' ');
}
}
System.out.println(country);
}

Java reverse string method

I'm tying to learn Java. I need to make a method called reverse that gets a string and return a string (but in reverse order). Here is what i tried. Can you fix the code and explain what I'm doing wrong? Please also give me some advice about a good start in Java. Thank you!
public class Test{
public static String reverse(String a){
int j = a.length();
char[] newWord = new char[j];
for(int i=0;i<a.length();i++)
{
newWord[j] = a.charAt(i);
j--;
}
return new String(newWord);
}
public static void main(String a[]){
String word = "abcdefgh";
System.out.println(reverse(word));
}
}
You can use this to reverse the string, you don't need to use your own method
new StringBuilder(word).reverse().toString()
If you want to use your solution you must change int j = a.length() to int j = a.length() -1;
The fixed code is
public class Test {
public static String reverse(String a) {
int j = a.length();
char[] newWord = new char[j];
for (int i = 0; i < a.length(); i++) {
newWord[--j] = a.charAt(i);
}
return new String(newWord);
}
public static void main(String a[]) {
String word = "abcdefgh";
System.out.println(reverse(word));
}
}
Like others have mentioned, arrays indexes start at 0. So if an array has size 5 for example it has indices 0,1,2,3,4. It does not have an index 5.
For an example of a string with length 5, the code change that I did newWord[--j] = a.charAt(i); will assign to the indices 4,3,2,1,0 in that order.
Regarding getting a good start in Java, I think you could try https://softwareengineering.stackexchange.com/. This site is not meant for that kind of thing.
This is a common difficulty with new Java developers.
The point you are missing is that the last entry in an array is at position a.length-1. Similarly for Strings
Here's an improved version to demonstrate.
public static String reverse(String a) {
char[] newWord = new char[a.length()];
for (int i = 0, j = a.length() - 1; i < a.length(); i++, j--) {
newWord[j] = a.charAt(i);
}
return new String(newWord);
}
You're already on the right track with your method. The one thing I will say to you is that you don't need to use an array of characters and then use something like return new String(newWord);. That's overly complicated for beginner Java in my view.
Instead, you can create an empty String and just keep appending the characters onto it as you loop through all the characters in the String you want to reverse.
So your for loop, because you're reversing the word, should begin at the end of the word being reversed (a in this case) and work backwards to index position 0 (ie. the start of the word being reversed).
Try this and see if this makes sense to you:
public static String reverse(String a) {
String reversedWord = "";
for (int index = a.length() - 1; index >= 0; index --) {
reversedWord += a.charAt(index);
}
return reversedWord;
}
This is, then, starting at the end of a, working backwards one character at a time (hence the use of index --) until we reach a point where index has gone beyond the character at index position 0 (the middle condition of index >= 0).
At each index position, we are simply taking the character from the a String and appending it onto the reversedWord String.
Hope this helps! Feel free to ask any other questions if you are stuck on this.
In your for loop, body must be as that
newWord[--j] = a.charAt(i);. It's because if the lenght of array is 8, its indexes are 0-7. So we first decrement j and then use it as array pointer.
public class Test {
public static String reverse(String a) {
int size= a.length();//size of string
char[] newWord = new char[size];//intialize
for (int i = size-1,j=0; i >=0 ; i--,j++) {//loop start from 7 to 0
newWord[j] = a.charAt(i);// and reverse string goes from 0 to 7
}
return new String(newWord);
}
public static void main(String a[]) {
String word = "abcdefgh";
System.out.println(reverse(word));
}
}
static void reverse {
String word = "Hello World";
StringBuilder str = new StringBuilder(word);
str.reverse();
System.out.println(str);
}
or you could do
new StringBuilder(word).reverse().toString()
public static void main(String[] args) {
String input = "hello world";
String output = new String();
for (int i = input.length() - 1; i >= 0; i--) {
output = output + input.charAt(i);
}
System.out.println(output);
}
package Reverse;
import java.util.*;
public class StringReverse {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a String: ");
String original = input.nextLine();
String rev = "";// Initialize as Empty String
for(int i = original.length() - 1 ; i>=0 ; i--){
rev += original.charAt(i);
}
System.out.println("Reverse form: "+rev);
}
}

How to separate an array list into individual letters in Java

I am working on an assignment that wants me to create a program that accepts a text file with words in it, goes through every word, and then outputs the word with the most amount of double letters. So if a text file had 2 words, (past and progressive for example), it would output progressive. My problem is getting the program to compare each letter in a word. Specifically I cant seem to figure out how to split each word into its letters. Here is what I have so far.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Doubles {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
///Prompts the user to give a file.
System.out.println("Enter the location of your file...");
String location = keyboard.next();
Scanner file = null;
List<String> list = new ArrayList<String>();
///If the the file location is wrong, give an error.
try {
file = new Scanner(new File(location));
} catch (FileNotFoundException e) {
System.out.println("Error: File not found");
System.exit(1);
}
while(file.hasNext()){
String word = file.nextLine();
list.add(word);
}
///System.out.println(list);
keyboard.close();
doublefinder(list);
}
private static void doublefinder(List<String> list) {
///Code to separate and compare letters.
}
}
I have tried many different approaches but I can't seem to find a solution. Any help would be much appreciated.
You can use the .toCharArray method to create a char array where each element is a letter of the word.
http://crunchify.com/java-simple-way-to-convert-string-to-char-array/
An example implementation is as follows:
public static boolean isDoubleword(String str){
char[] letters = str.toCharArray();
for(int i = 0; i< letters.length-1; i++){
if(letters[i] == letters[i+1])return true;
}
return false;
}
The above function takes a string and returns if the string is a double word.
The method could look like that
private String doubleFinder(List<String> list){
int maxDoubleLetters = 0;
int maxDoubleLettersID = 0; // the position of the word in your list
for(int n = 0; n < list.size(); n++){ // cycle throught each word
String word = list.get(n); // get a word from the list
char[] letters = word.toCharArray(); // split the word into letters
int doubleLetters = 0;
for(int i = 1; i < letters.length; i++){ // search for all double letters
if(letters[i] == letters[i-1]) doubleLetters++;
}
if(doubleLetters > maxDoubleLetters){
maxDoubleLetters = doubleLetters;
maxDoubleLettersID = n;
}
}
if(maxDoubleLetters > 0)
return list.get(maxDoubleLetters);
else
return null;
}
The method shown above will return the word with the highest number of double letters. If the file does not contain any words with double letters the method will return null.
Note: This will not work for words containing triple letters.
If you have any more questions fell free to ask in the comment section.
Arem,
The approach that I would use is to make a method that takes in a string and returns the number of double letters. This can be accomplished using the String.toCharArray(); function. You can then iterate through that array to compare the letters to see how many double letters there are in a string.
e.g.
public static int numDoubles(String str) {
int numDoubles = 0;
char[] blah = str.toCharArray()
for(int i = 0; i < str.length(); i++ {
//if the character == nextChar
numDoubles++;
}
return numDoubles;
}
Use that return value to compare your strings.

Changing input so in can take any length of string, problems with output

Currently I have a method that asks user for an input string but only outputs the first 16 characters! The method is supposed to take in any length of string then output the characters in 4x4 blocks after it does the following: first row remains the same. Shift the second row one position to the left, then shifts the third row two positions to the left. Finally, shift the fourth row three positions to the left. As of now it will only output the first 4x4 block
Also I am not sure how I can change the method so it doesnt ask for user input
I would like it to use a given string like:
String text = shiftRows("WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO");
"WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO" is the given encrypted string I would like to use. but without asking for user input..I keep getting errors and incorrect outputs..please show how I might fix this
code I am using:
public class shiftRows {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String[] input= new String[4];
String[] output= new String[4];
System.out.println("Enter a String");
String inputStr = sc.next();
for (int i = 0, n = 0; i < 4; i++, n+=4) {
input[i] = inputStr.substring(0+n, 4+n);
}
// -
output[0] = input[0];
for(int i=1; i<4; i++)
{
output[i] = Shift(input[i],i);
}
for(int i=0; i<4; i++)
{
System.out.println(output[i]);
}
}
public static String Shift(String str, int shiftNum)
{
char[] out = new char[4];
if(shiftNum==1)
{
out[0]=str.charAt(1);
out[1]=str.charAt(2);
out[2]=str.charAt(3);
out[3]=str.charAt(0);
}
if(shiftNum==2)
{
out[0]=str.charAt(2);
out[1]=str.charAt(3);
out[2]=str.charAt(0);
out[3]=str.charAt(1);
}
if(shiftNum==3)
{
out[0]=str.charAt(3);
out[1]=str.charAt(0);
out[2]=str.charAt(1);
out[3]=str.charAt(2);
}
return new String(out);
}
}
Here's a good way to do it :
import java.util.Scanner;
public class shiftRows {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String inputStr = "WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO";
for (int i = 0 ; i < inputStr.length() ; i++){
System.out.print(inputStr.charAt(i));
if ((i + 1)%4 == 0) System.out.println();
}
}
}
If you want to stock it into a String, just concatenate at each loop and add a "\n" each time the if test is valid.

Morsecode using static

I have this program but i have a few problems:
This is the place where i do the calcs.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class MorseCode {
public MorseCode()
{
}//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 = "C:\\APCS Course B\\Unit 4\\Unit 4 Documents\\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);
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
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)
{
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
}//end Translate Class
The main methods:
import javax.swing.JOptionPane;
import java.io.*;
import java.util.Scanner;
public class MorseCodeTester
{
public static void main(String[] args)throws IOException
{
String userInput;
final String SENTINEL = "0";//for exiting program when entered
//object creation
MorseCode text = new MorseCode();
//getting user input to be translated
do
{
Scanner in = new Scanner(System.in);
System.out.print("Please enter what you wish to translte to Morse code (no punctuation): ");
userInput = in.nextLine();
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
So my program is when I put in a input the output shows black even tho in the main methods i did the calculation that would convert it to Morse Code. Also is there any suggestions on if i could use the static identifier in any of my methods.
Here is the text file:
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 code should use a hashmap to key the morse code by letter, this makes your code much simpler.
Getting the morsecode for a letter is then a simple lookup.
Also you could just load the data once, maybe in the Constructor of MorseCode.
But to get at your question, you are just not printing the output. Just returning it and not showing it on the console.
if you change your toString method to look like this, it should print out something.
public String toString(String a, String[] b) {
System.out.println("Input: " + a);
System.out.print("Output:"); // changed to a print, to avoid newline
String output = "";
for (int i = 0; i < b.length; i++) {
output = output + b[i];
}
System.out.println(output); // this was missing
return output;
}//end toString method

Categories

Resources