arrays have no concept of negative indices, if you want to traverse from the last to first then you must START at the LAST index and move to the FIRST.
for(i =3; i>0; i--){
System.out.println(var[i - 1]);
}
Answer from T McKeown on Stack Overflowarrays have no concept of negative indices, if you want to traverse from the last to first then you must START at the LAST index and move to the FIRST.
for(i =3; i>0; i--){
System.out.println(var[i - 1]);
}
You were starting with a negative index which does not exist in arrays. It's also good practice to use array.length instead of an explicit number in case you change the size of the array later on.
public class RevIntArray {
public static void main(String[] args) {
int var[] = new int[] {1,2,3};
for(int i = var.length - 1; i >= 0 ; i--) {
System.out.println(var[i]);
}
}
}
Arrays in Java are indexed from 0 to length - 1, not 1 to length, therefore you should be assign your variable accordingly and use the correct comparison operator.
Your loop should look like this:
for (int counter = myArray.length - 1; counter >= 0; counter--) {
use myArray.length-1
for(int counter=myArray.length-1; counter >= 0;counter--){
System.out.println(myArray[counter]);
}
Videos
Replace your for loop with this:
String read = null;
for(int i=0; i<buffer.length; i++) {
read = scan.nextLine();
if(read.equals("quit")) {
break;
} else {
buffer[i] = read;
}
}
You want to read the new line at the beginning of the loop, not at the end.
The only problem I can find in your code is skipping the line after nextInt() .The nextInt() method doesnot consume the whole line it only consume the next token of the input as an int so you are on the same line(where you read the int) and you have to skip the line.By doing scan.nextLine(); after scan.nextInt();
String buffer[];
Scanner scan = new Scanner(System. in );
System.out.println("Enter Size: ");
int num = scan.nextInt();
buffer = new String[num];
scan.nextLine(); // skipping the line
String read = scan.nextLine();
for (int i = 0; i < buffer.length; i++) {
if (read.equals("quit")) {
break;
} else {
buffer[i] = read;
}
read = scan.nextLine();
}
for (int k = buffer.length - 1; k >= 0; k--) {
System.out.println(buffer[k]);
}
Demo(Prints the array backwards)
No need for libraries, plain Java will do
new StringBuilder("Bird").reverse().toString();
Maybe You can using Apache commons StringUtils
public static void t(String [] list) throws IOException
{
for (int i = 0; i <list.length; i++)
{
String element = list[i];
String reverseElement = StringUtils.reverse(element);
System.out.println(reverseElement);
}
}