Repeating number in java to next line - java

I have a Java program that reads from a file like such
6 fun. 3 hello 10 <> 2 25 4 wow!
The number represents how many times the word will be repeated so output would be
fun.fun.fun.fun.fun.fun.
hellohellohello
<><><><><><><><><><>
2525
wow!wow!wow!wow!
However, mine is printing all on one line
import java.io.*;
import java.util.*;
public class Words {
public static void main(String[] args)
throws FileNotFoundException {
Scanner input = new Scanner(new File("aa1234.txt"));
printStrings(input);
}
public static void printStrings(Scanner input) {
while (input.hasNext)) {
int times = input.nextInt();
String word = input.next();
for (int i = 1; i <= times; i++) {
System.out.print(word);
}
}
}
}
I've been playing around with input.nextLine() and whatnot, but don't understand how to get to the next line after it prints the repeated words. Help?

for (int i = 1; i <= times; i++) {
System.out.print(word);
}
System.out.println();

print one new line after printing all the same words in one line.
for (int i = 1; i <= times; i++) {
System.out.print(word);
}
System.out.println();

You can use System.out.print("\n") to print a line end.
Like this :
while (input.hasNext)) {
int times = input.nextInt();
String word = input.next();
for (int i = 1; i <= times; i++) {
System.out.print(word);
}
System.out.print("\n");
}
You can also use the System.out.println() to print a line and automatically append a line end. For example, build the string before print it :
while (input.hasNext)) {
int times = input.nextInt();
String word = input.next();
StringBuilder builder = new StringBuilder();
for (int i = 1; i <= times; i++) {
builder.append(word);
}
System.out.println(builder.toString());
}
Notice the use of StringBuilder, much more faster and consuming less memory than a classical string concatenation.

Issue:
mine is printing all on one line
Solution:
Because you have used System.out.print(), using that it will print everything on the same line. If you would want to have a line break then use System.out.println()

Use System.out.println to print the word on separate lines:
System.out.println(data)

Print a new line after the inner for loop. Something like this
while (input.hasNext())
{
int times = input.nextInt();
String word = input.next();
for (int i = 1; i <= times; i++) {
System.out.print(word);
}
System.out.println();
}

make your function like below
public static void printStrings(Scanner input) {
while (input.hasNext)) {
int times = input.nextInt();
String word = input.next();
for (int i = 1; i <= times; i++) {
System.out.print(word);
}
System.out.println();
}
}

Related

Reducing and printing a string Array

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();
}

Check each position in the input entry and return the number of times a character occurs

I wrote the following code but I can't seem to convert the string to a char and then search the input entry string. My code is below. Any helpful tips would be greatly appreciated. I'm supposed to use a while loop but felt like for was easier to start with.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String inputEntry;
String inputCharacter;
int length;
int i;
int counter = 0;
System.out.println("Enter a string: ");
inputEntry = in.next();
System.out.println("Enter a letter: ");
inputCharacter = in.next();
length = inputCharacter.length();
if (length == 1) {
for(i = 0; i <= inputEntry.length(); i++){
char c = inputCharacter.charAt(0);
if (inputEntry.charAt(i) == c){
counter++;
}
}
}
else {
System.out.println("The input letter was not a single letter.");
}
}
}
It looks like the only problem in your code is that you are using <= instead of < within your loop. <= is incorrect because it passes string length as an index, but first character resides at charAt(0), and last character resides at charAt(inputEntry.length() - 1)
Replacing your loop declaration with the following will do the trick:
for(i = 0; i < inputEntry.length(); i++){
Then you also need to System.out.println(counter); after the for loop.

How to get rid of space at the end of output?

My code checks if a certain number of user inputted string have any repeated characters. For example, if I input the strings "google" "paper" and "water", the code returns "paper" and "water"; because "google" has two Os.
I have the code part down, but when printing, a space appears after the very last string that is output and I can't figure out how to get rid of it.
import java.util.Scanner;
import java.util.*;
class words{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number or words: ");
String[] words = new String[sc.nextInt()];
System.out.print("Enter the strings: ");
boolean truth = false;
for (int i = 0; i < words.length; i++) {
words[i] = sc.next();
}
for(int i=0;i<words.length;i++){
int j;
for(j=1;j<words[i].length();j++) {
if(words[i].charAt(j) == words[i].charAt(j-1)){
break;
}
}
if(j==words[i].length()){
truth = true;
System.out.print(words[i]+" ");
}
}
if(!truth){
System.out.println("NONE");
}
}
}
Functions Make Logic Readable
Move the logic to check for repeating characters into a function; I would take advantage of String.toCharArray() and the shorter array syntax. Like,
private static boolean repeatedChars(String s) {
if (s == null) {
return false;
}
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length - 1; i++) {
if (chars[i] == chars[i + 1]) {
return true;
}
}
return false;
}
Then, you can use a lambda to filter your words based on them not having repeated characters and collect with Collectors.joining(CharSequence) like
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number or words: ");
String[] words = new String[sc.nextInt()];
System.out.print("Enter the strings: ");
for (int i = 0; i < words.length; i++) {
words[i] = sc.next();
}
System.out.println(Arrays.stream(words).filter(s -> !repeatedChars(s))
.collect(Collectors.joining(" ")));
And, if you need to display the NONE message you might re-use the Predicate<String> like
Predicate<String> pred = s -> !repeatedChars(s);
if (Arrays.stream(words).anyMatch(pred)) {
System.out.println(Arrays.stream(words).filter(pred).collect(Collectors.joining(" ")));
} else {
System.out.println("NONE");
}
There is an easy workaround for your problem. Instead of printing every word immediately if it does not have any continuous repetition, add it to a String variable with space at the end so that each word is separated by a space. After you run through your loop, you check if your flag is false and print NONE if it is false. If it is true, however, print the result string where you added everything with a .trim() at the end.
for (int i = 0; i < words.length; i++) {
words[i] = sc.next();
}
String result = ""; /*This is the string that holds all the strings that you need to print.*/
for(int i=0;i<words.length;i++){
int j;
for(j=1;j<words[i].length();j++) {
if(words[i].charAt(j) == words[i].charAt(j-1)){
break;
}
}
if(j==words[i].length()){
truth = true;
result = result + (words[i]+" ");
}
}
if(!truth){
System.out.println("NONE");
}
else{
System.out.println(result.trim()); /*The trim function removes any redundant space in the beginning and the end of the string.*/
}
Of-course doing it this way will waste a lot of Heap Memory but I guess this is for a small learning project. However, do look into StringBuilder on how to use it to avoid creating a lot of memory in the Heap!

Take a quote, and show how many characters, words, and average of each word

I am kinda new to Java, please do not tell me to use methods, etc. because I do not know how to do them. But I do know some charAt things, so can anyone help me find the amount of words, and avg of each word, i did the first part. Here is my code.
import java.util.Scanner;
public class FavouriteQuote {
public static void main(String[] args) {
// TODO Auto-generated method stub
String sQuote;
int counter = 0;
Scanner input = new Scanner (System.in);
System.out.print("Enter one of your favourite quotes: ");
sQuote = input.nextLine();
input.close();
for (int i = 0; i < sQuote.length(); i ++) {
counter ++;
}
System.out.println(counter);
}
}
But what average do you need? average word length in quote?
then your code may look like:
...
input.close();
System.out.println("Characters in quote:" + sQuote.length());
String[] words = sQuote.split("\\s");
// or
// String[] words = sQuote.split(" ");
System.out.println("words in quote:" + words.length);
int totalWordsLength =0;
for (String word: words)
{
totalWordsLength = totalWordsLength + word.length();
}
//or with loop counter
// for (int i=0; i < words.length; i++)
// {
// totalWordsLength += words[i].length();
// }
System.out.println("average word length in quote:" + (totalWordsLength/ words.length));
Keep in mind: here average is int so it will be only integer portion of divide result. i.e. 11/3 = 3
BTW (aside of question) - You do not need your for loop. It does not make any sense.
counter = sQuote.length() does the same.

Write a program that will read a line of text, and will display all letters in the text along with the number of times the letter appears in the text

I have the basics, but I need to make it so that my program will work without printing the unused letters of the alphabet at the end, say my sentence is "dog" I would want the output to be: D-1
O-1
G-1, instead of A-0 B-0 D-1, and so on. Thanks for any help provided, it is greatly appreciated.
what I have so far is:
package as10;
import java.util.*;
public class as
{
private static void countLetters(String sentenceString)
{
int[] array = new int[26];
sentenceString = sentenceString.toUpperCase();
for (int i = 0; i < sentenceString.length(); ++i)
{
if (sentenceString.charAt(i) >= 'A' && sentenceString.charAt(i) <= 'Z')
{
++array[sentenceString.charAt(i) - 'A'];
}
}
for (int i = 0; i < 26; ++i)
{
System.out.println((char) ('A' + i) + " - " + array[i]);
}
}
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
String letterString;
while (true)
{
System.out.println("Enter a line of text: ");
letterString = kbd.nextLine();
System.out.println("Letter Frequencies: ");
countLetters(letterString);
break;
}
kbd.close();
}
}
so, basically, you want to opt out all chars if counter is 0.
In other words, you will need an if statement around print line and only perform system output if relevant array value is non-zero.
Above statement is in pure English. It is again your assignment to convert that sentence into java, as I refuse to do your homework on your behalf.
Does it sound fair ? :)

Categories