Write a program that takes a string input from the user and then outputs the first character, then the first two, then the first three, etc until it prints the entire word. After going down to one letter, print the opposite back up to the full word.
I've gotten the first part done.
Scanner word = new Scanner(System.in);
System.out.println("Enter a word.");
String thing = word.next();
String rest = "";
for(int i=0;i< thing.length();i++){
String w = thing.substring(i,i+1);
rest += w;
System.out.println(rest);
}
This is what it should look like.
C
Co
Com
Comp
Compu
Comput
Compute
Computer
Computer
Compute
Comput
Compu
Comp
Com
Co
C
Strings in Java are indexed starting from 0, so the last character is indexed at length-1.
To iterate from the last character down to the first, the for loop would be for(int i = thing.length () - 1; i >= 0; i--).
Alternatively, recursion would be a simpler solution considering you already obtained the strings that should be printed in reverse.
static void f (String str, int n) {
if (n > str.length ()) return;
String temp = str.substring (0, n); // obtain the string
System.out.println (temp); // print
f (str, n + 1); // go to next substring
System.out.println (temp); // print after returning from the last obtainable substring
}
The function can now be called via f(thing, n);
You can try to implement two arrays, in the first you must split the String entered from the Scanner and in the second you must store the generated aux variable in each iteration of the first array, To finish you must iterate the second array in reverse.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a word: ");
String word = sc.next();
String[] array = word.split("");
int length = array.length;
String[] auxArray = new String[length];
String aux = "";
for (int i = 0; i < length; i++) {
aux += array[i];
auxArray[i] = aux;
System.out.println(aux);
}
for (int i = length - 1; i >= 0; i--) {
System.out.println(auxArray[i]);
}
}
Related
I am trying to reduce the string array by using a for a loop. This is an example I tried to do
User string input: Calculus
User input:5
output: CalcuCalcCalCaC
I have turned the string to a char array but the issue presents itself when trying to print them out multiple times. It only prints once and has the right starting output.
input string: Oregon
input number: 4
output: Oreg
I notice my for loop says that it is not looping when I hover over it on the IDE that I downloaded from JetBrains.
I tried different combinations of decrementing and incrementing but could not get that "for statement is not looping". Other than that I have tried different ways to do something in the for loop but I don't think anything needs to be done for now if the for loop is not looping then, right?
So my question is, how to reduce a string or char array and print the decrement value over and over again?
Here is my code so far for it.
public String wordDown(String userString, int userNum)
{
String stringModded = userString.substring(0, userNum);
char[] charArray = stringModded.toCharArray();
char repeat = ' ';
for(int i = 0; i<userNum; ++i)
{
repeat = (char) (repeat +charArray[i]);
charArray[i] = repeat;
for(int j = 1; i > charArray.length; ++j)
{
String modWord = String.valueOf(charArray[i + 1]);
return modWord;
}
}
return null;
}
public static void main(String[] args)
{
int userNumber;
String userString;
RandomArrayFunctionalities ranMethod = new RandomArrayFunctionalities();
Scanner in = new Scanner(System.in);
System.out.println("\nEnter a word:");
userString = in.next();
System.out.println("\nEnter a number within the word scope that you just enter:");
userNumber = in.nextInt();
System.out.println(ranMethod.wordDown(userString, userNumber));
}
You do not need to modify the original array. Use a StringBuilder to concatenate the successive parts of the word. Use the String.substring(int,int) method to pull out those parts. The example that follows uses a decrementing index to generate the successively smaller substrings.
public String wordDown(String word, int userNum) {
StringBuilder sb = new StringBuilder();
for (int length = userNum ; length > 0 ; --length) {
sb.append(word.substring(0, length));
}
return sb.toString();
}
I think you are over complicating things, you don't need a char array at all and you only need a single loop, and a single return statement:
public String wordDown(String userString, int userNum) {
String finalString = "";
for (int i = 0; i < userNum; ++i) {
finalString = finalString + userString.substring(0, userNum - i);
}
return finalString;
}
Simply loop up to the inputted number and substring from 0 to inputtedNumber - loopCounter and append the result to the previously held String value.
Example Run:
Enter a word:
Calculus
Enter a number within the word scope that you just enter:
5
CalcuCalcCalCaC
Sidenote:
Technically you would want to use StringBuilder instead of appending String in a loop, but that is probably out of the scope of this question. Here is that version just for reference:
public String wordDown(String userString, int userNum) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < userNum; ++i) {
sb.append(userString.substring(0, userNum - i));
}
return sb.toString();
}
Suppose you have a String and a CAPITAL letter in that indicates ending of a word. For example, if you have wElovEcakE where E, E and K indicates end of the words wE, lovE and cakE respectively. You need to reverse each word (as you know where it ends). Don’t reverse the String as a whole. To illustrate, if we give wElovEcakE as input output should be EwEvolEkac. See wE became Ew, lovE became Evol and so on....
And the way i tried to approach with ..
import java.util.Scanner;
public class Alternative {
public static void main(String[]args) {
Scanner robo=new Scanner (System.in);
System.out.println("Enter a word ");
String word=robo.nextLine();
char[] array=word.toCharArray();
for(int i =0;i<array.length;i++){
int count =0;
for(int j=0;j<=("EMPTY");j++) // here i am trying to operate a loop where it will work up to the Capital letter.
count ++;
}
//Code incomplete
}
}
}
Above i have mentioned "EMPTY" in the condition part ... i want to operate a loop where my loop will work up to the capital letter , then i will count all the letter that i have counted up to capital letter then last step will be like i will make another loop where i will reverse all the letter where condition for the loop will <=count ;Example:lovE (counted 4 letters i will reverse four times back).
Can you guys help me to write the condition at "EMPTY" part if you think that my approach is correct ..
Can you guys help me to solve the problem in any other way ?
test if this works for you:
Scanner robo = new Scanner (System.in);
System.out.println("Enter a word ");
String word = robo.nextLine();
String textInvert = "";
int indexAnt = 0;
for (int i = 0; i < word.length(); i++) {
if (Character.isUpperCase(word.charAt(i))) {
String wordSplit = word.substring(indexAnt, i + 1);
for (int j = wordSplit.length() - 1; j >= 0; j--)
textInvert += wordSplit.charAt(j);
indexAnt = i + 1;
}
}
System.out.println(textInvert);
Here is my solution with Regex pattern
String[] in = "wElovEcakE".replaceAll("([A-z]+?[A-Z])","$1,").replaceAll(",$","").split(",");
String out = "";
for(String current: in){
StringBuilder temp = new StringBuilder();
temp.append(current);
out+=temp.reverse();
}
System.out.println(out);
Result:
EwEvolEkac
Here is a solution that makes use of the StringBuilder class to hold and reverse each found word.
Scanner robo = new Scanner (System.in);
System.out.println("Enter a word:");
String word = robo.nextLine();
robo.close();
String upperCase = word.toUpperCase(); //used to find uppercase letters
StringBuilder builder = new StringBuilder();
for (int i = 0; i < word.length(); i++) {
char nextChar = word.charAt(i);
builder.append(nextChar);
if (nextChar == upperCase.charAt(i)) {
String subWord = builder.reverse().toString();
System.out.print(subWord); //It's not clear what to do with the found words
builder = new StringBuilder();
}
}
System.out.println();
Example
Enter a word:
makEmorEpiE
EkamEromEip
You can try this solution:
String textInvert = "wElovEcakE";
String revertText = textInvert
.chars().mapToObj(c -> (char) c)
.reduce(new LinkedList<>(Arrays.asList(new StringBuilder())), (a, v) -> {
a.getLast().append(v);
if (Character.isUpperCase(v)) {
a.add(new StringBuilder());
}
return a;
}, (a1, a2) -> a1)
.stream()
.map(s -> s.reverse())
.reduce(StringBuilder::append)
.map(StringBuilder::toString)
.get();
System.out.println(revertText);
public class Alternative {
public static void main(String[] args) {
Scanner robo = new Scanner(System.in);
System.out.println("Enter a word ");
String word = robo.nextLine();
char[] array = word.toCharArray();
int count = -1;
for (int i = 0; i < array.length; i++) {
if (Character.isUpperCase(array[i])) { //find the upper case letters in the word
for (int j = i; j > count; j--) //loop through the letters until the last count variable value is encountered
System.out.print(array[j]); //print the reversed values
count = i; //assign the last encountered uppercase letter's index value to count variable
}
}
}
}
I am supposed to do this :
For an input number print frequency of each number in the order of its occurrence.For eg :
Input:56464
Output:
Number-Frequency
5 -1
6 -2
4 -2
I cannot use any other libraries except java.lang and Scanner to input
So I tried this :
package practice2;
import java.util.Scanner;
public class DigitFrequency2
{
private static Scanner sc;
public static void main(String[] args)
{
sc = new Scanner(System.in);
System.out.println("Enter an integer number");
String sb = sc.nextLine();
System.out.println("Number\tFrequency");
int i,x,c = 0;
for(i=0;i<sb.length();i++)
{
c = 0;
for(x = i+1;x<sb.length();x++)
{
if(sb.charAt(i) == sb.charAt(x) && sb.charAt(i) != '*' && sb.charAt(x) != '*')
{
c++;
sb.replace(sb.charAt(x),'*');
}
}
if(c>0)
{
System.out.println(sb.charAt(i)+" \t"+c);
}
}
}
}
Number Frequency
6 1
4 1
Where am I going wrong please help.
Simple way is this. Won't bother commenting as it is clear whats going on.
Scanner in = new Scanner(System.in);
while (true) {
System.out.print("Input String: ");
String line = in.nextLine();
while (!line.isEmpty()) {
char c = line.charAt(0);
int length = line.length();
line = line.replace(String.valueOf(c), "");
System.out.println(c + " " + (length - line.length()));
}
}
There are few problems with sb.replace(sb.charAt(x),'*');:
replace replaces all characters, not just first one which is why your c can't be grater than 1.
Strings are immutable so since replace can't edit original string, it returns new one with replaced characters which you can store back in sb reference.
Anyway if you would be able to use other Java resources beside java.lang.* or java.util.Scanner simple approach would be using Map which will map character with number of its occurrences. Very helpful here is merge method added in Java 8 allows us to pass key initialValue combination of old and new value
So your code can look like:
String sb = ...
Map<Character, Integer> map = new TreeMap<>();
for (char ch : sb.toCharArray()) {
map.merge(ch, 1, Integer::sum);
}
map.forEach((k, v) -> System.out.println(k + "\t" + v));
Problem is that as mentioned, String is immutable, so String.replace() just returns a new string and it does not (cannot) modify the original. Either you should use StringBuilder, or store the returned value (e.g. sb = sb.replace(sb.charAt(x),'*');).
Going further, since you initialize c with 0, it will stay 0 if there is no other occurrence of the character in question (sb.charAt(i)), so your algorithm won't detect and print digits that occur only once (because later you only print if c > 0).
Counting occurrences (frequency) of characters or digits in a string is a simple operation, it does not require to create new strings and it can be done by looping over the characters only once.
Here is a more efficient solution (one of the fastest). Since digits are in the range '0'..'9', you can create an array in which you count the occurrences, and by looping over the characters only once. No need to replace anything. Order of occurrence is "remembered" in another order char array.
char[] order = new char[10];
int[] counts = new int[10];
for (int i = 0, j = 0; i < sb.length(); i++)
if (counts[sb.charAt(i) - '0']++ == 0)
order[j++] = sb.charAt(i); // First occurrence of the digit
And print in order, until the order array is filled:
System.out.println("Number\tFrequency");
for (int i = 0; order[i] != 0; i++)
System.out.println(order[i] + "\t" + counts[order[i] - '0']);
Example output:
Enter an integer number
56464
Number Frequency
5 1
6 2
4 2
For completeness here's the complete main() method:
public static void main(String[] args) {
System.out.println("Enter an integer number");
String sb = new Scanner(System.in).nextLine();
char[] order = new char[10];
int[] counts = new int[10];
for (int i = 0, j = 0; i < sb.length(); i++)
if (counts[sb.charAt(i) - '0']++ == 0)
order[j++] = sb.charAt(i); // First occurrence of the digit
System.out.println("Number\tFrequency");
for (int i = 0; order[i] != 0; i++)
System.out.println(order[i] + "\t" + counts[order[i] - '0']);
}
Note:
If you would want to make your code safe against invalid inputs (that may contain non-digits), you could use Character.isDigit(). Here is only the for loop which is safe against any input:
for (int i = 0, j = 0; i < sb.length(); i++) {
char ch = sb.charAt(i);
if (Character.isDigit(ch)) {
if (counts[ch - '0']++ == 0)
order[j++] = ch; // First occurrence of ch
}
}
This should be a good code to print frequency using user input:
public static void main(String args[])
{
System.out.println("Please enter numbers ");
String time = in.nextLine(); //USER INPUT
time = time.replace(":", "");
char digit[] = {time.charAt(0), time.charAt(1), time.charAt(2), time.charAt(3)};
int[] count = new int[digit.length];
Arrays.sort(digit);
for (int i = 0; i < digit.length; i++)
{
count[i]++;
if (i + 1 < digit.length)
{
if (digit[i] == digit[i + 1])
{
count[i]++;
i++;
}
}
}
for (int i = 0; i < digit.length; i++)
{
if (count[i] > 0)
{
System.out.println(digit[i] + " appears " + count[i]+" time(s)");
}
}
}
I'm trying to use Java to solve a simple challenge but I have unsuccessful and I can't find an answer. The idea is that the user enters a string of text, and the program returns the longest word in that string. I can use Scanner to accept the input from the user, and then the .split() method to split the string at the spaces with .split(" ") but I can't figure out how to store the split sentence in an array that I can iterate through to find the longest word. I always get a console output that looks like this:
[Ljava.lang.String;#401a7a05
I have commented out the code that I think should find the longest word so as to focus on the problem of being unable to use Scanner input to create an array of Strings. My code at the moment is:
import java.util.*;
import java.io.*;
class longestWord {
public static void main(String[] args) {
int longest = 0;
String word = null;
Scanner n = new Scanner(System.in);
System.out.println("enter string of text: ");
String b = n.nextLine();
String c[] = b.split(" ");
//for (int i = 0; i <= b.length(); i++) {
// if (longest < b[i].length()) {
// longest = b[i].length();
// word = b[i];
// }
//}
//System.out.println(word);
System.out.println(c);
}
}
That's because you are iterating over the string, not the array, and trying to output the entire array. Change your for loop to use c instead:
for (int i = 0; i < c.length; i++) //In an array, length is a property, not a function
{
if (longest < c[i].length())
{
longest = c[i].length();
word = c[i];
}
}
That should fix your first output. Then you want to change how you output your array, change that to something like this:
System.out.println(Arrays.toString(c));
Which will display the array like so:
[word1, word2, word3, word4]
So you want to get the input as a string and automatically make it an array? You can do that simply by calling the split function after nextLine on the scanner:
String[] wordArray = n.nextLine().split(" ");
there are many mistakes in you code. such a
you were
iterating over string not on array.
if (longest < b[i].length()) as b is your string not array of string
try this it will work it will print the longest word and its size as well.
class Test {
public static void main(String[] args) {
int longest = 0;
String word = null;
Scanner n = new Scanner(System.in);
System.out.println("enter string of text: ");
String b = n.nextLine();
String c[] = b.split(" ");
for (int i = 0; i < c.length; i++) {
if (longest < c[i].length()) {
longest = c[i].length();
word = c[i];
}
}
System.out.println(word);
System.out.println(longest);
}
}
My goal is to create a code that accepts a string, and the minimum number of characters allowed for each word. The output will be an int that tells the users the number of words in their sentence that was above or equal to the min they entered.
Now, my approach to this was to break the sentence up into individual word in the main method, then send each of those words into another method that will count the number of characters.
I am having difficulties in my main method, specifically splitting the sentence into individual words. I want to achieve this without using an array, only loops, substring and indexOf, etc. I commented the section of code that I am having issues with. I tested the rest of my code using a string with only one word, and my letterCounter method seems to be working fine. I know the answer is probably simple, but I am still having trouble figuring it out.
Any help would be wonderful! Thank you!
Here is my code:
public class Counter
{
public static void main(String [] args)
{
int finalcount = 0;
System.out.print("Enter your string: ");
String userSentence = IO.readString();
System.out.print("Enter the minimum word length: ");
int min = IO.readInt();
//Error checking for a min less than 1
while(min < 0)
{
IO.reportBadInput();
System.out.print("Enter the minimum word length: ");
min = IO.readInt();
}
int length = userSentence.length(); // this will get the length of the string
for(int i = 0; i < length; i ++)
{
if (userSentence.charAt(i) == ' ')
{
/* I dont know what to put here to split the words!
once I split the userSentence and store the split word into
a variable called word, i would continue with this code: */
if((letterCounter(word)) >= min)
finalcount++;
else
finalcount = finalcount;
}
}
IO.outputIntAnswer(finalcount);
}
//this method counts the number of letters in each word
public static int letterCounter (String n)
int length = n.length();
int lettercount= 0;
for(int i = 0; i < length; i ++)
{
boolean isLetter = Character.isLetter(n.charAt(i));
if (isLetter)
{
if ((n.length()) >= length)
{
lettercount++;
}
}
}
return lettercount;
}
}
Have a a look at String.split()
You could use string.split() like this to accomplish this:
String [] splittedString = inputString.split(" ");
for(int i = 0;i< splittedString.length; i++){
String currentWord = splittedString[i];
if(currentWord.length() >= min){
finalcount++;
}
}