Given a string and an integer value x, return a new string with the first x characters
of the original string now at the end. Make sure there are enough characters before
attempting to move them to the end of the string.
Sample Data :
Data File: stringChopper.dat
apluscompsci 3
apluscompsci 5
apluscompsci 1
apluscompsci 2
apluscompsci 30
apluscompsci 4
Sample Output : (output needs to be exact)
uscompsciapl
compsciaplus
pluscompscia
luscompsciap
no can do
scompsciaplu
My code:
public class StringChopperRunner_Cavazos {
public static void main(String[] args) throws IOException {
Scanner fileIn = new Scanner(new File("stringChopper.dat"));
while(fileIn.hasNext()) {
System.out.println(StringChopper.chopper(fileIn.next(), fileIn.nextInt()));
}
}
}
class StringChopper {
public static String chopper(String word1, int index) {
if(word1.length() < index - 1){
return "no can do";
}
else {
return word1;
}
}
}
So my question is; How can I return the String with the index number indicated if it's less than that to make sure there are ENOUGH letters printed?
Use String#substring to find different portions of a String and then concatenate them together using the + operator.
if (word1.length() < index - 1){
return "no can do";
} else {
return word1.substring(index) + word1.substring(0, index);
}
Related
the code below is meant to count each time character 'x' occurs in a string but it only counts once ..
I do not want to use a loop.
public class recursionJava
{
public static void main(String args[])
{
String names = "xxhixx";
int result = number(names);
System.out.println("number of x: " + result);
}
public static int number (String name)
{
int index = 0, result = 0;
if(name.charAt(index) == 'x')
{
result++;
}
else
{
result = result;
}
index++;
if (name.trim().length() != 0)
{
number(name);
}
return result;
}
}
You could do a replacement/removal of the character and then compare the length of the resulting string:
String names = "xxhixx";
int numX = names.length() - names.replace("x", "").length(); // numX == 4
If you don't want to use a loop, you can use recursion:
public static int number (String name)
{
if (name.length () == 0)
return 0;
int count = name.charAt(0)=='x' ? 1 : 0;
return count + number(name.substring(1));
}
As of Java 8 you can use streams:
"xxhixx".chars().filter(c -> ((char)c)=='x').count()
Previous recursive answer (from Eran) is correct, although it has quadratic complexity in new java versions (substring copies string internally). It can be linear one:
public static int number(String names, int position) {
if (position >= names.length()) {
return 0;
}
int count = number(names, position + 1);
if ('x' == names.charAt(position)) {
count++;
}
return count;
}
Your code does not work because of two things:
Every time you're calling your recursive method number(), you're setting your variables index and result back to zero. So, the program will always be stuck on the first letter and also reset the record of the number of x's it has found so far.
Also, name.trim() is pretty much useless here, because this method only removes whitespace characters such as space, tab etc.
You can solve both of these problems by
making index and result global variables and
using index to check whether or not you have reached the end of the String.
So in the end, a slightly modified (and working) Version of your code would look like this:
public class recursionJava {
private static int index = 0;
private static int result = 0;
public static void main(String[] args) {
String names = "xxhixx";
int result = number(names);
System.out.println("number of x: " + result);
}
public static int number (String name){
if(name.charAt(index) == 'x')
result++;
index++;
if(name.length() - index > 0)
number(name);
return result;
}
}
You can use StringUtils.countMatches
StringUtils.countMatches(name, "x");
I have to make a program that reads each word a file and makes an index of which lines the word occurs on in alphabetical order.
for example, if the file had:
a white white dog
crowded around the valley
the output should be:
a
around: 2
crowded: 2
dog: 1
the: 2
valley: 1
white: 1, 1
When my file contains:
one fish two fish blue fish green fish
cow fish milk fish dog fish red fish
can you find a little lamb
can you find a white calf
THE OUTPUT IS WRONG!: (NOT IN ALPHA ORDER)
a: 3 4
calf: 4
find: 3 4 4
lamb: 3
little: 3
white: 4
you: 3 4
blue: 1
can: 3
cow: 2
dog: 2
green: 1 1 2 2 2 2
milk: 2
red: 2
two: 1 1 1
fish: 1
one: 1
Here is my code::
INDEXMAKER MASTER CLASS
import java.io.*;
import java.util.*;
public class IndexMaker {
private ArrayList<Word> words;
private String fileName;
private String writeFileName;
public IndexMaker(String fileName, String writeFileName) {
this.fileName = fileName;
this.writeFileName = writeFileName;
words = new ArrayList<Word>();
}
public void makeIndex() {
try {
File file = new File(fileName);
Scanner lineScanner = new Scanner(file);
int lineNum = 0;
while (lineScanner.hasNext()) {
lineNum++;
Scanner wordScanner = new Scanner(lineScanner.nextLine());
while (wordScanner.hasNext()) {
String word = wordScanner.next().toLowerCase();
if (!words.contains(new Word(word))) {
insertInto(word, findPosition(word), lineNum);
} else {
addLineNum(word, lineNum);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void displayIndex() {
try {
//FileWriter fileWriter = new FileWriter(new File(writeFileName));
//BufferedWriter writer = new BufferedWriter(fileWriter);
for (Word word : words)
System.out.println(word.getWord() + ": " + word.getLineNums());
} catch (Exception e) {
}
}
private int findPosition(String word) {
for (int i = 0; i < words.size(); i++) {
if (word.compareTo(words.get(i).getWord()) <= 0)
return i;
}
return 0;
}
private void insertInto(String word, int pos, int lineNum) {
words.add(pos, new Word(word, String.valueOf(lineNum)));
}
private void addLineNum(String word, int lineNum) {
int pos = findPosition(word);
words.get(pos).addLineNum(lineNum);
}
}
WORD CLASS
public class Word {
private String word;
private String lineNums;
public Word(String word, String lineNum) {
this.word = word;
this.lineNums = lineNum;
}
public Word(String word) {
this.word = word;
this.lineNums = "";
}
public String getWord() {
return word;
}
public String getLineNums() {
return lineNums;
}
public void addLineNum(int num) {
lineNums += " " + num;
}
#Override
public boolean equals(Object w) {
if (((Word)w).getWord().equals(word))
return true;
else
return false;
}
}
CLIENT
public class Client {
public static void main(String[] args) {
IndexMaker indexMaker = new IndexMaker("readme.txt", "readme.txt");
indexMaker.makeIndex();
indexMaker.displayIndex();
}
}
any help would be appreciated, thanks.
I can't find your definition of compareTo. It seems this would be the key part of your program?
Properly implement your compareTo and confirm it works properly by printing the results of comparisons using System.out.println
Doing your own comparison is "ok" in that it will work if you do it properly. The other thing you could do would be to implement Comparable and then you can get Java to sort a list of words for you.
I'm trying to write a method that accept a string and print an
inverted triangle from it. For example, if I had
trianglePrint("abcdefgh"), the output would be
abcdefgh
abcfgh
abgh
ab
It kinda of works...it's just that I'm getting the following errors
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
-1 at Triangle.trianglePrint(Triangle.java:39) at Triangle.trianglePrint(Triangle.java:43) at
Triangle.trianglePrint(Triangle.java:43) at
Triangle.trianglePrint(Triangle.java:43) at
Triangle.trianglePrint(Triangle.java:43) at
Triangle.trianglePrint(Triangle.java:17) at
Triangle.main(Triangle.java:6)
Any suggestions on what I'm doing wrong? Suggestions on a more
efficient way to code this, will be appreciated too.
public class Triangle
{
public static void main(String[] args)
{
trianglePrint("abcdefgh");
}
public static void trianglePrint(String string)
{
int length,terms ;
length =string.length() ;
if (length%2==0)
terms = (length/2);
else
terms = (length/2) +1 ;
trianglePrint(string,terms,length);
}
public static void trianglePrint(String string,int terms,int length)
{
String [] Array = new String [terms];
int padterm= length ;
/*if (length%2==0)
terms = (length/2);
else
terms = (length/2) +1 ;
*/
if (terms == 1)
if (length%2==0)
Array[0]=pad(string.substring(0,2),padterm) ;
else
Array[0]=pad(string.substring(0,1),padterm) ;
else
Array[terms-1]=pad((string.substring(0, terms)
+string.substring(length-terms)),padterm);
//use to monitor value of term
System.out.println(terms);
//used to monitor actual array content
System.out.println(Array[terms-1]);
trianglePrint(string,(terms-1),length);
}
public static void printList(String[] list,int position)
{
if (position < list.length)
System.out.println(list[position]);
printList(list,position+1);
}
//pads with appropriate spaces
public static String pad(String string,int length)
{
String result ;
if (string.length() >= length)
result = string ;
else
result = pad(" "+ string+" " ,length);
return result ;
}
}
You need a condition to stop the recursion. If terms is 0, then Array[terms-1] will cause Exception, like:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at Triangle.trianglePrint(Triangle.java:46)
So when variable temrs becomes 0, we need to stop recursion. You can add the following code to trianglePrint method, which will make your program work.
if(0 == terms)
{
return;
}
Change
public static void trianglePrint(String string,int terms,int length)
{
to
public static void trianglePrint(String string,int terms,int length)
{
if(0 == terms)
{
return;
}
Output in console;
4
abcdefgh
3
abcfgh
2
abgh
1
ab
I wrote new code to solve the problem for you, using recursion. I believe it is both shorter and more efficient than your existing solution. An assumption goes into this: the strings have an even number of digits (you didn't explain how to handle odd number of digits)
public static void solve(String word) {
solve(word, 0);
}
public static void solve(String word, int it) {
// print starting spaces
for(int i = 0; i < it; i++)
System.out.print(" ");
// print out string
System.out.print(word);
// print new line
System.out.println();
if(word.length() > 2) {
int newlengthperside = (word.length() - 2)/2;
solve( word.substring(0, newlengthperside) + word.substring(word.length() - newlengthperside), it+1);
}
}
To understand this code, first look at the main method. We have a for loop that prints out a certain number of spaces before the string, based on the variable passed to the method, then we print out the string, then we print out a new line. Afterwards, we determine if the length of the string is not finished yet, and we take the left side and the right side of the new string, and call the method again. This recursion will terminate once the string has less than or equal to 2 characters.
We also make the method easy to use by overloading the method with another solve that just takes in a word, and calls the main solve method with that word and 0, the number of spaces to initially print.
Your algorithm (as I understand it), seems to simplify into this
public static void trianglePrint(String in,
int offset) {
if (offset >= in.length()) { // Terminating condition.
return;
}
StringBuilder sb = new StringBuilder(offset); // For padding.
for (int i = 0; i < offset; i++) {
sb.append(' ');
}
final String padding = sb.toString(); // This is the padding, so don't clear.
sb.append(in); // Add the current input.
sb.append(padding); // Add more "invisible" padding.
System.out.println(sb.toString()); // print it.
int left = in.length() / 2; // One half.
String lh = in.substring(0, left - 1); // the left.
String rh = in.substring(left + 1, in.length()); // the right.
trianglePrint(lh + rh, offset + 1); // recurse.
}
public static void trianglePrint(String in) {
trianglePrint(in, 0);
}
You're doing recursion to simply decrement the terms argument. This is not a good use of recursion (outside of a functional programming language optimized for tail recursion) and would be better implemented using a for loop. The good recursive paradigm for this would be to actually shorten the string:
public static void trianglePrint(String string) {
trianglePrint(string, 0);
}
public static void trianglePrint(String string, int padding) {
for (int i = 0; i < padding; i++) {
System.out.print(" ");
}
System.out.println(string);
if (string.length > 2) {
int midpoint = string.length()/2; //assumes string length is even
trianglePrint(string.substring(0, midpoint - 1) + string.substring(midpoint + 1), padding + 1);
}
}
Not necessarily the fastest code, but very simple.
A slightly different approach can simplify further by leveraging the recursion more fully for the padding. StringBuilder also makes it easier to delete from the middle of a string:
public static void trianglePrint2(String s) {
System.out.println(s);
int mid = s.length()/2;
if (!s.replace(" ", "").equals("")) //if not all spaces
trianglePrint(" " + new StringBuilder(s).delete(mid-1, mid+1) + " ");
}
or alternatively (more efficient):
public static void trianglePrint(String s) {
trianglePrint(s, s.length()/2);
}
public static void trianglePrint(String string, int mid) {
System.out.println(s);
if (string.length() > mid)
trianglePrint(" " + new StringBuilder(s).delete(mid-1, mid+1), mid);
}
Both will work with odd or even lengths.
I have tried to develop code for project euler
Problem 17
I have successfully written a java program and the output appears as expected. But however the online judge says it is the wrong answer. Have a look at my code:
package projectEuler;
import java.util.*;
public class Problem17 {
/**
* #param args
*/
static String []units={"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
static String []special={"Ten","Eleven","Twelve","Thirteen","Fourteen",
"Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
static String []tens={"","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy",
"Eighty","Ninety"};
static String hundredValue="Hundred and";
public static void main(String[] args)
{
long totalLength=0;
for(int currentNumber=1;currentNumber<=1000;currentNumber++)
{
String currentWord=getWords(currentNumber);
// System.out.println(currentNumber+"->"+currentWord.replaceAll(" ",""));
totalLength+=currentWord.replaceAll(" ","").length();
}
System.out.print("The total length of all the word is :"+totalLength);
/*Scanner input = new Scanner(System.in);
System.out.print("Enter a number :");
int num = input.nextInt();
System.out.print(getWords(num));*/
}
public static String getWords(int num)
{
//Find the equivalent word and return it
String wordValue="";
switch(String.valueOf(num).length())
{
case 1:
wordValue=operateOn_1(num);
break;
case 2:
wordValue= operateOn_2(num);
break;
case 3:
wordValue= operateOn_3(num);
break;
default:
wordValue="One Thousand";
}
return wordValue;
}
public static String operateOn_3(int num)
{
String result="";
result= Problem17.units[num/100]+" "+
Problem17.hundredValue+" "+
operateOn_2(Integer.parseInt((String.valueOf(num).substring(1))));
return result;
}
public static String operateOn_2(int num)
{
String result="";
if(String.valueOf(num).charAt(0)=='1')
{
result=Problem17.special[num%10];
}
else
{
result=Problem17.tens[Integer.parseInt(String.valueOf((String.valueOf(num)).charAt(0)))];
result+=" "+operateOn_1(num%10);
}
return result;
}
public static String operateOn_1(int num)
{
return (Problem17.units[num]);
}
}
The total length which the program found out as 21592 but it is wrong according to project euler. If any could have a look at my code and help me please...
It looks like the problem is with the word 'and'
static String hundredValue="Hundred and";
Which should not occur for numbers such as 300 (Three hundred and)
In addition to the "Hundred and"-problem described by Christopher, there is another issue:
You pass an int to operateOn_2, which you then convert to a string. This way, you miss the leading zero when converting a number like 101, which is converted to One Hundred and Eleven
This program I'm making isn't compiling right, I keep getting the error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -9
at java.lang.String.charAt(String.java:687)
at pro1.main(pro1.java:161)
Here's my code:
import java.io.*;
import java.util.*;
public class pro1 {
static String str="";
static String str1="";
static int range=250;
static int length;
static String key="";
static String ep="";
static String pt="";
static char temp;
static int t,p,h;
static int r,x,y,z,w;
static Random generator = new Random();
static public String getContents(File aFile)
{
StringBuilder contents = new StringBuilder();
try {
BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
String line = null;
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
str1=contents.toString();
return str1;
}
public static void main (String args[]) throws IOException {
File testFile = new File("/home/amritha/Desktop/sam.txt");
System.out.println("Original file contents: " + getContents(testFile));
System.out.println("message:"+str1);
String sbox="abcdefghijklmnopqrstuvwxyz";
length=str1.length()-1;
for(int i=0;i<length;i++)
{
t=(int)str1.charAt(i);
if(t==32)
{
int t1=32;
temp=(char)t;
}
else
{
range=generator.nextInt(26)+1;
temp=sbox.charAt(range);
}
key+=""+temp;
}
System.out.println("Key:"+key);
for(int i=0;i<length;i++)
{
t=(int)str1.charAt(i);
{
if(t==32)
{
t=32;
temp=(char)t;
}
else
{
t-=97;
}
}
p=(int)key.charAt(i);
{
if(p==32)
{
p=32;
temp=(char)p;
}
else
{
p-=97;
}
}
if((t==32)&&(p==32))
{
int v=32;
temp=(char)v;
}
else
{
r=(t+p)%26;
temp=sbox.charAt(r);
}
ep+=""+temp;
}
System.out.println("Encrypted Text:"+ep);
for(int i=0;i<length;i++)
{
y=(int)ep.charAt(i);
{
if(y==32)
{
y=32;
temp=(char)y;
}
else
{
y-=97;
}
}
x=(int)key.charAt(i);
{
if(x==32)
{
x=32;
temp=(char)x;
}
else
{
x-=97;
}
}
if((x==32)&&(y==32))
{
int w=32;
temp=(char)w;
}
else
{
z=(y-x)%26;
temp=sbox.charAt(z);
}
pt+=""+temp;
}
System.out.println("deccrypted Text:"+pt);
}
}
Your code looks fishy in every way, and I cannot imagine anyone wanting to read 170 lines of this code.
Look at the exception: It tells you exactly what's going wrong: You pass -9 to charAt() as an index, which is - obviously - out of range, as you should only pass 0 ... (length-1) in there.
And it gives you the line number, too... so go to line number 161 and look what's in there and how it got there.
My guess would be it has something to do with this line:
z=(y-x)%26;
If x is larger than y the result of the % operation may be negative (or 0). And charAt (which is what z is given as parameter to) expects a positive value.
You should try:
z=Math.abs(y-x)%26;
Edit: As a side note, this shouldn't be to hard to figure out on your own, by looking at the exception as was pointed out by others, or in the worst case using a debugger and seeing exactly what values the different variables have and why when the exception occurs.