I am in a java bootcamp and had an assignment about reversing an array and printing it out. I figured it out after some searching and etc. But I do not get it here is my code
import java.util.Scanner;
public class Assignment_01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner num = new Scanner(System.in);
int[] arr;
arr = new int[5];
for(int i = 0; i < arr.length; i++) {
System.out.println("Please enter numbers for array");
arr[i] = num.nextInt();
}
for(int i = arr.length; i > 0; i--) {
System.out.print(arr[i - 1] + " ");
}
}
}
I do not get why the - 1 is added to the array. I tried to read other articles here but for some reason it is just getting past me. I am sorry for bothering you all but I know I need to be able to understand it. Thank you very much for your help
Thats pretty simple: in Java all indexes are being stored from 0, not from 1.
So, arr.length actually returns lastArrayIndex + 1, and you can't access arr[arr.length], because there is no element with such index.
And as the last index of array if arr.length-1, we start from it.
Your code is actually equal to this one (may be you will find it more straightforward):
for (int i = arr.length - 1; i >= 0; i--) {
System.out.println(arr[i] + " ");
}
Sorry for posting it a seperate answer - not enough reputation for writing comments.
Remember that the last index of an array is arr.length-1. Therefore, if you want to print the value starting from the last index it should be i-1. (Your i has been set to arr.length). If you don't want to have the arr[i-1]. You can do the following instead:
//change i from arr.length to i = arr.length-1
//change i>0 to i>=0
//change arr[i-1] to arr[i]
for(int i = arr.length-1; i >= 0;i--){
System.out.print(arr[i ]+" ");
}
Related
I'm supposed to write a program using for loops that print out the even indexes of my array. For example, if I create an array that has 10 numbers, it will have indexes from 0-9 so in that case I would print out the numbers at index 2, 4, 6 and 8. This is what I wrote so far but it doesn't work. Please note that I am not trying to print out the even numbers of the array. All I want are the even indexes.
Example I enter the following array: 3,7,5,5,5,7,7,9,9,3
Program output:
5 // (the number at index 2)
5 // (the number at index 4)
7 // (the number at index 6)
9 // (the number at index 8)
My Code:
public class Arrayevenindex
{
public static void main(String[] args)
{
int number; // variable that will represent how many elements the user wants the array to have
Scanner key = new Scanner(System.in);
System.out.println(" How many elements would you like your array to have");
number = key.nextInt();
int [] array = new int [number];
// let the user enter the values of the array.
for (int index = 0; index < number; index ++)
{
System.out.print(" Value" + (index+1) + " :");
array[index] = key.nextInt();
}
// Print out the even indexes
System.out.println("/nI am now going to print out the even indexes");
for (int index = 0; index < array.length; index ++)
{
if (array[number+1]%2==0)
System.out.print(array[number]);
}
}
}
You can just change your for loop and get rid of the inner IF...
for( int index = 0; index < array.length; index += 2) {
System.out.println(array[index]);
}
Just absolutely same thing using java 8 Stream API
Integer[] ints = {0,1,2,3,4,5,6,7,8,9};
IntStream.range(0, ints.length).filter(i -> i % 2 == 0).forEach(i -> System.out.println(ints[i]));
I assume this would be sufficient
// For loop to search array
for (int i = 0; i < array.length; i++) {
// If to validate that the index is divisible by 2
if (i % 2 == 0) {
System.out.print(array[i]);
}
}
This is what I did and it works:also I am not printing out index[0] because technically its not even thats why I started the for loop at 2. Your post did help me a lot. I also thank everyone else as well that took the time to post an answer.
import java.util.Scanner;
public class Arrayevenindex
{
public static void main(String[] args)
{
int number; // variable that will represent how many elements the user wants the array to have
Scanner key = new Scanner(System.in);
System.out.println(" How many elements would you like your array to have");
number = key.nextInt();
int [] array = new int [number];
// let the user enter the values of the array.
for ( int index = 0; index < number; index ++)
{
System.out.print(" Value" + (index+1) + " :");
array[index] = key.nextInt();
}
// Print out the even indexes
System.out.println("/nI am now going to print out the even indexes");
for ( int index = 2; index < array.length; index +=2)
{
System.out.print(array[index] + " ");
}
}
}
I'm supposed to create and initialize a 100-element array, then make the 7th element the number "7", and finally print the array, starting a new line every 20 elements. I've been trying to figure this out for a long time and I can't.
My code right now is:
public class Array {
public static void main(String args[]) {
int [] array = new int[100];
for (int a = 0; a < array.length; a++) {
if (array[a] == 6) {
array[a]=7;
array[a] = a + 1;
}
printArray(array);
}
}
public static void printArray(int[] array){
for (int a=0; a < array.length; a++) {
System.out.print(" " + array[a]);
if ((a - 1) % 20 == 0) {
System.out.println("");
}
}
}
}
When I run this my output is a lot of zeros, far more than 100. They are separated every 20 characters as intended, but the seventh element is not 7. I think it has to do with the association between int "a" and my array, but I can't figure it out. I know the solution must be simple but I just cannot see it. Thank you all!
Proper indentation of your code, in particular the main method, reveals what is going on. You are calling printArray from within the for loop, so you are printing the array contents 100 times.
for (int a = 0; a < array.length; a++) {
if (array[a] == 6) {
array[a]=7;
array[a] = a + 1;
}
printArray(array);
}
Move the call to printArray after the } ending brace for the for loop.
Now you'll get 100 0s.
Also, I think you meant to have array[a] = a + 1; executed if the index was not 6, e.g.
if (array[a] == 6) {
array[a] = 7;
} else {
array[a] = a + 1;
}
Additionally, you will want to print a newline after 20 numbers, e.g. after indexes 19, 39, etc., so add 1 to a before calculating the remainder, instead of subtracting 1, so that 19 + 1 = 20, whose remainder is 0.
There are many things wrong. However, to answer your question, you are printing the array 100 times since printArray is inside your first loop.
You misplaced an end parenthesis in your main method. The properly formatted method looks like this:
public static void main(String args[]) {
int [] array = new int[100];
for (int a = 0; a < array.length; a++) {
if (array[a] == 6) {
array[a]=7;
}
array[a] = a + 1;
}
printArray(array);
}
First of all your code is organized very badly so it's very easy for u to miss what went where. You have 2 major mistakes, first of all you called printArray()
Inside your for loop and therefore printed it 100 times.
Second, you kept checking if the value inside the array in index a is 6.
You need to check if a is 6 since it is your index like this:
if(a == 6)
array[a] = 7;
Well, I ran your code, and there are a few places that can be corrected.
As for your problem of the many things being printed, that's because you've placed your printarray() inside the for loop, so it's printing the array 100 times.
As for printing it out, i find this code to be more concise:
public static void printArray(int[] array){
int counter = 0;
for(int i = 0; i < array.length; i++){
System.out.print(array[i] + " ");
counter++;
if(counter == 20){
counter = 0;
System.out.print("\n");
}
}
}
Also, I'm not really sure why you're using a for loop to just change the 7th element. You could use this:
array[6] = 7;
I'm not really sure what you're doing in the for loop.
I hope this helped! Good luck!
Suppose I declare an array:
int[] arr = {10,2,7,11,3};
The largest (positive) change in this array would be 9 as 11 - 2 = 9.
How would I write a method that find the largest change in code with the smaller integer occurring earlier?
Thank you,
I rewrote the answer since I misunderstood the question.
The simplest but almost certainly not the most efficient way to do this is to check every change and comparing it to the previous one. If it is bigger, discard the previous one and remember this one instead.
int change = arr[1] - arr[0]; //give it an initial value, if we find a bigger change we will replace it
for(int i = 0; i < arr.length - 1; i++) {
for(int j = i + 1; i < arr.length; j++) {
if(arr[j]-arr[i] > change) {
change = arr[j]-arr[i];
}
}
}
This will still give an answer even if there are no positive changes. If you do not want that, you can modify it. It is trivial.
Keep in mind that arr.length - 1 is important in the outer loop.
Looks like you want to find the smallest number and the largest number in the list and comparing it with the largest number on the list.
List first item as minimum.
Compare to next item and if greater, assign that number as lesser.
List first item as largest.
Compare to next item and if smaller, assign that number as greater.
At the end of the list, you will have the least and the greatest number. The difference will be the difference between the smallest and the largest.
Hope that helps.
Interesting question! You could brute-force this pretty easily, as I'm still thinking for a more creative solution.
int [] arr = {5, 4, 3, 2, 1};
int biggestDifference = arr[1]-arr[0];
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
if ((arr[j] - arr[i]) > biggestDifference) {
biggestDifference = arr[j] - arr[i];
}
}
}
Sorting the array would ensure that the smallest number will always be at the front and largest at the back.
public static void main(String []args){
int[] arr = {10,2,7,11,3};
int diff = findBiggestDiff(arr);
System.out.println(diff);
}
public static int findBiggestDiff(int[] arr){
Arrays.sort(arr);
int diff = arr[arr.length-1] - arr[0];
return diff;
}
hi guys i am just doing some reading for myself to learn java and came across this problem and is currently stuck.
i need to print out series of number based on the input given by the user.
for example, if input = 5, the output should be as follows
#1#22#333#4444#55555
import java.util.*;
public class ex5{
public static void main(String[] args){
Scanner kb = new Scanner(System.in);
System.out.println("Please type a #: ");
int input = kb.nextInt();
for(int i=0;i<input;i++){
if(input==1){
System.out.print("#1");
}
if(input==2){
System.out.print("#1#22");
}
}
}
}
this doesnt seem to be working because this is the output i get
Please type a #:
2
#1#22#1#22
im not sure what to put inside the for loop right now and i dont think i am using the for loop here very well either...
any help guys?
for (int i=1; i<=5; i++){
System.out.print("#");
for (int j=1; j<=i; j++) System.out.print(i);
}
out
#1#22#333#4444#55555
you're going to need a nested for-loop to solve this problem.
Yeah, this isn't how you want to do it. You're going to want to build the string inside the for loop.
Start with a new string
String s = "";
As you loop, add to that string.
for(int i=1;i<=input;i++){
s += #;
for(int j=0; j<i; j++) {
s+=i;
}
}
You need to use a nested for loop.
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Please type a #: ");
int input = kb.nextInt();
for (int i = 1; i <= input; i++) {
System.out.print("#");
for (int k = 0; k < i; k++) {
System.out.print(i);
}
}
}
It is because you are checking for the numbers 1 and 2 in the if statement. It is hard coded to only check for these two numbers and would not work once you go past the values that you have an if statement for
What you want to do is to output the value of your iterator (in your case, i) i times (hint, you can use another loop inside the big loop) and then ad an # sign at the end of the string.
I will try to not give you any code so you can learn it yourself, but feel free to ask more questions.
You are trying to print given number - given number of times?
Then you'll need two loops for this - outer loop for iterating the number and inner - for iterating -times the given number.
It would be something like this:
for(int i = 0; i < input; ++i) {
System.out.print("#");
for(int j = 0; j < i; ++j) {
System.out.print(i);
}
}
I need to write a method that accepts two ints as arguments, a min and a max. On the first line i need to print all numbers in that range (inclusive). On the next line I start with min+1, print all numbers up to max, and then go back to the front of the range and print min. Next line I start with min+2, and so on until I have repeated this starting with each number in the range.Very hard to explain, here's two examples: Say I pass 1 and 5 as the min and max arguments. I want the method to print this:
12345
23451
34512
45123
51234
Or if 3 and 9 were passed, I would expect this:
3456789
4567893
5678934
6789345
7893456
8934567
9345678
I've tried all kinds of things, I'm sure there is an easy way to do this that I am not realizing. I'm supposed to do this without arrays or arrayLists. I think I have a good base to work with, but I just can't figure out where to go from here. My base code prints this:
12345
2345
345
45
5
And this:
3456789
456789
56789
6789
789
89
9
I'm stumped. Here's my code:
public void printSquare(int min, int max){
for (int i=min; i<=max; i++){
for (int j=i; j<=max; j++){
System.out.print(j);
}
System.out.println();
}
}
You should think about how many values you want on each row, and then determine what those values should be. Its hard to make it any clearer without giving you the solution.
Let us know how you go.
Peter is right, and IMO is answering a homework question in the right manner. You know how many elements you want on each line, so you need an outer loop that gives you that many elements, this will stop you from getting the cascading behavior you're seeing now.
At that point you need to think about your inner loop(s), and you'll probably find this easiest using the modulus operator (%). This will allow you to iterate without ever going over your target.
You should be able to figure it out from there, and you're much better off figuring out the algorithm yourself than copying it from someone else, at least at this level of development. Good Luck!
Think about a way to print the missing numbers. The answer is below, if you cannot come up with it you can check it.
This should also print the missing parts:
public void printSquare(int min, int max){
for (int i=min; i<=max; i++){
for (int j=i; j<=max; j++){
System.out.print(j);
}
for (int k=0; k<i-min; k++){
System.out.print(min+k);
}
System.out.println();
}
}
I didn't run this one but it might work:
public void printSquare(int min, int max){
int dif = max - min;
for (int i=min; i<=max; i++){
for (int j=i; j <= i+dif ; j++){
int temp = j;
if ( temp > max ) temp = temp - max;
System.out.print(temp);
}
System.out.println();
}
}
try and just shift an array like so:
static void Main(string[] args)
{
// this will work equally well with numbers letters or other types of characters
int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
String a = "hello";
for (int i = 0; i < nums.Length; i++)
{
int j = 5;
int num = i;
while (j-- > 0)
{
if (num >= nums.Length)
{
num = 0;
}
// shift the loop
Console.Write(nums[num++]);
}
Console.WriteLine();
}
}
public class Test1{
public void printSquare(int min, int max){
for (int i=min; i<=max; i++){
for (int j=i; j<=max; j++){
System.out.print(j);
}
for(int k= min; k<i; k++){
System.out.print(k);
}
//System.out.print(i-1);
System.out.println();
}
}
public static void main(String[] args){
Test1 t = new Test1();
t.printSquare(1,5);
}
}
This is a very simple implementation. Hope this helps!
int n = max-min+1;
for (int i=0 ; i<n; i++){
for (int j=0; j<n; j++)
cout<<min + (i+j)%n;
cout<<"\n";
}
Output:
min = 3 | max = 9
3456789
4567893
5678934
6789345
7893456
8934567
9345678
Here's the code..
for i = 0 to max-min
for j = 0 to max-min
print min + (i+j)%n