How to print array data in columns [duplicate] - java

This question already has answers here:
Is there an easy way to output two columns to the console in Java?
(3 answers)
Closed 4 years ago.
I have code here that takes in two different array types, one boolean and one of ints. I want to get the code to print like this
marked edgeTo
------ --------
true 2
true 0
true 0
true 5
true 3
true 0
I am currently using a foreach loop to print out the data and I cannot get edgeTo's data (2 0 0 5 3 0) to print underneath its title edgeTo and across from its respective marked boolean value. Any suggestions as to what I am doing wrong? Here is the snipet of code I have so far
System.out.println("marked edgeTo");
System.out.println("------- --------");
for (boolean el : bob.marked) {
System.out.println(el);
}
for (int el : bob.edgeTo) {
System.out.println(el);
}

if two arrays have same length, you can use 1 loop
System.out.println("marked\tedgeTo");
System.out.println("-------\t------");
for (int i = 0; i < bob.marked.length;i++) {
System.out.println(String.valueOf(bob.marked[i]) + "\t" + String.valueOf(bob.edgeTo[i]));
}

In case your arrays are of different lengths:
System.out.println("marked edgeTo");
System.out.println("------- --------");
int lesserArr = Math.min(bob.marked.length, bob.edgeTo.length);
for (int i = 0; i < lesserArr;i++) {
System.out.println(String.valueOf(bob.marked[i]) + "\t" + String.valueOf(bob.edgeTo[i]));
}
for (int j = 0;j < Math.abs(bob.marked.length-bob.edgeTo.length); j++) {
if (bob.marked.length < bob.edgeTo.length)
System.out.println("\t\t" + String.valueOf(bob.edgeTo[lesserArr + j]));
else
System.out.println(String.valueOf(bob.marked[lesserArr + j]));
}
}

Related

Sum of a sequence by using for and while loop [duplicate]

This question already has answers here:
Sum numbers using loop
(2 answers)
java for loop sum and average of range
(3 answers)
Closed 2 years ago.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Last Number ");
int inputedNumber = Integer.valueOf(scanner.nextInt());
int result = 0;
int outcome = 0;
for(int i = 0; i < inputedNumber; i++) {
result += ;
}
/*/*while (outcome <= inputedNumber) {
result += inputedNumber;
outcome++;
}*/
System.out.println(result);
}
}
I have a problem to understand what is wrong here, because I would like to solve the task , originally it should be (Implement a program, which calculates the sum 1+2+3+...+n where n is given as user input.) but it gives me another answer, please , pin out for me in a both way , to understand what I went wrong , because everything so far make sense for me , but code doesn't work as it should to be
You can try the code below:
for(int i = 1; i <= inputedNumber; i++) {
result += i;
}
Note: you should start with i=1 based on your requirement:
1+2+3+..+n
You need to replace result += ; with result += i;
For the first case. This is not a valid Java code, you should put a value/variable after += operator.
for (int i = 0; i < inputedNumber; i++) {
result += ;
}
If you put the variable i after it, and use i<= inputedNumber. You will get the expected answer.
for (int i = 0; i <= inputedNumber; i++) {
result += i;
}
In the second case, you are actually doing n*(n+1)
while (outcome <= inputedNumber) {
result += inputedNumber;
outcome++;
}
This can be tested as input the value as 2:
The first iteration:
outcome -> 0
inputedNumber -> 2
result -> 2
The second iteration:
outcome -> 1
inputedNumber -> 2
result -> 4
The third iteration:
outcome -> 2
inputedNumber -> 2
result -> 6
The fix is similar to what I suggested before. You could take this as an exercise.

How to use Less than and equal to use for loop to build array in java

public static void loop_array_build1()
{
int array_quantity = 12;
int rd_1[] = new int[array_quantity];
//Building
for (int i = 1; i < array_quantity; i++)
{
rd_1[i] = i;
System.out.println("Array building : " + rd_1[i]);
}
System.out.println("");
System.out.println("Total array built -> " + rd_1.length);
System.out.println("");
//Showing
for (int x = 1; x <= rd_1.length; x++)
{
System.out.println("Array showing : " + x);
}
}
I can not use Less than and equal(=<) because I want to build from 1 until 12, but if I use normal Less than(<)
it's not error
for(int i = 1; i < array_quantity; i++) << Not error
for(int i = 1; i <= array_quantity; i++) << Error
Or I have to start array index at 0 only, not from 1?
When I print this line System.out.println("Total array built -> " + rd_1.length); It show array has 12,
maybe it's depended on from these 2 line
int array_quantity = 12;
int rd_1[] = new int[array_quantity];
How I can know really quantity array already were build, not in from index.
Array indexing in Java starts from 0. So, if rd_1 has 12 elements, then you can address rd_1[0] to rd_1[11] inclusive.
Hence your for loop should be of the form
for (int i = 0; i < rd_1.length; i++)
You can't build from index 1 to 12 because array indexes count from 0 therefore 0-11. if you want these indexes to have the values 1-12 userd_1[i] = i+1; and i starts at 0.
The following 2 lines instantiate the array with the given length which is 12. After this line, the array exists with 12 indexes with value null.
int array_quantity = 12;
int rd_1[] = new int[array_quantity];
The length is fixed to what you defined on instantiating the array and cannot be changed. If you want to know the amount of values which are actually set, you will have to count them like this:
int counter = 0;
for (int i : rd_1) {
counter++;
}
counter then holds the amount of values which are set
Taking your snippet this would be the output, that means as other mentioned Array in Java starts from index 0, Hence if you don't use it will be zero
// If you get the value of 0 index it will be 0
System.out.println("rd_1[0] :- "+ rd_1[0]);
//Output :- rd_1[0] :- 0
// If you get the value of 11 index it will be 11
System.out.println("rd_1[11] :- "+ rd_1[11]);
//Output :- rd_1[11] :- 11
// If you get the value of 11 index it will be 11
System.out.println("rd_1[12] :- "+ rd_1[12]);
//Output :- Exception ArrayIndexOutOfBoundsException because Array will have 0 to 11 index, 12index will not be there
So the correct snippet would be as below
public static void loop_array_build1()
{
int array_quantity = 12;
int rd_1[] = new int[array_quantity];
for(int i=0;i<array_quantity;i++)//Building
{
rd_1[i] = i+1;
System.out.println("Array building : rd_1["+i+"] -- "+rd_1[i]);
}
}
Array building : rd_1[0] -- 1
Array building : rd_1[1] -- 2
Array building : rd_1[2] -- 3
Array building : rd_1[3] -- 4
Array building : rd_1[4] -- 5
Array building : rd_1[5] -- 6
Array building : rd_1[6] -- 7
Array building : rd_1[7] -- 8
Array building : rd_1[8] -- 9
Array building : rd_1[9] -- 10
Array building : rd_1[10] -- 11
Array building : rd_1[11] -- 12

Printing Odd and Even Elements of an Array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I'm trying to write a program that reads a sequence of integers and divide it into two sequences. The values on odd positions will be the first sequence and the values of even positions will be the second sequence. The program prints the elements of the first sequence and then the elements of the second sequence separated by a single space. The first input value specifies the number of elements.
Input: 7 1 2 4 5 6 8 9
Expected Output: 1 4 6 9 2 5 8
My Output: 2 0
package twosequences;
import java.util.Scanner;
public class TwoSequences {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] values = new int[n];
for (int i = 0; i < values.length; i ++) {
values[i] = sc.nextInt();
}
int odd = 0;
int even = 0;
int i = 1;
if (i % 2 == 0) {
even = values[i];
} else {
odd = values[i];
}
i++;
System.out.printf("%d %d%n", odd, even);
}
}
I'm not sure why I'm outputting 2 0. Any suggestions?
You need two different loops to iterate over even and odd elements respectively to obtain the desired output.
for (i = 0 ; i < n ; i += 2) {
even = values[i];
System.out.printf("%d ", even);
}
for (i = 1 ; i < n ; i += 2) {
odd = values[i];
System.out.printf("%d ", odd);
}
Hope this helps.
Print the even-numbered elements in one loop; then use another loop to print the odd-numbered elements.
System.out.print(values[0]); // print by itself to avoid prepending " ".
for (int i = 2; i < values.length; i += 2) {
System.out.print(" " + values[i]);
}
for (int i = 1; i < values.length; i += 2) {
System.out.print(" " + values[i]);
}
System.out.println();
you take the second element of an array (2), and only for that one you are checking if it's even or not.
The result goes true for first 'if', and
even = 2;
, the if statement ends and odd stays as declares (0), that' why u got result like that.
If you want output whith more than 2 integers, you need to change
, where n would be all scanned even numbers.
Try to put a counter in first for loop, like
for (int i = 0; i < values.length; i ++) {
values[i] = sc.nextInt();
if(values[i]%2==0) evenCounter++;
}
Now to count odds just count values.length - evenCounter.
Also you do not need to make simple arrays like int[], you can go with
List<Integer> list = new ArrayList<>();
You will be able to add elements in for loop withour knowing how many elements you will be implementing.
Hope some of those helps.

Arraylist look for specific Element [duplicate]

This question already has answers here:
How to count the number of occurrences of an element in a List
(25 answers)
Closed 6 years ago.
I'm trying to do a Blackjack game but I don't know how to change the value of "ACE" to 1 if 11 is too high. I'm now trying to search a Arraylist for A's to change the value of one ore more of them. But how can I see how much A's are in my Arraylist?
while (getPointsPC() < 17 || getPointsPC() < getPointsPL()){
int acees = 0;
random = bj.getRandom();
CardsPC.add(bj.getCard(random));
setPointsPC(random);
lblPointsPC.setText("Points Dealer: " + Integer.toString(getPointsPC()));
String text = CardsPC.get(0);
for(int i = 1; i < CardsPC.size(); i++){
text = text + ", " + CardsPC.get(i);
}
if (CardsPC.contains("A") && getPointsPC() > 21 && acees < CardsPC.**HOW_MUCH_A's???**){
setPointsPC(13);
acees++;
}
lblCardsPC.setText(text);
}
Is your CardsPC is your mentioned ArrayList? Just set counter variable:
String text = "";
int counter = 0;
for(int i = 0; i < CardsPC.size(); i++){
text = text + (i > 0 ? ", " : "") + CardsPC.get(i);
if (CardsPC.get(i).contains("A")) { // or use equals, base on your input.
counter++;
// do something with found "A" element if you want.
}
}

Using variable/dynamic condition variable in nested for loops

I don't know how to address the question properly to even google it so far.
In a nested loop such as this
for (int i=0;i>0;i++)
{
for(int k=0;k<0;k++)
{
}
}
What kind of applications would there be if we use k
I have this question because I wanted to make a loop which iterates like star printing with * char printing left triangle but it iterates on a 2 dimensional matrix as the cursor moves it iterates on the array items such as this
a[0][0]
a[1][0], a[1][1]
a[2][0], a[2][1], a[2][2]
a[3][0], a[3][1], a[3][2], a[3][3]
I want to figure out a for loop or something to be able to iterate the array such as this. What do you suggest?
You must change the first for condition, because when i = 0 the condition i > 0 is false, so it never enters the loop.
Note that when you go line be line, the k must iterate in this pattern: [0, 01, 012, 0123] while i in [0, 1, 2, 3]. In other words, k must iterate until it reaches the value of i, so the condition of the nested for must be k < i + 1.
for (int i = 0; i < 4; i++) {
for (int k = 0; k < i + 1; k++) {
// Here you should access to the array
// array[i][k]
System.out.print(i + " " + k + " - "); // [DEBUG]
}
System.out.println(); // [DEBUG]
}
Output: Just to see indexes
0 0 -
1 0 - 1 1 -
2 0 - 2 1 - 2 2 -
3 0 - 3 1 - 3 2 - 3 3 -
It looks like what you want is something like
for (int i = 0; i < SOME_LIMIT; ++i) {
for (int k = 0; k <= i; ++k) {
do_something_with (a[i][k]);
}
}
It looks like you've already done the hard part -- designing the basic premise of the application and writing down on paper what you'd like to do.
Now all you do is take what you've written down and translate it in to code.
I'll give you one hint. On the inside loop, for(int k=0;k<0;k++), thibnk about how you would change this in order to achieve the behavior you're looking for.
Keep at it, you'll get there. The hard part is already done.

Categories

Resources