I am trying to display an array of numbers in a square matrix that increases by 1 in a snake pattern. Cant get right output. User inputs row/columns and matrix is displayed. Look at photo below. I have also attempted if statements for even/odd rows with modulo but still getting same output. (Bear with me, I am new to this, sorry about format or if I'm missing information)
http://imgur.com/a/ZDhFw
import java.util.Scanner;
public class A3_Q2 {
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
System.out.println("[-------------------------]");
System.out.println("[ Array Pattern ]");
System.out.println("[-------------------------]");
System.out.println("How many rows/columns do you want your array to have? (Mist be at least 3):");
int arraySize = keyboard.nextInt();
while(arraySize < 3)
{
System.out.println("Lets try this again ....");
System.out.println("How many rows/columns do you want your array to have? (Mist be at least 3):");
arraySize = keyboard.nextInt();
}
int [][] pattern = new int[arraySize][arraySize];
int i = 0;
int number = 1;
while (i < arraySize)
{
for (int j = 0; j < arraySize; ++j)
{
pattern[i][j] = number;
System.out.printf("%3d", pattern[i][j]);
number++;
}
System.out.println("");
++i;
for (int j = arraySize-1; j >= 0; --j)
{
pattern[i][j] = number;
System.out.printf("%3d", pattern[i][j]);
number++;
}
System.out.println("");
++i;
}
}
}
I've changed your code so that it works. As you already mentioned, you can use the modulo operator here.
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("[-------------------------]");
System.out.println("[ Array Pattern ]");
System.out.println("[-------------------------]");
System.out.println("How many rows/columns do you want your array to have? (Mist be at least 3):");
int arraySize = keyboard.nextInt();
while(arraySize < 3)
{
System.out.println("Lets try this again ....");
System.out.println("How many rows/columns do you want your array to have? (Mist be at least 3):");
arraySize = keyboard.nextInt();
}
int [][] pattern = new int[arraySize][arraySize];
int number = 1;
for(int i=0;i<arraySize;i++){
if(i%2==0){
for(int j=0;j<arraySize;j++){
pattern[i][j]=number;
number++;
}
}
else{
for(int j=arraySize-1;j>=0;j--){
pattern[i][j]=number;
number++;
}
}
for(int j=0;j<arraySize;j++){
System.out.printf("%3d", pattern[i][j]);
}
System.out.println();
}
}
EDIT: Tested this in IDE to make sure it works.
You first need to have have an initial value for pattern[i][j].
for (int i = 0; i < arraySize; i++) {
for (int j = 0; j < arraySize; j++) {
pattern[i][j] = arraySize*i + j + 1;
}
}
You need to then have a condition that will print out the numbers in ascending order when i is even, and descending when i is odd.
for (int i = 0; i < arraySize; i++) {
if (i % 2 == 0) {
for (int j = 0; j < arraySize; j++) {
System.out.printf("%3d", pattern[i][j]);
}
} else {
for (int j = arraySize - 1; j >= 0; j--) {
System.out.printf("%3d", pattern[i][j]);
}
}
System.out.println();
}
Related
I've been looking for different solutions out here but on my code they won't work. I'm getting an input from a user but then it doesn't display what's inside the if-else statement. I tried to do a different code for the if statement but it doesn't work. The int input works but it doesn't work in the string input.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int numbers [] = new int[10];
int temp;
String sc = " ";
Scanner scan = new Scanner(System.in);
// Loop through array
// Change value of each array per iteration
System.out.print("Enter 10 integers: ");
for(int i = 0; i < numbers.length; i++){
numbers[i] = scan.nextInt();
}
System.out.print("\nPlease Choose Among The Following:");
System.out.println("\n A - Display the numbers \t B - Display the values of even indexes \n C - Display the values of odd indexes \t D - Display the values in ascending order \n E - Display the values in descending order");
System.out.print("\nEnter The Letter of Your Choice: ");
sc = scan.nextLine();
if (sc.equals('A') || sc.equals('a')){
System.out.print("Display each item in array");
for(int number: numbers){
System.out.println(number);
}}
else if (sc.equals('B') || sc.equals('b')){
System.out.println("Display odd indexes");
for(int i = 0; i < numbers.length; i++){
if(i % 2 == 0){
System.out.println(numbers[i]);
}
}}
else if (sc.equals('C') || sc.equals('c')){
System.out.println("Display even indexes");
for(int i = 0; i < numbers.length; i++){
if(i % 2 == 1){
System.out.println(numbers[i]);
}
}}
else if (sc.equals('D') || sc.equals('d')){
int [] ascendingList = numbers.clone();
System.out.println("Display in ascending order using bubble sort");
for(int i = 0; i < ascendingList.length - 1 ; i++){
for(int j = 0; j < (ascendingList.length - i - 1); j++){
if(ascendingList[j] > ascendingList[j+1]){
temp = ascendingList[j];
ascendingList[j] = ascendingList[j+1];
ascendingList[j+1] = temp;
}
}
}
for(int number: ascendingList){
System.out.println(number);
}}
else if (sc.equals('E') || sc.equals('e')){
int [] descendingList = numbers.clone();
System.out.println("Display in descending order using bubble sort");
for(int i = 0; i < descendingList.length - 1 ; i++){
for(int j = 0; j < (descendingList.length - i - 1); j++){
if(descendingList[j] < descendingList[j+1]){
temp = descendingList[j];
descendingList[j] = descendingList[j+1];
descendingList[j+1] = temp;
}
}
}
for(int number: descendingList){
System.out.println(number);
}}
}
}
I have written a program in ArrayList to find the sorted array. But I have to find the sum of the numbers entered as well.
I couldn't succeed in getting the results as it is in the array list
import java.util.ArrayList;
import java.util.Scanner;
public class project1 {
public static void main(String[] args) {
int add = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter 5 numbers: ");
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < 5; i++) list.add(input.nextInt());
System.out.println("add" +add);
System.out.println("Sorting numbers...");
sort(list);
System.out.println("Displaying numbers...");
System.out.println(list);
}
public static void sort(ArrayList<Integer> list) {
for (int i = 0; i < list.size() - 1; i++) {
int currentMin = list.get(i);
int currentIndex = i;
for (int j = i + 1; j < list.size(); j++) {
if (currentMin > list.get(j)) {
currentMin = list.get(j);
currentIndex = j;
}
}
if (currentIndex != i) {
list.set(currentIndex, list.get(i));
list.set(i, currentMin);
}
}
}
}
I am looking to get the sum of the entered numbers along with sorting. Any help will be very appreciated.
change this
for (int i = 0; i < 5; i++) list.add(input.nextInt());
to this
int sum = 0;
for (int i = 0; i < 5; i++){
int num = input.nextInt();
list.add(num);
sum += num;
}
the value of the sum is saved inside sum and you can do what ever you want with it.
I am using the For loop to add the values the user entered to a var name sum that is located out side of the for loop and when the for loop is done you have the sum
You could just write sum += currentMin at the bottom of the for (int i; ... loop. This way you count every number exactly once, after it is put in its final place.
ArrayList<Integer> list = new ArrayList<>();
int sum = 0
for (int i = 0; i < 5; i++) {
int in = input.nextInt();
sum = sum + in;
list.add(in);
}
I am getting user input for function (smallest or largest) and for populating array. Then according to the input function i want to compare consecutive elements and find the smallest or largest number. I cannot understand why and how to fix my code.
The code runs but does not work as supposed to. The smallest and largest numbers are all wrong
import java.util.Scanner;
public class App {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Are you trying to find the Smallest or Largest number in an array of numbers? S/L");
String functionExpected = sc.nextLine();
System.out.println("How many elements you plan to enter? ");
int lengthOfArray = sc.nextInt();
// Populating array according to input and length
int[] numbersArray = new int[lengthOfArray];
for (int i = 0; i < numbersArray.length; i++) {
System.out.println("Enter an element here: ");
numbersArray[i] = sc.nextInt();
}
// Print out array
for (int i = 0; i < numbersArray.length; i++) {
System.out.print(numbersArray[i] + " ");
}
System.out.println();
if (functionExpected.equalsIgnoreCase("L")) {
int temp = 0;
System.out.println("We are going to find the largest number in the array of elements you enter!");
for (int i = 0; i < numbersArray.length; i++) {
for (int j = 1; j < numbersArray.length;) {
if (numbersArray[i] > numbersArray[j]) {
temp = numbersArray[i];
break;
} else {
temp = numbersArray[j];
break;
}
}
}
System.out.println("Largest of the three numbers is : " + temp);
}
if (functionExpected.equalsIgnoreCase("S")) {
int temp = 0;
System.out.println("We are going to find the smallest number in the array of elements you enter!");
for (int i = 0; i < numbersArray.length; i++) {
for (int j = 1; j < numbersArray.length;) {
if (numbersArray[i] > numbersArray[j]) {
temp = numbersArray[j];
break;
} else {
temp = numbersArray[i];
break;
}
}
}
System.out.println("Smallest of the three numbers is : " + temp);
}
}
}
As pointed out by the comments the inner loops (j based) are completely unnecessary.
int temp = numbersArray[0];
for (int i = 1; i < numbersArray.length; i++) {
if(numbersArray[i] > temp) {
temp = numbersArray[i]
}
}
Just switch the > to < in the if for smallest/largest.
How to make square matrix appear in a "snake" pattern? User inputs # of rows/columns in array and then matrix is displayed in ascending order but in a snake pattern.
1 2 3 4
8 7 6 5
9 10 11 12
16 15 14 13
import java.util.Scanner;
public class A3_Q2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
System.out.println("[-------------------------]");
System.out.println("[ Array Pattern ]");
System.out.println("[-------------------------]");
System.out.println("How many rows/columns do you want your array to have? (Mist be at least 3):");
int arraySize = keyboard.nextInt();
while(arraySize < 3)
{
System.out.println("Lets try this again ....");
System.out.println("How many rows/columns do you want your array to have? (Mist be at least 3):");
arraySize = keyboard.nextInt();
}
int [][] pattern = new int[arraySize][arraySize];
int number = 1;
for (int i = 0; i <= arraySize -1; i++){
for(int j = 0; j <= arraySize - 1; j++)
{
pattern[i][j] = number;
number++;
System.out.printf("%3d", pattern[i][j]);
}
System.out.println("");
}
}
}
If we wanted to just print the 2D array in ascending order from left to right on each row, we could just use the following for loop:
for (int i=0; i < arraySize; ++i) {
for (int j=0; j < arraySize; ++j) {
System.out.printf("%3d", pattern[i][j]);
}
}
To get the reverse order effect you want, we only need to add logic such that for odd rows, we print a row backwards, from left to right:
for (int i=0; i < arraySize; ++i) {
if (i%2 == 0) {
// for even rows, print as we normally would
for (int j=0; j < arraySize; ++j) {
System.out.printf("%3d", pattern[i][j]);
}
}
else {
// for odd rows, iterate backwards over the array, the print left to right
for (int j=arraySize-1; j >= 0; --j) {
System.out.printf("%3d", pattern[i][j]);
}
}
System.out.println();
}
Update:
You can initialize your array using something like the following:
int arraySize = 4;
for (int i=0; i < arraySize; ++i) {
for (int j=0; j < arraySize; ++j) {
pattern[i][j] = i*arraySize + j + 1;
}
}
This is my code for the Bubble Sort. I cannot get the actual sorted values to output. The program reads the inputted numbers, but does not print it sorted.
I'm not sure what I have to do to make them sort.
Any advice or suggestions would be helpful.
package sortingalgorithm2;
import java.util.Scanner;
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Scanner read = new Scanner (System.in);
int[] num = new int[15];
int size = 15;
System.out.println("Enter 15 numbers: ");
for (int i=0; i <= size-1; i++)
{
num[i] = read.nextInt();
}
for (int i=0; i <= size-1; i++)
{
if (num[i] >=1 && num[i] <= 1000)
{
System.out.println("The numbers you entered are: ");
System.out.println(+num[0]);
System.out.println(+num[1]);
System.out.println(+num[2]);
System.out.println(+num[3]);
System.out.println(+num[4]);
System.out.println(+num[5]);
System.out.println(+num[6]);
System.out.println(+num[7]);
System.out.println(+num[8]);
System.out.println(+num[9]);
System.out.println(+num[10]);
System.out.println(+num[11]);
System.out.println(+num[12]);
System.out.println(+num[13]);
System.out.println(+num[14]);
}
else
{
System.out.println("Data input is invalid. Enter a number between "
+
"1 and 1000.");
break;
}
}
BubbleSort (num);
for (int i=0; i < num.length; i++)
{
System.out.println("The sorted numbers are: ");
System.out.print(num[i]+ " ");
}
}
private static void BubbleSort(int[] num)
{
for (int i=0; i <= num.length; i++)
for (int x=1; x <= num.length; x++)
if (num[x] > num[x+1])
{
int temp = num[x];
num[x] = num[x+1];
num[x+1] = temp;
}
}
}
Try this Bubble sort :
private static void BubbleSort(int[] num) {
for (int i = 0; i < num.length; i++) {
for (int x = 1; x < num.length - i; x++) {
if (num[x - 1] > num[x]) {
int temp = num[x - 1];
num[x - 1] = num[x];
num[x] = temp;
}
}
}
}
You are printing the actual numbers in the order the user entered. Try this instead:
int[] sortedNumbers = new int[15];
sortedNumbers = BubbleSort (num);
for (int i=0; i < sortedNumbers.length; i++)
{
System.out.println("The sorted numbers are: ");
System.out.print(sortedNumbers[i]+ " ");
}
public static int[] BubbleSort(int [] num)
{
int temp;
for (int i=1; i<num.length; i++)
{
for(int j=0; j<num.length-i; j++)
{
if (num[j] > num [j+1])
{
temp = num [j];
num [j] = num [j+1];
num [j+1] = temp;
}
}
}
return num;
}
Try this :
for (int i = 0; i < num.length; i++) {
for (int j = i + 1; j < num.length; j++) {
if (num[i] > num[j]) {
num[i] = num[i] + num[j] - (num[j] = num[i]);
}
}
}
you are passing the array variable num (which is not static) to BubbleSort()(which does not returns a value and shadows the global num variable with its own) and trying to use the same num variable to access your sorted array from your main method which is not right.
The genuine fix to this is to declare your variable num as static just before the main method( in the class declaration). So I have made the changes in the program and here is the solution.
import java.util.Scanner;
public class sol {
static int num [] =new int [15]; //declaring num as static in the class definition.
public static void main(String[] args)
{
Scanner read = new Scanner (System.in);
int size = 15;
System.out.println("Enter 15 numbers: ");
for (int i=0; i <= size-1; i++)
{
num[i] = read.nextInt();
}
read.close();
/*for (int i=0; i <= size-1; i++)
{
if (num[i] >=1 && num[i] <= 1000)
{
System.out.println("The numbers you entered are: ");
System.out.println(+num[0]);
System.out.println(+num[1]);
System.out.println(+num[2]);
System.out.println(+num[3]);
System.out.println(+num[4]);
System.out.println(+num[5]);
System.out.println(+num[6]);
System.out.println(+num[7]);
System.out.println(+num[8]);
System.out.println(+num[9]);
System.out.println(+num[10]);
System.out.println(+num[11]);
System.out.println(+num[12]);
System.out.println(+num[13]);
System.out.println(+num[14]);
}
else
{
System.out.println("Data input is invalid. Enter a number between "
+
"1 and 1000.");
break;
}
}*/ //I have disabled this just to check with the sort method.
BubbleSort ();//no need to pass the array as it is static and declared as a //class variable hence can be used to by all the methods of that class
System.out.println("The sorted numbers are: ");
for (int i=0; i < num.length; i++)
{
System.out.print(num[i]+ " ");
}
}
private static void BubbleSort()
{
for (int i=0; i < num.length; i++)// required changes in the looping
for (int x=0; x < num.length-i-1; x++)
if (num[x] > num[x+1])
{
int temp = num[x];
num[x] = num[x+1];
num[x+1] = temp;
}
}
}