String of n length in java - java

public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int N=sc.nextInt();
String s="";
for(int i=0;i<N;i++){
s=sc.nextLine();
}
Eg : N= 10
S = aabbbabbab
How do I take an input of String of n length ?
I am trying to take an input String which must be of length N.
I know the above logic is wrong, but still i am confused ?
PS: The first line of input contains a single integer N − the length of the string.
The second line contains the initial string S itself.

Check if the input String is greater than the maximumlength.
if (s.length() > maximumLength) { // do something
And what you can do is to use a substring in order to trim the input.
fixedInput = s.substring(0, maximumLength - 1);
Okay, as you are reading the number first, you must initialize maximumLength with the first input.
As an alternative you can ask the user until the input fits the entered length:
do {
s = sc.nextLine();
if (s.length() != maximumLength)
System.out.println("The input did not fit the size");
} while (s.length() != maximumLength);

Use this:
Scanner sc = new Scanner(System.in);
int N = sc.nextInt(); // N == 5 e.g
sc.nextLine(); // Consume the leftover '\n'
String s = sc.nextLine(); // Hello World
s = s.substring(0, N);
System.out.println(s); // Hello

I would suggest to check the input string using an if and return the user to input again if it doesn't match the length that you are looking for.
Example:
if(s.length() != n) {
//Take another input
}
You can do the above in a loop until this condition is satisfied (maybe a while loop).
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
String s="";
do{
s = sc.nextLine();
}while(s.length() != n);
}

In the above code, all you are doing is reading in n strings, and setting s to the last one (there will also be an exception thrown if there aren't n strings in the input stream). What you need to do is read in a string and compensate for any length errors.
if(in.hasNextLine()) {
s = in.nextLine();
if(s.length() > n) s = s.substring(0, n); // Cut the string so it is of the desired length
else {
for(int i = 0; i < n - s.length(); i++) s += " "; // Add spaces until the string is of the desired length
}
}

Related

How to resolve the following program with a for loop into producing an appropriate output?

The following Java program is supposed to manipulate a string input by the user in such a way that the user will decide which character needs to be replaced with another and just the last character from the string should be replaced. Example if the user enters the string "OYOVESTER" and decides to replace "O" with "L", the program should output the following result: "OYLVESTER" (notice that only the last "O" was replaced with "L")
NOTE: YOU CANNOT USE BREAK COMMAND TO STOP THE LOOP. IT IS PROHIBITED.
import java.util.Scanner;
public class StringFun {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
String inString = keyboard.nextLine();
String outString = "";
//Replace Last
System.out.println("Enter the character to replace");
char oldCharF = keyboard.next().charAt(0);
System.out.println("Enter the new character");
char newCharF = keyboard.next().charAt(0);
int count = 0; // variable that tracks number of letter occurrences
for(int index = inString.length() - 1;index >= 0;index--) {
if(inString.charAt(index) == oldCharF && count < 1){
outString = newCharF + outString;
outString = outString + inString.substring(0,index);
count++;
}
if (count < 1) {
outString = outString + inString.charAt(index);
}
}
System.out.print("The new sentence is: "+outString);
}
}
I keep getting the following output which is incorrect:
Enter the string to be manipulated
OYOVESTER
Enter the character to replace
O
Enter the new character
L
The new sentence is: LRETSEVOY
There are many simpler ways to achieve your requirement but I hope you have to demonstrate this with loops (without breaks)
Then you can use some thing like this :
boolean skip = false;
for (int index = inString.length() - 1; index >= 0; index--) {
if (!skip && inString.charAt(index) == oldCharF) {
outString = newCharF + outString;
skip = true;
}
else {
outString = inString.charAt(index) + outString;
}
}
PS : Using String concatenation inside loops is not recommended since
every String concatenation copies the whole String, usually it is preferable to
replace it with explicit calls to StringBuilder.append() or StringBuffer.append()
No break command seems like a weird condition. You could just a boolean value, and other methods, to break the loop when you need. Why not do something like this?
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
String word = keyboard.nextLine();
//Replace Last
System.out.println("Enter the character to replace");
char oldCharF = keyboard.next().charAt(0);
System.out.println("Enter the new character");
char newCharF = keyboard.next().charAt(0);
int index = word.lastIndexOf(oldCharF);
if(index > 1){
word = word.substring(0,index) + newCharF + word.substring(index+1);
}
System.out.println("The new sentence is: " + word);
}

Asking user to enter specific number of strings then adding each string to array?

New to java. I need to ask the user the number of strings (consisting only of upper and lowercase letters, spaces, and numbers) they want to input. These strings need to be stored in an array. Then I created a boolean method to be able to tell if those strings are palindromic (ignoring spaces and cases). If it is palindromic then I add to the result list to print later on. I am confused on how to ask the user to input that exact amount of strings and how to check each individual string. I must use StringBuilder. This is what I have so far (it's kind of a mess, sorry). I feel like I'm using the StringBuilder/array wrong, how can I fix this?
public class Palindromes {
public static void main(String[] args) {
int numOfStrings;
Scanner scan = new Scanner(System.in); // Creating Scanner object
System.out.print("Enter the number of strings: ");
numOfStrings = scan.nextInt();
System.out.print("Enter the strings: ");
StringBuilder paliString = new StringBuilder(numOfStrings);
for(int n=0; n < paliString; n++){
paliString[n] = scan.nextLine();
scan.nextLine();
String[] stringPali = new String[numOfStrings];
StringBuilder str = paliString;
if(isPali(userString)){
paliString = append.userString;
}
System.out.println("The palindromes are: " + userString ";");
}
static boolean isPali(String userString) {
int l = 0;
int h = userString.length() - 1;
// Lowercase string
userString = userString.toLowerCase();
// Compares character until they are equal
while (l <= h) {
char getAtl = userString.charAt(l);
char getAth = userString.charAt(h);
// If there is another symbol in left
// of sentence
if (!(getAtl >= 'a' && getAtl <= 'z'))
l++;
// If there is another symbol in right
// of sentence
else if (!(getAth >= 'a' && getAth <= 'z'))
h--;
// If characters are equal
else if (getAtl == getAth) {
l++;
h--;
}
// If characters are not equal then
// sentence is not palindrome
else
return false;
}
// Returns true if sentence is palindrome
return true;
}
}
SAMPLE RESULT:
Enter the number of strings: 8
Enter the strings:
Race Car
Mountain Dew
BATMAN
Taco Cat
Stressed Desserts
Is Mayonnaise an instrument
swap paws
A Toyotas a Toyota
The palindromes are: Race Car; Taco Cat; Stressed Desserts; swap paws; A Toyotas a Toyota
As I think the best way to answer this is to help you learn in small steps, I tried to stick with your initial idea on how to solve this and edited your main method with minimal changes.
This one does the trick.
public static void main(String[] args) {
int numOfStrings;
Scanner scan = new Scanner(System.in); // Creating Scanner object
System.out.print("Enter the number of strings: ");
numOfStrings = scan.nextInt();
scan.nextLine(); // you need this to catch the enter after the integer you entered
System.out.print("Enter the strings: ");
StringBuilder paliString = new StringBuilder();
for (int n = 0; n < numOfStrings; n++) {
String userString = scan.nextLine();
if (isPali(userString)) {
if (paliString.length() > 0) {
paliString.append("; ");
}
paliString.append(userString);
}
}
System.out.println("The palindromes are: " + paliString);
}
Key changes:
I added scan.nextLine(); right after reading the number of strings. This handles the newline you get when the user hits enter.
You don't need to initialize the StringBuilder with numOfStrings. This just preallocates the size of the StringBuilder in characters. Not the number of strings. Either way, it's not necessary. StringBuilder grows as needed.
I suggest you inspect what I did inside the for-loop. This was the biggest mess and changed significantly.
Last but not least: Writing the result needs to be outside of the for-loop, after all palindromes have been added to the StringBuilder.
Edit
Based on your comment, in this next iteration, I changed the usage of StringBuilder to the usage of an ArrayList. (Which is something completely different)
I am using it here because Lists in Java grow on demand. And since the number of palindromes is probably not equal to the number of input strings, this is the way to go. To really assign it to an array, one could always call String[] paliStringsArray = paliStrings.toArray(new String[]{}); but as ArrayLists already use an underlying array and are not necessary to to generate the output you want, I didn't put it into the new version.
Please compare the differences of this step to the previous version. I also added this String.join("; ", paliStrings) part, which creates the output you want.
public static void main(String[] args) {
int numOfStrings;
Scanner scan = new Scanner(System.in); // Creating Scanner object
System.out.print("Enter the number of strings: ");
numOfStrings = scan.nextInt();
scan.nextLine(); // you need this to catch the enter after the integer you entered
System.out.print("Enter the strings: ");
List<String> paliStrings = new ArrayList<>();
for (int n = 0; n < numOfStrings; n++) {
String userString = scan.nextLine();
if (isPali(userString)) {
paliStrings.add(userString);
}
}
System.out.println("The palindromes are: " + String.join("; ", paliStrings));
}
And now to the last step. Arvind Kumar Avinash actually solved a part that I also missed in the initial question. (I'll read more carefully in the future). He was validating the user input. So for the last iteration, I added his validation code in a modified way. I put it into a method as I think that makes things clearer and gets rid of the necessity of a the boolean valid variable.
public static void main(String[] args) {
int numOfStrings;
Scanner scan = new Scanner(System.in); // Creating Scanner object
System.out.print("Enter the number of strings: ");
numOfStrings = scan.nextInt();
scan.nextLine(); // you need this to catch the enter after the integer you entered
System.out.print("Enter the strings: ");
List<String> paliStrings = new ArrayList<>();
for (int n = 0; n < numOfStrings; n++) {
String userString = readNextLine(scan);
if (isPali(userString)) {
paliStrings.add(userString);
}
}
System.out.println("The palindromes are: " + String.join("; ", paliStrings));
}
static String readNextLine(Scanner scanner) {
while (true) {
String userString = scanner.nextLine();
if (userString.matches("[A-Za-z0-9 ]+")) {
return userString;
} else {
System.out.println("Error: invalid input.");
}
}
}
I need to ask the user the number of strings (consisting only of upper
and lowercase letters, spaces, and numbers) they want to input. These
strings need to be stored in an array.
I have done the above part of your question. I hope, this will give you direction to move forward.
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
boolean valid = true;
int numOfStrings = 0;
do {
valid = true;
System.out.print("Enter the number of strings: ");
try {
numOfStrings = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
System.out.println("Error: invalid input.");
valid = false;
}
} while (!valid);
String[] stringPali = new String[numOfStrings];
String input;
for (int i = 0; i < numOfStrings; i++) {
do {
valid = true;
System.out.print("Enter a string consisting of only letters and digits: ");
input = scan.nextLine();
if (!input.matches("[A-Za-z0-9 ]+")) {
System.out.println("Error: invalid input.");
valid = false;
}
} while (!valid);
stringPali[i] = input;
}
}
}
A sample run:
Enter the number of strings: a
Error: invalid input.
Enter the number of strings: 3
Enter a string consisting of only letters and digits: Arvind
Enter a string consisting of only letters and digits: Kumar Avinash
Enter a string consisting of only letters and digits: !#£$%^&*()_+
Error: invalid input.
Enter a string consisting of only letters and digits: Hello #
Error: invalid input.
Enter a string consisting of only letters and digits: Hello 123
Feel free to comment in case of any doubt/issue.
Wish you all the best!
[Update]
Based on your request, I have posted the following update which asks for the strings only once and then allows the user to enter all the strings one-by-one:
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
boolean valid = true;
int numOfStrings = 0;
do {
valid = true;
System.out.print("Enter the number of strings: ");
try {
numOfStrings = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
System.out.println("Error: invalid input.");
valid = false;
}
} while (!valid);
String[] stringPali = new String[numOfStrings];
String input;
System.out.println("Enter " + numOfStrings + " strings consisting of only letters and digits: ");
for (int i = 0; i < numOfStrings; i++) {
do {
valid = true;
input = scan.nextLine();
if (!input.matches("[A-Za-z0-9 ]+")) {
System.out.println("Error: invalid input.");
valid = false;
}
} while (!valid);
stringPali[i] = input;
}
}
}
A sample run:
Enter the number of strings: 3
Enter 3 strings consisting of only letters and digits:
Arvind
Kumar
He$ll0
Error: invalid input.
Avinash
Feel free to comment in case of any doubt.

How to replace multiple occurences of a character in a java string using replace and charAt methods

This is my second question here and still a beginner so please bear with me.
I have this code of a very basic hangman type game.I have changed the characters to "-",I am able to get the indices of the input but I am not able to convert back the "-" to the characters entered.
Its an incomplete code.
String input;
String encrypt = line.replaceAll("[^ ]","-");
System.out.println(encrypt);
for (int j=0;j<10;j++){ //Asks 10 times for user input
input = inpscanner.nextLine();
int check = line.indexOf(input);
while (check>=0){
//System.out.println(check);
System.out.println(encrypt.replaceAll("-",input).charAt(check));
check = line.indexOf(input,check+1);
}
Here is how it looks like:
You have 10 chances to guess the movie
------
o
o
o
L
L
u //no repeat because u isn't in the movie.While 'o' is 2 times.
I would like to have it like loo---(looper).
How can I do like this "[^ ]","-" in case of a variable?
This might help.
public static void main(String[] args) {
String line = "xyzwrdxyrs";
String input;
String encrypt = line.replaceAll("[^ ]","-");
System.out.println(encrypt);
System.out.println(line);
Scanner scanner = new Scanner(System.in);
for (int j=0;j<10;j++) { //Asks 10 times for user input
input = scanner.nextLine();
//int check = line.indexOf(input);
int pos = -1;
int startIndex = 0;
//loop until you all positions of 'input' in 'line'
while ((pos = line.indexOf(input,startIndex)) != -1) {
//System.out.println(check);
// you need to construct a new string using substring and replacing character at position
encrypt = encrypt.substring(0, pos) + input + encrypt.substring(pos + 1);
//check = line.indexOf(input, check + 1);
startIndex = pos+1;//increment the startIndex,so we will start searching from next character
}
System.out.println(encrypt);
}
}

Do while loop to delete characters until count is achieved not working Java

I'm trying to make this do while loop delete vowels from a string until the correct character count is reached (140), however it is not working. I'm unsure if the do while loop is working then stopping once the condition is met but if that is the case how can I run the rest of my code once the condition is met?
Thanks in advance!
Here is the code I am using:
public static void main(String[] args)
{
Scanner scan = new Scanner( System.in );
System.out.println("Enter the phrase to be shortened: ");
String toCompress = scan.nextLine();
int length = toCompress.length();
System.out.println(length);;
do {
toCompress = toCompress.replaceAll("[AEIOUaeiou]", "");
}while(length >= 140);
System.out.println("Compressed phrase: ");
System.out.println(toCompress);
int length2 = toCompress.length();
System.out.print(length2);;
scan.close();
}
You need to remove one vowel at a time until it reaches the 140 length. Right now you don't update the length after doing toCompress = toCompress.replaceAll("[AEIOUaeiou]", "")
Correct way:
public static void main(String[] args){
Scanner scan = new Scanner( System.in );
String[] vow={"A","a","O","o","E","e","U","u","I","i"};
List<String> vowels=Arrays.asList(vow);
System.out.println("Enter the phrase to be shortened: ");
String toCompress = scan.nextLine();
int length = toCompress.length();
System.out.println(length);
String compressed="";
while(length >= 140&&compressed.length()<140){
String firstLetter=toCompress.substring(0,1);
//if the first letter is not a vowel, add it to the compressed string
if(!vowels.contains(firstLetter)) compressed.concat(firstLetter);
//remove the first letter from toCompress
toCompress=toCompress.substring(1);
//update the length to the new value
length=compressed.length()+toCompress.length();
}
//After reaching 140 characters, concatenate the rest of toCompress to compressed
compressed.concat(toCompress);
System.out.println("Compressed phrase: ");
System.out.println(compressed);
System.out.print(compressed.length());
scan.close();
}
I'm not sure why you're using the while loop here. replaceAll() will look for all the characters in your string that match the regex/pattern you've provided, and replace them with the character/pattern in your second argument (which in this case is an empty string). Doing it in a loop will not change the result, and is useless in this case.
The while loop will also never complete in cases where there are more than a 140 non-vowel characters in the string. Look up the documentation for replaceAll() and understand how it works. Useful link:
https://www.tutorialspoint.com/java/java_string_replaceall.htm
I've figured out a better way to do this:
public static void main(String[] args)
{
Random RNG = new Random(); //Set up the RNG
Scanner scan = new Scanner( System.in ); //Set up the scanner
System.out.println("Enter the phrase to be shortened: ");
String toCompress = scan.nextLine();
//Setup the string builder with the user input
StringBuilder shorten = new StringBuilder(toCompress);
//Wile the length is greater than or equal to 140,do some conversions then
//run the if statement
while (shorten.length() >= 140)
{
int randChar = RNG.nextInt(shorten.length());
char convertToChar = shorten.charAt(randChar);
int convertToInt = (int)convertToChar;
//If statement choosing which ASCII chars to delete (vowels)
if ((convertToInt > 32) || (convertToInt == 65)
|| (convertToInt == 69) || (convertToInt == 73)
|| (convertToInt == 79) || (convertToInt == 85))
{
shorten.deleteCharAt(randChar);
}
}
System.out.println("Compressed phrase:");
System.out.println(shorten);
System.out.println(shorten.length());
scan.close();
}}

How to make the output show how many times 2 specific letters come up in a string?

The following code is not correct. When I enter the string, "The rain in Spain" the output is 0 when it should be 2. Or when I put "in in in" the output is 1 when it should be 3. So please help me out and show me how to change this to make it work. Thanks!
import java.util.Scanner;
public class Assignment5b {
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the string: ");
String str = keyboard.next();
String findStr = "in";
int lastIndex = 0;
int count =0;
while(lastIndex != -1){
lastIndex = str.indexOf(findStr,lastIndex);
if( lastIndex != -1){
count ++;
lastIndex+=findStr.length();
}
}
System.out.print("Pattern matches: " + count);
}}
Replace String str = keyboard.next(); with String str = keyboard.nextLine();
.next() method only scans for the next token. While nextLine() scans the entire line being input till you hit enter.
Another way to find the occurrence is simply:
System.out.print("Enter the string: ");
String str = keyboard.nextLine();
String findStr = "in";
System.out.println(str.split(findStr, -1).length);
In your cases. keyboard.next() is taking word by word. So the expression keyboard.next() will give you the first word - "The". So your whole of code will run for String str = "The".
Change your keyboard.next() to keyboard.nextLine()
or
put your code in a while condition like
while(keyboard.hasNext()) {
}
import java.util.Scanner;
public class Temp {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the string: ");
String str = keyboard.nextLine();
String findStr = "in";
int lastIndex = 0;
int count =0;
while(lastIndex != -1){
lastIndex = str.indexOf(findStr,lastIndex);
if( lastIndex != -1){
count ++;
lastIndex+=findStr.length();
}
}
System.out.print("Pattern matches: " + count);
}
}
NextLine Documentation says:
public String nextLine()
Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.
Returns:
the line that was skipped
Throws:
NoSuchElementException - if no line was found
IllegalStateException - if this scanner is closed
import java.util.Scanner;
public class Assignment5b {
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the string: ");
String str = keyboard.nextLine();
String findStr = "in";
int lastIndex = 0;
int count =0;
while(lastIndex != -1){
lastIndex = str.indexOf(findStr);
if( lastIndex != -1){
str = str.substring(lastIndex+findStr.length(),str.length());
count ++;
}
}
System.out.print("Pattern matches: " + count);
}}
Couple of the things to be noted -
You need to use keyboard.nextLine(); if you need the entire line. Else it will just get the first word.
If you input "in" in the input statement "The rain in Spain". Program will output 3, there is "in" in "rain", "in" and "Spain"

Categories

Resources