Why the array seem to be longer than its maximum length? - java

Im new, I try to write some code, its for counting the string letter, space, and such. So, i set array length 50. But when i run the code later and enter more than 50 characters, it still can be run,and the total count can be more than 50, why? thank you.
import java.util.Scanner;
public class javaexcrises {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String astrg = new String();
char[] ch = new char[50];
int charcount=0;
int spaccount=0;
int numcount=0;
int othcount=0;
System.out.println("Please enter some word ");
if(scan.hasNextLine()){
astrg = scan.nextLine();
ch = astrg.toCharArray();
int i;
for(i=0;i<astrg.length();i++){
if(Character.isLetter(ch[i])){
charcount++;
}
else if(Character.isDigit(ch[i])){
numcount++;
}
else if(Character.isSpaceChar(ch[i])){
spaccount++;
}
else{
othcount++;
}
}
System.out.println("Character = "+charcount);
System.out.println("Space = "+spaccount);
System.out.println("Number = "+numcount);
System.out.println("Others ="+othcount);
System.out.println("Total = "+ch.length);
}
scan.close();
}
}

ch = astrg.toCharArray();
toCharArray() returns a reference to a NEW array, and that reference replaces the old one that you allocated. That new array is large enough to contain the entire input string.

When we do astrg.toCharArray(), It returns a newly allocated character array, whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string.
If you remove new char[50] also it will not affect.

Related

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.

Taking a string and modifying it with an integer

Being fairly new to Java, I have an exercise where the user will be asked to enter a word. Next, they will be asked to enter a number. Then the program will modify the word by taking the number and implementing it to change the string. For example, if the word "Hello" was entered, and the integer entered was the number "3", it will take each character in the string (Hello) and move them each 3 letters down in the alphabet, which would then make the output word "Khoor". I recently learned about method replacing (.replace) in the same chapter as this question but it seems like having to clarify every single letter with a replace would be too lengthy. This is what I have so far.
public class Lab03Exercise7 {
public static void main(String [] args)
{
// Prompt user to enter a string
System.out.print("Enter a word");
// Import Java scanner
Scanner input = new Scanner( System.in );
int numberinput;
String wordinput = input.nextLine();
// Prompt user to enter an integer
System.out.print( "Enter a number");
numberinput = input.nextInt();
}
}
You can do it as follows:
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
System.out.print("Enter a word: ");
String wordInput = input.nextLine();
System.out.print("Enter a number: ");
int numberInput = input.nextInt();
StringBuilder updatedStr = new StringBuilder();
for (char c : wordInput.toCharArray()) {
updatedStr.append((char) (c + numberInput));
}
System.out.println("Updated string: " + updatedStr);
}
}
Explanation: Break the word into an array of characters and iterate through the array. During iteration, add the number to the character and append the updated character to a StringBuilder object. Note that you can add an integer to a char value but you need to cast it before appending to the StringBuilder object.
You can use something like this:
final StringBuilder sb = new StringBuilder();
for(int i = 0 ; i < wordinput.length(); i++) {
final char currentChar = wordinput.charAt(i);
sb.append((char)(currentChar + numberinput));
}
System.out.println(sb.toString());
So basically, we're going character by character and adding the shift that you've got from the user. here I don't handle the edge cases - where we need to rotate after z / Z
In general, this algorithm called Caesar Cipher and you can get some more info about it here: https://www.geeksforgeeks.org/caesar-cipher-in-cryptography/
As highlighted by #maio290' comment you have to use the ascii table to solve your problem, differentiating between lowercase characters and uppercase characters. Starting from the assumption we have a 26 chars alphabet (a-z and A-Z) in the example we are translating the chars of three positions so we will have for example:
"Hello" will be translated to "Khoor"
"zed" will be translated to "chg"
In the case of z char it will be translated to c, I'm posting an example explaining the situation:
public class Caesar {
public static String encode(String original, int k) {
char[] arr = original.toCharArray();
StringBuilder encoded = new StringBuilder();
for (char ch : arr) {
char initialCharacter = Character.isLowerCase(ch) ? 'a' : 'A';
int dec = ((int)(ch - initialCharacter) + k) % 26;
encoded.append((char)(dec + initialCharacter));
}
return encoded.toString();
}
public static void main(String[] args) {
System.out.println(encode("Hello", 3)); //<-- will print Khoor
System.out.println(encode("zed", 3)); //<-- will print chg
}
}
You have to transform your char to int and after retransform it to char , differentiating between lowercase chars and uppercase chars and assuming an alphabet of 26 chars , for further details see the ascii table.
I believe this is gonna help to solve your problem. Just do not forget to handle it after 122(letter z). You can check the ASCII table here (https://theasciicode.com.ar/)
public static void main(String[] args) throws Exception {
String word = "word";
char[] arr = word.toCharArray();
int count=0;
for (char c : arr) {
//!!Handle if the sum is bigger than 122 (letter z), you need to do some easy math.
arr[count] = (char) (((int)c) + 3);
count++;
}
String newWord = new String(arr);
}

String of n length in 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
}
}

Creating array with unknown elements by Input them

I know this isn't something you are supposed to do yet but I'm still trying to figure out a way to run this loop, an letting the arr[i] inside it "know" about the rise of the number of elements in the array (which I declare outside of the loop because I don't want it to make a new one each time).
int counter=1, note=0;
System.out.println("Please enter characters, -1 to stop: ");
do {
char[] arr= new char[counter];
for (int i=0;i<=counter;i++){
arr[i] = s.next().charAt(0);
if (arr[i]==-1){
note = -1;
break;
}
++counter;
}
} while (note>=0);
From your much clearer comment, this is an example main method.
public static void main(String[] args) {
Scanner input = new Scanner(System.in); // Input
int amt = 0; // Amount of chars received
List<Character> chars = new ArrayList<>(); // ArrayList is easier for now
while (input.hasNext()) { // Grabs Strings separated by whitespaces
String token = input.next(); // Grab token
if (token.equals("-1")) {
break; // End if -1 is received
} else if (token.length() != 1) {
throw new IllegalArgumentException("Token not one char: " + token);
// It seems you want only chars - this handles wrong input
} else {
chars.add(token.charAt(0)); // Adds the character to the list
amt++; // Increment amt
}
}
char[] array = new char[amt]; // Converting to an array
for (int i = 0; i < amt; i++) {
array[i] = chars.get(i); // Copies chars into array
}
System.out.println(Arrays.toString(array)); // Handle data here
}
I hope that this is correct. An input of a b c d -1 leads to an output of [a, b, c, d].
If you use the Input String size check I think as you will be resolved.
int counter=0, note=0;
System.out.println("Please enter characters, -1 to stop: ");
String input=s.nextLine();
counter=input.length();
char[] arr= new char[counter];
for (int i=0;i<counter;i++){
arr[i] = input.charAt(i);
}
and If you are using the ArrayList rather than Array is no need to worry about the size.
ArrayList is effective flexable data
cause using add function.

Why do I get "null" as an output string? Java

What I am trying to do is read from a file (in this case the file contains over 100,000+ lines) and store the values in an array, then print out the first 10 lines. However when I run the program I get the first line, and then followed by 9 lines of "null" which is obviously not what I want! This is the code and any tips would be appreciated.
import java.io.*;
import java.util.Scanner;
public class DawsonZachA5Q2{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a size for the number of letters for words: ");
int size = keyboard.nextInt();//prompts user for input
String[] array = new String[27000];
try {
File file = new File("big-word-list.txt");
Scanner scanner = new Scanner(file);
// Start a line count and declare a string to hold our current line.
int linecount=0;
// Tells user what we're doing
System.out.println("Searching for words with " + size + " letters in file...");
int wordCount=0;
while (scanner.hasNext()){
int i = 0;
String word = scanner.next();
if(size == word.length()){
wordCount++;
array[i]=word;
i++;
//add word to array
// increase the count and find the place of the word
}
}
linecount++;
System.out.println(wordCount);
System.out.println(wordCount+" words were found that have "+size+ " letters.");//final output
for(int o = 0; o<10; o++){
System.out.println(array[o]);
}
scanner.close();
}// our catch just in case of error
catch (IOException e) {
System.out.println("Sorry! File not found!");
}
} // main
} // class
Define int i = 0; outside of the while loop. It gets set to zero each time the loop runs. That is the problem here.
You have mistaken in the while loop. You must define 'int i = 0' before the while loop. In your case, what happen is that whenever the while loop execute, i is initialized to 0. i.e. every time, the word with required length found, that word will be stored in array[0] (Since i is initialized to 0 every iteration of while loop) replacing the previous stored value. As a result, you only get the first value and remaining displayed as null since nothing is stored after array[1].
Therefore, the actual flow should be like this.
// i is initialized outside of loop.
int i = 0;
while (scanner.hasNext()){
//int i = 0; this is your error
String word = scanner.next();
if(size == word.length()){
wordCount++;
array[i]=word;
i++;
//add word to array
// increase the count and find the place of the word
}
}

Categories

Resources