Printing an array - java

I have an array of 28 characters. I'm trying to use a for loop to print the string and its length so that the next line removes the last character from the previous line. For example:
7 Example
6 Exampl
5 Examp
4 Exam
3 Exa
2 Ex
1 E
I have this so far, but it's not printing. What am I doing wrong?
for(int index=28; index <= nameArray.length; index--)
{
System.out.print(nameArray[index]);
}

It is as simple as that ..
class A {
public static void main(String [] args) {
String array = "Example";
for(int i=7;i>0;i--) {
System.out.print(i+" ");
System.out.println(array.substring(0, i));
}
}
}
// Output :
7 Example
6 Exampl
5 Examp
4 Exam
3 Exa
2 Ex
1 E

If the length is 28 characters, you cannot start the index at 28. Arrays in Java are zero-based, so that means that the index can range from 0 to 27 (length - 1).

Firstly, you probably want your middle condition to be index > 0, not index <= nameArray.length (which should always be true, even as you enter the negative numbers).
Secondly, is it an array of characters you're accessing? If so, then as I'm sure you know, nameArray[index] refers to a character, not a string.
(Also, as bobbymcr points out, the top index in an array of 28 elements is 27, not 28.)
To print substrings, you should first initialize a String using your character array, then print increasingly smaller substrings using substring.
For example:
private static void printSubstrings(String input) {
for (int length = input.length(); length > 0; length--) {
System.out.printf("%d %s\n", length, input.substring(0, length));
}
}
Then, if nameArray is a char[], you could use the String(char[]) constructor to pass to this method:
printSubstrings(new String(nameArray));
Example input:
char[] nameArray = new char[] { 'E', 'x', 'a', 'm', 'p', 'l', 'e' };
printSubstrings(new String(nameArray));
Output:
7 Example
6 Exampl
5 Examp
4 Exam
3 Exa
2 Ex
1 E

Always remeber that the array indexes start from 0
[E][x][a][m][p][l][e]
0 1 2 3 4 5 6
I don't understand why you break your head with char arrays, when you have String.
Here i propose you a solution where:
1-transform the char[] to String
2-Iterate the String object and use the some methods from the String class to get the desired result:
public class Example
{
public static void main(String[] args) {
//Here an array with 28 characters
char[] array = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p'
,'q','r','s','t','u','v','w','x','y','z','!','#'};
//For easier manipulation i will just transform that array to String
//Why not, String was invented so we dont have to use char[].
String arrayAsString = new String(array);
//Use the methods that String class provides, to make the solution easier
for(int i=0;i < array.length;i++) {
System.out.println((i+1) + " " + arrayAsString.substring(0,(arrayAsString.length()-i)));
}
}
}

for(int index=28; index <= nameArray.length; index--)
First off, you're trying to start at index 28 - that doesn't exist. Arrays are 0 based which means they go from 0 to length - 1
Second, you're saying that the index has to be less than or equal to the length. Since you're going from the end to the start, that would always be true.
for (int index = nameArray.length - 1; index >= 0; index--)
That's what you're looking for.

Related

I have to check if an element of the array is the same as the previous one (java)

I followed the advice of the site but I did not find answers that satisfied me.
I have to solve a school exercise. I have an array and I need to check if there is at least a sequence of 3 consecutive "a" characters.
public static String alternative(char[] a) {
String ret = "";
int consecutiveCounter = 0;
int i = 1;
while(consecutiveCounter<3){
while(i<= a.length){
if(a[i] =='a' && a[i] == a[i-1] ) {
consecutiveCounter++;
} else {
consecutiveCounter = 0;
}
i++;
}
}
if (consecutiveCounter == 3) {
ret += "there are three consecutive a char";
} else {
ret += "there are not three consecutive a char";
}
return ret;
}
public static void main(String[] args) {
char[] a = new char[]{'a', 'a', 'b', 'c', 'a', 'b', 'a'};
System.out.println(alternative(a));
}
the terminal gives me this exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 7 out of bounds for length 7
at Es1.alternative(Es1.java:9)
at Es1.main(Es1.java:31)
I can't increase the value of the index (i) without going out of the array bounds
It may be better to use for loops here, both checking the bounds of array, and the inner counting occurrences of 'a' and returning early as soon as the required limit is reached:
public static String alternative(char[] a) {
for (int i = 0, n = a.length; i < n; ) {
for (int count = 1; i < n && a[i++] == 'a'; count++) {
if (count == 3) {
return "there are three consecutive 'a' chars";
}
}
}
return "there are not three consecutive 'a' chars";
}
It's worth mentioning that String class (which is basically built on char array) has several methods to implement this functionality:
String::contains: "aabbccaaa".contains("aaa") // true
String::indexOf: "aabbccaa".indexOf("aaa") // -1, aaa not found
String::matches (using regular expression): "aabbaaaccaa".matches(".*a{3}.*") // true
Also, I don't think your outer looping will work well.
1.Suppose there is no consecutive char, then consecutiveCounter will remain 0 and while(consecutiveCounter<3) wont end.
2.Even if there is one or two, but it will be set to 0 again, and while(consecutiveCounter<3) wont end.
Here are some suggestions.
Use a for loop from i = 1 to i < a.length. Then i won't exceed the last index of the array.
You are only trying to find 3 consecutive 'a's. So initialize consecutiveCounter to 1.
As soon as the first consecutive pair are found, you increment consecutiveCounter and it will now be 2 which is correct.
Then in the same if clause check to see if that value equals 3. If so, return the String immediately (you may have even 4 or 5 consecutive a's but you also have 3 so return when the count of 3 is first encountered.
Else, if the if statement fails, reset consecutiveCounter to 1 and continue the loop.
At the end, outside the loop, return the string that indicates the requirement wasn't met.
Note: If you were trying to find the maximum number of consecutive a's setting the counter to 1 wouldn't work because you may have no a's at all. But since you are looking for a specific number == 3, it works fine.

Java int array and char array implementation: why does this work?

I am working on the Kattis problem "abc" in a programming seminar class. The question asks you to input three ints between 0 and 100, and have them match the pattern of another group of three char inputs with the case: A < B < C. Here 'A' will be int with least value, 'B' will be second greatest value, etc. I determined my logic but was unsure how to match values to char. Then a fellow student gave me help with the last line but I didn't get a chance to ask about how it worked. Code I have is as follows:
public class ABC {
public static void main(String[] args) {
var scanner = new Scanner(System.in);
int[] num = new int[3];
for (int i=0; i<num.length; i++) {
num[i] = scanner.nextInt();
}
Arrays.sort(num);
char[] chArr = scanner.next().toCharArray();
for (int i=0; i<chArr.length; i++) {
System.out.println(num[chArr[i] - 'A']); //How does num[chArr[i] - 'A'] work?
}
}
}
Input:
1 2 3
C A B
Output:
3 1 2
So, my question is: How does the expression in the println at the end work? I'm a noob to posting on SO, so any suggestions would be gratefully accepted.
A char in C is literally just an 8-bit integer. It tends to be used to represent ASCII characters, but in code it's an integer. Or in other words, char and uint8 are essentially the same type (in fact, one is an alias for the other in most implementations).
This relationship persists, in some form, into Java. A char is fundamentally an integer that presents itself as a character. Thus, you can do integer arithmetic with characters.
To examine num[chArr[i] - 'A']:
chArr[i] retrieves the character at index i of chArr, an array of chars. Say this is 'C'.
Note that the ASCII value of 'C' is 67.
Note that the ASCII value of 'A' is 65.
67 - 65 = 2. So, 'C' is the 3rd letter of the alphabet, meaning it corresponds to index 2 of num.
Retrieve the value at index 2 of num, and print it.
It's quite easy to understand:
Example :
char a = 'a';
char b = 'b';
// zero = 0 a this point
int zero = a - 'a';
// one = 1; and so on
int one = b - 'b';
Now in your case:
// is equivalent to whatever you enter and the difference of 'A'.
num[chArr[i] - 'A']
But if you enter something whose difference with A is more than the size of nums you are going to get an Array out bounds exception.

Need help to understand String length logic

I am trying to understand how String length() function work while reversing a string.
String length is 4 then why i need to give length()-1 in below working code.
No issue in below code, need help to understand length()
public class MStringReverse {
String getReverse(String input) {
System.out.println(input.length());
String reverse = "";
for(int i = input.length() - 1; i >= 0; i--) {
reverse = reverse + input.charAt(i);
}
return reverse;
}
public static void main(String[] args) {
MStringReverse mr = new MStringReverse();
String result = mr.getReverse("Achilis");
System.out.println(result);
}
}
As the index starts from 0, not from 1. So if you have a String of length 4 then 0,1,2,3 are the only possible indexes. If your index provided as the argument in charAt() is less than 0 or greater than or equals the length of the String then you will get StringIndexOutOfBoundsException exception. Here you can see how charAt method works :
public char charAt(int index) {
if ((index < 0) || (index >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return value[index];
}
That's because indexing starts at 0.
charAt(0) is character 1.
The answer is that you are iterating on indexes, which start at 0.
Imagine an array of length 4. It will store 4 items, the first one at index 0, second at index 1, third at 2 and the last one at index 3. The index of the last element is always length() - 1, that's why you put it as the upper border in loops in order to not raise an IndexOutOfBoundsException while iterating.
You could add some console output to view the accessed indexes per String for each iteration like this:
public class MStringReverse {
static String getReverse(String input) {
System.out.println("Input length is " + input.length());
String reverse = "";
for(int i = input.length() - 1; i >= 0; i--) {
System.out.println("accessing index " + i + " of \"input\"");
reverse = reverse + input.charAt(i);
System.out.println("last index of \"reverse\" is now " + (reverse.length() - 1));
}
return reverse;
}
public static void main(String[] args) {
String result = getReverse("Achilis");
System.out.println(result);
}
}
Because your string index starts at 0. Your length is 7. If you access input.charAt(7) you will get an index out of range exception.
A c h i l i s
0 1 2 3 4 5 6
The last index of the String is 1 less than the length because of a 0-based index.
i.e.
abcd has a length of 4 but to iterate from the last character, you need to start at index 3 (which is d), therefore length()-1 is where you start.
String length is always less than one because it starts index position from 0 .
if the String length is 4 then index position starts from 0 to 3
For this, you just understand the concept of the array.
Suppose we have an array of int of size 5.
So if size is 5 that means array index is from 0 to 4 last index always -1 from actual size.
Same apply on String length method in case of reversing the string.
Suppose you
String name = "Stack";
Its length is 5 but the last index is 4 because of the last index always -1 from actual length.

Java: Assign values to alphabet and determine value of a string

So I am trying to solve the problem in Java below. Could someone give me an idea of how to approach this? I can only think of using a bunch of confusing for-loops to split up the arr, go through the alphabet, and go through each string, and even then I am confused about strings versus chars. Any advice would be great.
--
Suppose the letter 'A' is worth 1, 'B' is worth 2, and so forth, with 'Z' worth 26. The value of a word is the sum of all the letter values in it. Given an array arr of words composed of capital letters, return the value of the watch with the largest value. You may assume that arr has length at least 1.
{"AAA","BBB","CCC"} => 9
{"AAAA","B","C"} => 4
{"Z"} => 26
{"",""} => 0
--
Here is what I have tried so far but I'm lost:
public static int largestValue(String[] arr){
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int largest = 0;
int wordTotal=0;
for (int i = 0; i < arr.length; i++){
String[] parts = arr[i].split("");
if (wordTotal < largest){ //I don't think this is in the right place
largest = 0; }
for (int j = 0; j < alphabet.length(); j++){
for(int k = 0; k <parts.length; k++){
if ( alphabet.charAt(j) == parts[k].charAt(0) ){
wordTotal = 0;
wordTotal += alphabet.indexOf(alphabet.charAt(j))+1;
}
}
}
}
return largest;
}
I would start by breaking the problem into parts, the first step is summing one String. To calculate the sum you can iterate the characters, test if the character is between 'A' and 'Z' (although your requirements say your input is guaranteed to be valid), subtract 'A' (a char literal) from the character and add it to your sum. Something like,
static int sumString(final String str) {
int sum = 0;
for (char ch : str.toCharArray()) {
if (ch >= 'A' && ch <= 'Z') { // <-- validate input
sum += 1 + ch - 'A'; // <-- 'A' - 'A' == 0, 'B' - 'A' == 1, etc.
}
}
return sum;
}
Then you can iterate an array of String(s) to get the maximum sum; something like
static int maxString(String[] arr) {
int max = sumString(arr[0]);
for (int i = 1; i < arr.length; i++) {
max = Math.max(max, sumString(arr[i]));
}
return max;
}
or with Java 8+
static int maxString(String[] arr) {
return Stream.of(arr).mapToInt(x -> sumString(x)).max().getAsInt();
}
And, finally, validate the entire operation like
public static void main(String[] args) {
String[][] strings = { { "AAA", "BBB", "CCC" }, { "AAAA", "B", "C" },
{ "Z" }, { "", "" } };
for (String[] arr : strings) {
System.out.printf("%s => %d%n", Arrays.toString(arr), maxString(arr));
}
}
And I get
[AAA, BBB, CCC] => 9
[AAAA, B, C] => 4
[Z] => 26
[, ] => 0
I think it helps to take note of the two key parts here:
1: You need to be able to find the value of a single word, which is the sum of each letter
2: You need to find the value of all words, and find the largest
Since you need to go through each element (letter/character) in a string, and also each element (word) in the array, the problem really is set up for using 2 loops. I think part of the whole problem is making the for loops clear and concise, which is definitely doable. I don't want to give it away, but having a function that, given a word, returns the value of the word, will help. You could find the value of a word, see if its the largest so far, and repeat. Also, to find the value of a word, please do not use 26 if's (look up ASCII table instead!). Hope this gives you a better understanding without giving it away!

String index out of range exception and for loop is not working

I am getting correct output for first for loop: for(int i=0;i<=name.length();i++) but don't know why I am not getting any output for this loop: for(int i=name.length();i>=0;i--). While executing I am getting an error saying that index out of range.
I check the error here but I didn't understand it.
public class runner {
public static void main(String[] args) {
String name = "java";
System.out.println(".length method()" + name.length());// executing
// .length()
// method
System.out.println(".charAt method()" + name.charAt(5));
for (int i = 0; i <= name.length(); i++) {
System.out.println(name.charAt(i));
}
for (int j = name.length(); j >= 0; j--) {
System.out.println(name.charAt(j));
}
}
}
Output
j
a
v
a
The problem is i<=name.length();
you want i<name.length(); because the length goes beyond the bounds of the wrapped char array in String.
For the same reason, you need to change the second for loop to
for(int j=name.length()-1 ;j>=0;j--){
arrays are 0-indexed, change <= to <
your will get that error every time you call
name.charAt(name.length())
You have out of bound exception, because Java array indexing starts from zero. For example if you have array with length = 5, then index of the first element will be 0 and index of the last element will be 4 (length - 1).
Change your line
for(int i=0;i<=name.length();i++){
to
for(int i=0;i<name.length();i++){
and line
for(int j=name.length();j>=0;j--){
to
for(int j=name.length()-1;j>=0;j--){
The other answers already pointed out that indexing begins at zero in java (and most other programming languages).
Since you seem to be new to java, here an example without the explicit use of indices.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Test
{
public static void main(String[] args)
{
String name = "java";
System.out.println("NORMAL ORDER\n");
for (char c : name.toCharArray()) // for each loop
System.out.println(c);
System.out.println("\nREVERSE ORDER\n");
List<Character> chars = new ArrayList<Character>(); // it's not possible to use primitive types as generic parameter
for (char c : name.toCharArray()) // we fill the chars list
chars.add(c); // autoboxing from char to Character
Collections.reverse(chars);
for (char c : chars)
System.out.println(c);
}
}
OUTPUT
NORMAL ORDER
j
a
v
a
REVERSE ORDER
a
v
a
j
Always remember to check the highest index that an array can have. In your case the name.length() function returns the size of the String name.
Suppose your String is "JAVA" it contains 4 characters. So name.length() will return 4.
But notice that the indices for each character are:
'J' - 0
'A' - 1
'V' - 2
'A' - 3
When you put your index counter at 4 it tries to access something that does not exist in the bounds of the array. Hence the ArrayIndexOutOfBoundsException is raised.
For solving your problem make all name.length() calls into name.length() - 1. Or modify the for loop to not include the case when the counter equals the name.length()

Categories