I'm trying to sort a list of strings in array into alphabetical order without using the sort method.
public static String[] sortedAdjectives(String[] original)
{
String[] sortedArray;
int aValue = 65;
String word = "";
sortedArray = new String[25];
for(int i = 0; i <25; i++)
{
original[i]=word;
char c = word.charAt(0);
sortedArray[c-aValue]=word;
}
return sortedArray;
Is my method, and
public static void main(String[] args) throws FileNotFoundException {
Scanner names = new Scanner(new File("names.txt"));
Scanner adjectives = new Scanner(new File("adjectives.txt"));
String[] adjectiveArray;
adjectiveArray = new String[25];
int counter = 0;
while (counter<25)
{
String in = adjectives.next();
fixCapitalization(in); //method that fixes capitalization
adjectiveArray[counter]=in;
counter++;
}
sortedAdjectives(adjectiveArray);
Is where I put the items from the file into an array. I'm getting
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at Hmwk.sortedAdjectives(Hmwk.java:56)
at Hmwk.main(Hmwk.java:24)
When I try to run my program and I can't figure out where I'm going wrong. If you could point me in the right direction i'd be much appreciative. Thanks for your time.
You have word initialized as an empty string:
String word = "";
Then you are calling charAt(0) on an empty string. Can't do that.
Your string needs to be at least longer than 1 character in order to call that method.
You made a little mistake in the for loop.
It should probably be word = original[i]; which you did it inversely and makes the word never take the original parameter as reference.
Also a few things to improve here: using arraylist would have better extensibility and avoid erasing repetitive letters.
Related
Trying to write a java method that will take a string, loop through it and where it finds a vowel (A,E,I,O,U,Y) replace it with the vowel plus "OB".
I've written the below but it isn't working as I'd expect and doesn't seem to be matching the current character in my string with the vowels from my list. (The program compiles and runs so it isn't an issue with not importing necessary bits at the beginning. The input string will always be uppercase and only contain alphas.) I'm struggling to figure out where I'm going wrong.
Can anyone help?
public static String obifyText(String text) {
String[] myList = new String[] {"A","E","I","O","U","Y"};
StringBuilder tempText = new StringBuilder(text);
String obify = "OB";
for (int i = 0; i < text.length() -1 ; i ++ ) {
if ( Arrays.asList(myList).contains(tempText.charAt(i)) ) {
System.out.println(tempText.charAt(i)+" found.");
tempText = tempText.insert((i+1),obify);
}
}
text = tempText.toString();
return text;
}
Don't play with indexes.
Managing with indexes could be difficult when you are dealing with changing the string.
Loop on the chars itself as follows:
public static void main(String[] args){
String[] myList = new String[] {"A","E","I","O","U","Y"};
String text = "AEE";
StringBuilder tempText = new StringBuilder("");
String obify = "OB";
for (char c : text.toCharArray()){
tempText = tempText.append(c);
if ( Arrays.asList(myList).contains(c+"") ) {
System.out.println(c+" found.");
tempText = tempText.append(obify);
}
}
text = tempText.toString();
System.out.println(text);
}
OUTPUT:
A found.
E found.
E found.
AOBEOBEOB
charAt returns a char, but myList stores String elements. An array of Strings can never contain values of char. Your if statement never runs.
You can convert the char value to a string:
Arrays.asList(myList).contains(Character.toString(tempText.charAt(i)))
There's just one more problem with your code.
When the code inserts OB after a vowel, there is a side effect: a new vowel O is created. Your code then tries to insert OB after the new O. This is undesired, right?
To make it not do this, you can loop from the end of the string to the start:
for (int i = text.length() - 1; i >= 0 ; i--) {
If this is not a homework question to practice using StringBuilder or for loops, here's a one liner solution using regex:
return text.replaceAll("([AEIOUY])", "$1OB");
You compare two different types in Arrays.asList(myList).contains(tempText.charAt(i)), Arrays.asList(myList) is a List<String> and tempText.charAt is a char. So the contains check will never result in true.
One possible fix, change myList to Character[]
Character[] myList = new Character[] {'A','E','I','O','U','Y'};
There is another problem with the actual insertion, see Pankaj Singhal answer for a solution to that.
Good day, guys,
I'm working on a program which requires me to input a name (E.g Patrick-Connor-O'Neill). The name can be composed of as many names as possible, so not necessarily restricted to solely 3 as seen in the example above.But the point of the program is to return the initials back so in this case PCO. I'm writing to ask for a little clarification. I need to separate the names out from the hyphens first, right? Then I need to take the first character of the names and print that out?
Anyway, my question is basically how do I separate the string if I don't know how much is inputted? I get that if it's only like two terms I would do:
final String s = "Before-After";
final String before = s.split("-")[0]; // "Before"
I did attempt to do the code, and all I have so far is:
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
String[] x = input.split("-");
int u =0;
for(String i : x) {
String y = input.split("-")[u];
u++;
}
}
}
I'm taking a crash course in programming, so easy concepts are hard for me.Thanks for reading!
You don't need to split it a second time. By doing String[] x = input.split("-"); you have an Array of Strings. Now you can iterate over them which you already do with the enhanced for loop. It should look like this
String[] x = input.split("-");
String initials = "";
for (String name : x) {
initials += name.charAt(0);
}
System.out.println(initials);
Here are some Java Docs for the used methods
String#split
String#charAt
Assignment operator +=
You can do it without splitting the string by using String.indexOf to find the next -; then just append the subsequent character to the initials:
String initials = "" + input.charAt(0);
int next = -1;
while (true) {
next = input.indexOf('-', next + 1);
if (next < 0) break;
initials += input.charAt(next + 1);
}
(There are lots of edge cases not handled here; omitted to get across the main point of the approach).
In your for-each loop append first character of all the elements of String array into an output String to get the initials:
String output = "";
for(String i : x) {
output = output + y.charAt(0);
}
This will help.
public static void main(String[] args) {
String output = "";
String input = "Patrick-Connor-O'Neil-Saint-Patricks-Day";
String[] brokenInput = input.split("-");
for (String temp : brokenInput) {
if (!temp.equals(""))
output = output + temp.charAt(0);
}
System.out.println(output);
}
You could totally try something like this (a little refactor of your code):
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = "";
System.out.println("What's your name?");
input = scan.nextLine();
String[] x = input.split("-");
int u =0;
for(String i : x) {
String y = input.split("-")[u];
u++;
System.out.println(y);
}
}
}
I think it's pretty easy and straightforward from here if you want to simply isolate the initials. If you are new to Java make sure you use a lot of System.out since it helps you a lot with debugging.
Good coding.
EDIT: You can use #Mohit Tyagi 's answer with mine to achieve the full thing if you are cheating :P
This might help
String test = "abs-bcd-cde-fgh-lik";
String[] splitArray = test.split("-");
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < splitArray.length; i++) {
stringBuffer.append(splitArray[i].charAt(0));
}
System.out.println(stringBuffer);
}
Using StringBuffer will save your memory as, if you use String a new object will get created every time you modify it.
This question already has answers here:
Reverse a string in Java
(36 answers)
Closed 8 years ago.
I recently attended an interview where I was asked to write a program.
The problem was:
Take a string. "Hammer", for example.
Reverse it and any character should not be repeated.
So, the output will be - "remaH".
This is the solution I gave:
public class Reverse {
public static void main(String[] args) {
String str = "Hammer";
String revStr = "";
for(int i=0; i<=str.length()-1;i++){
if(revStr.indexOf(str.charAt(i))==-1){
revStr = str.charAt(i)+revStr;
}
}
System.out.println(revStr);
}
}
How I can improve the above?
The problem is String is immutable object, and when using operator+ to concat a char with the current result, you actually create a new string.
This results in creating strings of length 1+2+...+n, which gives you total performance of O(n^2) (unless the compiler optimizes this for you).
Using a StringBuilder instead of concatting strings will give you O(n) performance, and with much better constants as well.
Note that a StringBuilder offers an efficient append() implementaiton, so you need to append elements to it, and NOT add them at the head of your StringBuilder.
You should also reconsider usage of indexOf() - if a characters cannot appear twice at all, consider using a Set<Chatacter> to maintain the list of 'used' characters, if it can appear twice, but not one after the other (for example "mam" is valid) - there is really no need for the indexOf() in the first place, just check the last character read.
Here is a solution without using any stringbuilder or intermediary String objects, just treating Strings as arrays of chars; this should be more efficient.
import java.util.Arrays;
public class Reverse {
public static void main(String[] args) {
String str = "Hammer";
String revStr = null;
char [] chars = str.toCharArray();
char [] reversedChars = new char[chars.length];
// copy first char
reversedChars[reversedChars.length - 1] = chars[0];
// process rest
int r = reversedChars.length - 2;
for(int i = 1 ; i < chars.length ; i++ ){
if(chars[i] != chars[i-1]){
reversedChars[r] = chars[i];
r--;
}
}
revStr = new String(Arrays.copyOfRange(reversedChars, r+1, reversedChars.length));
System.out.println(revStr);
}
package com.in.main;
public class Reverse {
public static void main(String[] args) {
String str = "Hammer";
StringBuilder revStr= new StringBuilder("");
for(int i=str.length(); i>=0;i--){
if(revStr.indexOf(str.charAt(i))==-1){
revStr.append(str.charAt(i));
}
}
System.out.println(revStr);
}
}
This question already has answers here:
Reversing characters in each word in a sentence - Stack Implementation
(6 answers)
Closed 9 years ago.
I am supposed to write a code that reads a sentence from the user and prints the characters of the words in the sentence backwards. It should include a helper method that takes a String as a parameter and returns a new String with the characters reversed. The individual words are reversed, for example the sentence "Hi dog cat". would print "iH god tac". I can make the entire sentence reverse but i cant figure out how to reverse individual words. Thanks! Also, i know how to return the String once i have found it, but i just cant get the right string
import java.util.Scanner;
import java.util.Stack;
public class ReverseStack
{
public static void main(String[] args)
{
String sentence;
System.out.println("Enter a sentence: ");
Scanner scan = new Scanner(System.in);
sentence = scan.nextLine();
String k = PrintStack(sentence);
}
private static String PrintStack(String sentence)
{
String reverse;
String stringReversed = "";
Stack<String> stack= new Stack<String>();
sentence.split(" ");
for(int i=0;i<sentence.length(); i++)
{
stack.push(sentence.substring(i, i+1));
}
while(!stack.isEmpty())
{
stringReversed += stack.pop();
}
System.out.println("Reverse is: " + stringReversed);
return reverse;
}
}
I will type an expatiation so you can still get the experience of writing the code, rather than me just giving you the code.
First create a Stack of Characters. Then use add each character in the String to the Stack, starting with the first char, then the second, and so on. Now either clear the String or create a new String to store the reversed word. Finally, add each character from the Stack to the String. This will pull the last character off first, then the second to last, and so on.
Note: I believe you have to use the Character wrapper class, rather than the primitive char; I may be incorrect about that though.
If you aren't familiar with how Stacks work, here is a nice interactive tool to visualize it: http://www.cise.ufl.edu/~sahni/dsaaj/JavaVersions/Stacks/AbstractStack/AbstractStack.htm
Change:
Stack<String> stack = new Stack<String>();
to be
Stack<Character> stack = new Stack<Character>();
and refactor your methods code as necessary; i.e.
What is the easiest/best/most correct way to iterate through the characters of a string in Java?
I did it with a different kind of stack, but I suspect this might help
private static String reverseWord(String in) {
if (in.length() < 2) {
return in;
}
return reverseWord(in.substring(1)) + in.substring(0, 1);
}
private static String reverseSentence(String in) {
StringBuilder sb = new StringBuilder();
StringTokenizer st = new StringTokenizer(in);
while (st.hasMoreTokens()) {
if (sb.length() > 0)
sb.append(' ');
sb.append(reverseWord(st.nextToken()));
}
return sb.toString();
}
public static void main(String[] args) {
String sentence = "Hi dog cat";
String expectedOutput = "iH god tac";
System.out.println(expectedOutput
.equals(reverseSentence(sentence)));
}
Outputs
true
I want to organize a text file with multiple data
A 33 9.25
V 92 1.123
H 100 2.4
into a parallel Array
So far I got to declaring the arraylist and i know i need to do something with a while loop and hasnext... not sure where to go from there.
public static void main(String[] args) throws IOException
{
Scanner fileIn = new Scanner ( new File("sortdata.txt"));
ArrayList<Character> array1 = new ArrayList<Character>();
ArrayList<Integer> array2 = new ArrayList<Integer>();
ArrayList<Double> array3 = new ArrayList<Double>();
while (fileIn.hasNext())
String i = fileIn.next();
int k = 0;
for(i.index(k);i.length();i.index(k++))
if (i.index(k) =='.')
{
}
}
I know some of my code is wrong but I've been looking at it for a long time, think i'm just missing something minor here.
After reading each line from the file here String i = fileIn.next();, trim() the String(to eliminate leading and trailing white spaces as suggested by #X86) and then follow the below steps.
Split the String on white space using the String#split() method.
The String[] returned by the split method above contains all the 3 data required.
From the string[0] get the character using string.charAt(0) and put it into the Character ArrayList.
Parse string[1] as a Integer using Integer.parseInt(string[1]) and put it into the Integer ArrayList.
Parse string[2] as a Double using Double.parseDouble(string[2]) and put it into the Double ArrayList.
This should work:
while (fileIn.hasNextLine()) {
String c[]= fileIn.nextLine().split(" ");
array1.add(new Character(c[0].charAt(0)));
array2.add(new Integer(c[1].trim()));
array3.add(new Double(c[2].trim()));
}