Array wont work with small sentences - java

If I change the text to two words the program wont output anything. Not a clue on how to fix this, thanks in advance.
public class test {
public static void main(String args[]) {
String text = "The cat sat on the mat!"; //Change the string to "Hello there!"
int wordLengthCount [] = new int [20];
String wordCountText = "";
String sentence[] = text.split("[,\\-:\\?\\!\\ ]");
for (int i = 0; i < sentence.length; i++)
{
wordLengthCount[sentence[i].length()]++;
}
for(int wordLength=0; wordLength<sentence.length; wordLength++)
{
if (wordLengthCount[wordLength] != 0){
wordCountText += wordLengthCount[wordLength] + " with length of " + wordLength + "\n";
}
}
System.out.println(wordCountText);
}
}

You need to iterate over all wordLengthCount
Quick fix:
for (int wordLength = 0; wordLength < wordLengthCount.length; wordLength++) {
if (wordLengthCount[wordLength] != 0) {
wordCountText += wordLengthCount[wordLength] + " with length of " + wordLength + "\n";
}
}
Live demo

Related

How can a program print its own source code without reading any file

I've to write a code that outputs its own source code, but I am not allowed to read it from the file.
This is what we got from the teacher:
public class SelfPrint {
public static void main(String[] args) {
System.out.print(getMyText());
}
private static String programText [] = {
....
};
private static String getMyText() {
}
}
Try this.
getMyText has three for statements. The first one prints the first 5 lines of the program. The second one prints the constant value of programText. And the last one prints the rest of the program. So programText will be printed twice.
public class SelfPrint {
public static void main(String[] args) {
System.out.print(getMyText());
}
private static String[] programText = {
"public class SelfPrint {",
" public static void main(String[] args) {",
" System.out.print(getMyText());",
" }",
" private static String[] programText = {",
" };",
" private static String getMyText() {",
" char q = 34, c = 44;",
" String n = System.lineSeparator();",
" StringBuilder sb = new StringBuilder();",
" for (int i = 0; i < 5; i++)",
" sb.append(programText[i]).append(n);",
" for (int i = 0; i < programText.length; i++)",
" sb.append(q + programText[i] + q + c).append(n);",
" for (int i = 5; i < programText.length; i++)",
" sb.append(programText[i]).append(n);",
" return sb.toString();",
" }",
"}",
};
private static String getMyText() {
char q = 34, c = 44;
String n = System.lineSeparator();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++)
sb.append(programText[i]).append(n);
for (int i = 0; i < programText.length; i++)
sb.append(q + programText[i] + q + c).append(n);
for (int i = 5; i < programText.length; i++)
sb.append(programText[i]).append(n);
return sb.toString();
}
}
Test (on Windows11)
C:\temp>javac SelfPrint.java
C:\temp>java SelfPrint > out
C:\temp>diff SelfPrint.java out
C:\temp>echo %ERRORLEVEL%
0

Limiting # of characters per line

I'm a beginner and I'm having trouble trying to display the output so that if its too big it will move it to the next line.
This is what I have so far:
import java.util.Scanner;
public class numberBracket {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("howMany: ");
int howMany = scanner.nextInt();
System.out.println("lineLength: ");
int lineLength = scanner.nextInt();
scanner.nextLine();
printNumbers(howMany, lineLength);
}
public static void printNumbers(int howMany, int lineLength) {
Integer charLength = Integer.valueOf(lineLength);
for(int i = 1; i <= howMany; i ++) {
String t = "[" + i + "]";
while(t.length() > charLength ) {
int index = t.lastIndexOf(' ', charLength);
System.out.print(t.substring(0, index));
t = t.substring(index + 1);
}
System.out.print(t);
}
}
}
So if they enter 10 for the lineLength it would be
[1][2][3]
[4]
and if they entered 12 it would be
[1][2][3][4]
You can use this snippet:
public static void printNumbers(int howMany, int lineLength) {
StringBuilder sb = new StringBuilder();
int length = 0;
for (int i = 1; i <= howMany; i++) {
String t = "[" + i + "]";
if (length + t.length() > lineLength) {
sb.append("\n");
length = 0;
}
length += t.length();
sb.append(t);
}
System.out.println(sb.toString());
}
public static void printNumbers(int howMany, int lineLength) {
String printed = "";
for (int i = 1; i <= howMany; i++) {
String t = "[" + i + "]";
if ((printed.length() + t.length()) > lineLength) {
printed = "";
System.out.println();
}
printed += t;
System.out.print(t);
}
}
I believe you have to check if it has room in the current line before printing.
If it does have room print it, if it doesn't, print in a new line.
public static void printNumbers(int howMany, int lineLength) {
int alreadyPrintedLength = 0;
for(int i = 1; i <= howMany; i ++) {
String t = "[" + i + "]";
int actualCharLength = t.length();
boolean hasRoomInCurrentLine = (alreadyPrintedLength + actualCharLength) <= lineLength;
if (hasRoomInCurrentLine) {
System.out.print(t);
alreadyPrintedLength += actualCharLength;
} else {
System.out.print(System.lineSeparator() + t);
alreadyPrintedLength = actualCharLength;
}
}
}

How can i make for loop a recursive method

How can I make this code a recursive method?
for (int i = 3; i < arr.length; i++) {
writer.write(arr[i] + "\n");
strout += arr[i] + "\n";
}
You can try encapsulating the code in a function:
public static String printRecursive(BufferedWriter writer, String[] arr, int i) throws IOException {
String strout = "";
if(i<arr.length) {
writer.write(arr[i] + "\n");
//System.out.println(arr[i] + "\n");
strout += arr[i] + "\n" + printRecursive(writer,arr,i+1);
}
return strout;
}
And you can call it from main:
String strRec = printRecursive(writer,arr,3);
I hope this help you.
Edited: Added writer according last comment
Something like that?
let arr = [/* array elements */];
let idx = 3;
let stdout = "";
const recursiveMethod = () => {
writer.write(`${arr[idx]}\n`);
strout += `${arr[idx]}\n`;
if(idx < arr.length) {
idx++;
return recursiveMethod();
}
}
recursiveMethod();

What is wrong with this swapping program in Java, why and what should I do?

I am making a multiple string input random swap without using a temp variable.
But when I input, this happens a few times:
This happens more frequently... (note that the first output is always null and some outputs occasionally repeat)
My code:
import java.util.Arrays;
import java.util.Scanner;
public class myFile {
public static boolean contains(int[] array, int key) {
Arrays.sort(array);
return Arrays.binarySearch(array, key) >= 0;
}
public static void println(Object line) {
System.out.println(line);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String finalText = "";
String[] input = new String[5];
String[] swappedInput = new String[input.length];
int[] usedIndex = new int[input.length];
int swapCounter = input.length, useCounter;
for (int inputCounter = 0; inputCounter < input.length; inputCounter++) { //input
println("Enter input 1 " + (inputCounter + 1) + ": ");
input[inputCounter] = in.nextLine();
}
while (--swapCounter > 0) {
do{
useCounter = (int) Math.floor(Math.random() * input.length);
}
while (contains(usedIndex, useCounter));
swappedInput[swapCounter] = input[swapCounter].concat("#" + input[useCounter]);
swappedInput[useCounter] = swappedInput[swapCounter].split("#")[0];
swappedInput[swapCounter] = swappedInput[swapCounter].split("#")[1];
usedIndex[useCounter] = useCounter;
}
for (int outputCounter = 0; outputCounter < input.length; outputCounter++) {
finalText = finalText + swappedInput[outputCounter] + " ";
}
println("The swapped inputs are: " + finalText + ".");
}
}
Because of randomality some times useCounter is the same as swapCounter and now look at those lines (assume useCounter and swapCounter are the same)
swappedInput[swapCounter] = input[swapCounter].concat("#" + input[useCounter]);
swappedInput[useCounter] = swappedInput[swapCounter].split("#")[0];
swappedInput[swapCounter] = swappedInput[swapCounter].split("#")[1];
In the second line you are changing the value of xxx#www to be www so in the third line when doing split you dont get an array with two values you get an empty result thats why exception is thrown in addition you should not use swappedInput because it beats the pourpuse (if i understand correctly yoush shoud not use temp values while you are using addition array which is worse) the correct sollution is to only use input array here is the solution
public class myFile {
public static boolean contains(int[] array, int key) {
Arrays.sort(array);
return Arrays.binarySearch(array, key) >= 0;
}
public static void println(Object line) {
System.out.println(line);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String finalText = "";
String[] input = new String[5];
int[] usedIndex = new int[input.length];
int swapCounter = input.length, useCounter;
for (int inputCounter = 0; inputCounter < input.length; inputCounter++) { //input
println("Enter input 1 " + (inputCounter + 1) + ": ");
input[inputCounter] = in.nextLine();
}
while (--swapCounter >= 0) {
do {
useCounter = (int) Math.floor(Math.random() * input.length);
}
while (contains(usedIndex, useCounter));
// Skip if results are the same
if (useCounter == swapCounter) {
swapCounter++;
continue;
}
input[swapCounter] = input[swapCounter].concat("#" + input[useCounter]);
input[useCounter] = input[swapCounter].split("#")[0];
input[swapCounter] = input[swapCounter].split("#")[1];
usedIndex[useCounter] = useCounter;
}
for (int outputCounter = 0; outputCounter < input.length; outputCounter++) {
finalText = finalText + input[outputCounter] + " ";
}
println("The swapped inputs are: " + finalText + ".");
}
}

String word reverse in Java giving wrong result?

Here is my code to print string characters reversed in Java without using any API. But it's not working properly. Can anybody help me to correct it?
public static void main(String args[]) {
String input = "I am test";
String result = "";
for (int i = input.length() - 1; i > 0; i--) {
Character c = input.charAt(i);
if (c != ' ') {
result = c + result;
} else {
System.out.println(result + " ");
}
}
}
It is giving output "test amtest", while the output should be "test am I".
Please help me to get exact output without using predefined methods or API's.
There are four problems with your implementation:
You do not go all the way down to zero,
You put an end of line after each printout in the loop,
You do not print the "tail" result after the loop is over, and
You do not clear out result after printing it in the loop.
Fixing these issues will give you proper output (demo).
try
public static void main(String args[]) {
String input = "I am test";
String result = "";
int start=input.length()-1;
for (int i = input.length()-1; i >=0; i--) {
Character c = input.charAt(i);
if (c == ' ') {
for(int j=i+1;j<=start;j++)
result +=input.charAt(j);
result+=" ";
start=i-1;
}
else if (i==0)
{
for(int j=0;j<=start;j++)
result +=input.charAt(j);
}
}
System.out.println(result);
}//It is giving output as test amtest
//output should be : test am I
public static void main(String args[]) {
String input = "I am test";
String result = "";
String[] frags = input.split(" ");
for (int i = frags.length - 1; i >= 0; i--) {
System.out.print(frags[i] + " ");
}
System.out.println();
}
You can try recursion as well -
public static void main(String args[]) {
String input = "I am test";
List<String> listOfString = Arrays.asList(input.split(" "));
System.out.println(reverseString(listOfString));
}
private static String reverseString(List<String> input) {
int n = input.size();
String result = "";
if(input.isEmpty()){
return result;
}
if(n>1){
/*adding last element with space and changes the size of list as well
test + " " + [am, I]
test + " " + am + " " + [I]*/
result = input.get(n-1) + " " + reverseString(input.subList(0, n-1));
}else{
result = input.get(n-1);
}
return result;
}
hope it helps.
public static void main(String args[]){
String input = "I am test";
String result="";
for(int i=input.length()-1;i>=0;i--){
result=result+input.charAt(i);
}
System.out.println(result);
}

Categories