I know there is another thread with the same name, but the answer isn't really the one I'm looking for.
I can only use for loops. The other answer uses complex syntax like:
reverse = !reverse ? i == max : reverse;
i = reverse ? i-1 : i+1;
Can it be simpler than that?
Thanks a lot.
So, this is the output.
I can only get until 4 I don't know how to keep from there...
1
1 2
1 2 3
1 2 3 4
1 2 3
1 2
1
This is what I have so far:
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i=1;i<=4;i++) {
for(int j = 1; j <= i; j++) System.out.print(j+" ");
System.out.println("");
}
for(int i=4;i>=1;i--){
for(int j = 1; j <= i; j++) System.out.print(j+" ");
System.out.println("");
}
}
}
but my output is the following:
1
1 2
1 2 3
1 2 3 4
1 2 3 4
1 2 3
1 2
1
Hii have done using the below code
public class Test
{
public static void main(String args[]) {
int j,i;
int max=4;
int n=0;
for(i=0;i<((max*2)-1);i++)
{
if(i<max)
n++;
else
n--;
for(j=1;j<=n;j++)
{
System.out.print(j+" ");
}
System.out.println("");
}
}
}
The below is the outputYou can generalize it for any number i hope this is fine
Your two outer loops are:
for(int i=1;i<=4;i++) {
for(int i=4;i>=1;i--) {
This will generate the sequence 1, 2, 3, 4, 4, 3, 2, 1. If you want to only have one 4-length row in the output, change the second loop to:
for(int i=3;i>=1;i--) {
so that it starts from 3, instead of 4. The problem is that currently, both your outer loops generate the value 4 right after one another.
Related
If a user inputs some numbers like this (number of lines are arbitrary):
1
2
3
4
5
I need to create a method that makes a series of outputs like this:
First output:
1
2
3
4
5
Second output:
2
1
3
4
5
Third output:
4
3
2
1
5
Fourth output:
5
4
3
2
1
I'm just confused with the pattern that is being utilized here.
I think you must flip from the middle on each iteration i the sub sequence from 0 to i*2 -1.
Pseudo code assuming that seq is the input sequence:
void pattern(seq){
print(seq)//First output
for(int i=1;i*2<=seq.length-1;i++){
seq = concatenate(seq.subSquence(i,i*2-1), seq.subSquence(0,i-1), seq.subSquence(i*2,seq.length-1) );
print(seq)
}
seq = concatenate(seq.subSquence(i,seq.length-1), seq.subSquence(0,i-1))
print(seq)//Last output
}
What you have to do is to take always next_element from original structure (array, list) and place it top.(others elements goes down by 1 till next element initial position)
next_element is start from second_position and it's increment by 1 till the end of structure (length or size)
import java.util.Arrays;
import java.util.stream.Collectors;
public class Test {
public static void main(String[] args)
{
int a1[] = {1,2,3,4,5};
new Test().compute(a1);
int a2[] = {5,4,3,2,1};
new Test().compute(a2);
}
public void compute(int[] a)
{
for(int i=1;i<a.length;i++)
{
//i : next_element which will be place always on first_position
int temp= a[i];
//j : current_element (iterate by till next_element)
for(int j=i; j>0; j--)
{
a[j] = a[j-1];
}
a[0] = temp;
String str = Arrays.stream(a).boxed().map(t->String.valueOf(t)).collect(Collectors.joining(","));
System.out.println("step="+i+": array="+str);
}
}
}
Output
step=1: array=2,1,3,4,5
step=2: array=3,2,1,4,5
step=3: array=4,3,2,1,5
step=4: array=5,4,3,2,1
and (reverse)
step=1: array=4,5,3,2,1
step=2: array=3,4,5,2,1
step=3: array=2,3,4,5,1
step=4: array=1,2,3,4,5
The following is no homework. I'm just trying to write my own permutation code. I have an idea but I have problems in writing this idea as code.
As example the input is myArray={1,2,3};
Then the output is supposed to be:
1 2 3
2 1 3
2 3 1
3 2 1
3 1 2
1 3 2
I figured out it's possible by switching the first element with second, then switch second with third (however not entirely possible, but I know I need this).
That's why my question is how can I do this in Java?
I have 1 2 3 and I want switch first element with second, so I get 2 1 3. Print this. Now I want switch second element with third, I get 2 3 1, print it. Repeat n! times where n is myArray length.
I tried to do this with the following code but it seems like I'm far away from it :(
public class Test{
public static void main(String[] args){
int[] myArray = {1,2,3};
for(int x=0; x<6; x++){
for(int i=0; i<myArray.length-1; i++){
int temp=myArray[i];
myArray[i]=myArray[i+1];
myArray[i+1]=temp;
}
for(int i=0; i<myArray.length; i++){
System.out.print(myArray[i]+" ");
}
System.out.println("");
}
}
}
Output:
2 3 1
3 1 2
1 2 3
2 3 1
3 1 2
1 2 3
I'm not sure if I understood correctly though.
public static void main(String[] args) {
int[] myArray = {1, 2, 3};
for (int i = 0; i < 6; i++) {
print(myArray);
int temp = myArray[i % myArray.length];
myArray[i % myArray.length] = myArray[(i + 1) % myArray.length];
myArray[(i + 1) % myArray.length] = temp;
}
}
private static void print(int[] array) {
for (int anArray : array) {
System.out.print(anArray + " ");
}
System.out.println("");
}
EDIT:
I noticed, there is a wrong order, so it should be better:
public static void main(String[] args) {
int[] myArray = {1, 2, 3};
for (int i = 0; i < 6; i++) {
int idx = i % (myArray.length - 1);
print(myArray);
int temp = myArray[idx];
myArray[idx] = myArray[idx + 1];
myArray[idx + 1] = temp;
}
}
I'm creating a program that receives a 6x7 list of integers and stores then in an array. However I'm getting a java.util.NoSuchElementException, I've been out of practice for a while so I may be sloppy with my syntax and I'm wondering what I am doing wrong.
This is an example of a .txt file being read.
0 1 0 3 1 6 1
0 1 6 8 6 0 1
5 5 2 1 8 2 9
6 5 6 1 1 9 1
1 5 6 1 4 0 7
3 5 3 4 4 0 7
my code
public static void main(String[] args) throws FileNotFoundException
{
System.out.println(new File("num1.txt").getAbsolutePath());
int i;
int j;
i=0;
j=0;
int [][]connect4Array;
connect4Array= new int [6][7];
int [][]list;
Scanner readFile = new Scanner(new File("num1.txt"));
while(readFile.hasNextInt())
{
for(i=0;i<5;i++)
{
connect4Array[i][j]=readFile.nextInt();
for(j=0;j<6;j++)
{
connect4Array[i][j]=readFile.nextInt();
}
}
}
System.out.println(connect4Array[1][2]);
list=connect4Array;
isConsecutiveFour(list);
readFile.close();
}
list=connect4Array;
isConsecutiveFour(list);
readFile.close();
}
public static boolean isConsecutiveFour(int[][] values) throws FileNotFoundException
{
boolean connected4;
connected4=false;
int cntr1;
int cntr2;
cntr1=0;
cntr2=0;
int i;
int horizontalMatch;
int verticalMatch;
int diagonalMatch;
horizontalMatch=0;
i=0;
//check for horizontal matches
for(cntr1=0;cntr1<6;cntr1++)
{
for(cntr2=0;cntr2<7;cntr2++)
{
if(values[cntr1][cntr2]==values[cntr1][cntr2])
{
cntr2++;
if (values[cntr1][cntr2]==values[cntr1][cntr2])
{
cntr2++;
if (values[cntr1][cntr2]==values[cntr1][cntr2])
{
cntr2++;
if (values[cntr1][cntr2]==values[cntr1][cntr2])
{
connected4=true;
horizontalMatch=+1;
}
}
}
}
}
}
System.out.println(connected4);
System.out.println("Horizontal Matches= "+horizontalMatch);
return(connected4);
}
the full error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at assignment5.Assignment5.isConsecutiveFour(Assignment5.java:90)
at assignment5.Assignment5.main(Assignment5.java:49)
edit:
I wasn't planning on sharing the rest of my code, but after fixing the error in the for loop, it noticed another in a different part of my code with the same error. If you guys could help again that'd be great
Each time through the outer loop, you're reading 35 values, because you're iterating the second loop 5 times, and each iteration reads one value, then iterates the third loop 6 times. And you have 42 values in the file. So you're finishing the file partway through the second iteration of the outer loop, then getting the error when you're trying to read the 43rd value.
You probably don't need the outer loop at all, or the first line inside the second loop. The following may do what you want. Notice how I've changed the termination conditions on each loop, to accommodate your 6 rows and 7 columns.
for (i = 0; i < 6; i++) {
for ( j = 0; j < 7; j++){
connect4Array[i][j]=readFile.nextInt();
}
}
the problem is with connect4Array[i][j]=readFile.nextInt(); in outer loop which the value of j at there is always 0 as you defined before loops but in inner loop it'll get the value of j defined in for statement also you need to increase the borders (i and j):
for(i=0;i<=5;i++)
{
for(j=0;j<=6;j++)
{
connect4Array[i][j]=readFile.nextInt();
}
}
What I have to do is to create a SpanishNumbers application that displays numbers 1 through 10 in Spanish. A method with an int parameter should display the Spanish word for the number passed. A loop structure in the main() method should be used to call the method ten times. The Spanish word equivalents for numbers 1 through 10 are...
1 uno 2 dos, 3 tres, 4 cuatro, 5 cinco, 6 seis, 7 siete, 8 ocho, 9 nueve, 10 diez.
I do not know why am I getting this error below
http://i.stack.imgur.com/HLIiI.png
Thanks in advanced!
import java.util.Scanner;
public class SpanishNumberss {
public static void spanishNumbers(int num) {
String[] numbers = {"uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez"};
for (int i = 1; i <= num; i++) {
System.out.println(numbers[num]);
}
}
public static void main(String args[]) {
for (int i = 1; i <= 10; i++)
spanishNumbers(i);
}
}
In Java, indexes of an array start with 0, not 1, and run through length - 1, not length.
Adjust your for loop condition in main as follows:
for (int i = 0; i < numbers.length; i++)
You'll need to adjust your other for loop similarly.
Arrays indexes are 0 based (starts from 0 not from 1) . Also you are declaring your array numbers inside the method each time is called just declare as a class variable. So take care that in your example index 0 refers to 1 (uno) and so on.
I made you an example and add 0,"cero"
public class SpanishNumberss {
private static final String[] numbers = {"cero","uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez"};
public static void spanishNumbers(int num) {
//loop here is unnecesary
System.out.println(numbers[num]);
}
public static void main(String args[]) {
//and here in main i call them from 1 to 10
for (int i = 1; i < 11; i++){
spanishNumbers(i);
}
}
}
ArrayIndexOutOfBounds means you have gone out of the boundaries of your array (in your case numbers). What you have to realize is array's are 0 index-based. So in your for loop, you really 0 - 9, not 1-10.
And an even better solution, as #rgettman has posted is to use the length property of the array. So you are not hard-coding in those magic numbers.
Arrays go from 0 to N-1
That's why you're getting that error, change your for cycle to:
for (int i = 1; i <= num; i++) {
System.out.println(numbers[num]);
}
Your problem is here:
for (int i = 1; i <= num; i++)
Arrays in Java are 0-based. So the valid indices run from 0 to array.length - 1. So an array of length 5 would have the valid indices 0, 1, 2, 3, and 4. Change your loop to the following:
for (int i = 0; i < num; i++)
This will ensure that in your loop i will only have the values from 0 to 9.
your loop should only have the values from 0 to 9:
for (int i = 0; i < num; i++)
first of all i don't think you need a loop in the spanishnumber method...
cos you already know the index of what you are looking...// that's if i understand you
so the only place you need the loop is in the main method...so your code should look like dis
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
spanishNumbers(6);
}
}
public static void spanishNumbers(int num) {
String[] numbers = {"uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez"};
System.out.println(numbers[num -1]);
}
So the question is asking to create a method that will take an integer x as a parameter and print out all integers from 0->x that are multiples of three.
I can print out the number of times three divides x like so:
public int Threes(int x){
int i = 0;
for(int counter = 1; counter <= x; counter++){
if (counter % 3 ==0){
i ++;
}
}
return i;
but I'm not sure how to print out each multiple of 3!?
for(int counter = 1; counter <= x; counter++){
if (counter % 3 ==0){
System.out.println(counter);
}
}
An even quicker approach would be to increment by 3
public void Threes(int x) {
for (int counter = 3; counter <= x; counter = counter + 3) {
System.out.println(counter);
}
}
This loop will jump right to the multiples of 3, instead of counting every single number and having to do a modulo check for each iteration. Since we know that 1 and 2 are not multiples of 3, we just skip right to 3 at the beginning of the loop. If the input happens to be less than 3, then nothing will be printed. Also, the function should be void since you're printing instead of returning anything.
(Your title says 1 to n, but your question says 0 to n, so if you actually need from 0 to n, then change the declaration of counter to int counter = 0;)
Jason Aller wow that was so simple and elegant. This one builds on it by counting down from 300 to 3, by 3's.
public class byThrees {
public static void main(String[] args) {
for (int t = 100; t >= 0; t--) {
System.out.println(t*3);
Best practice using the For-loop in Java.
public class MultiplesOfThree {
public static void main(String []args){
for (int m = 1; m<=12; m++){
System.out.println(m*3);
}
}
}