Program ends after entering a string in Java - java

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);
}}
}
}

Related

Java Program to Insert Element in Array

private static int i;
public static void main(String[] args)
{
int n,num1,num3;
int arr[] = new int[50];
Scanner scan = new Scanner(System.in);
System.out.print("Enter number you want in array:");
n = scan.nextInt();
int a[] = new int[n];
System.out.println("Enter any number:");
for (int i = 0; i < n; i++)
{
a[i] = scan.nextInt();
}
for (int i = 0; i < n; i++)
{
for (int num = i + 1; num < n; num++)
{
if (a[i] > a[num])
{
num1 = a[i];
a[i] = a[num];
a[num] = num1;
}
}
}
System.out.print("Ascending Order:");
for (int i = 0; i < n - 1; i++)
{
System.out.print(a[i] + ",");
}
System.out.println(a[n-1]);
System.out.println("Enter Last number:" );
num1= scan.nextInt();
System.out.print("New Array Position: ");
for(i=0; i<n+1; i++)
{
System.out.print(arr[i] + " ");
}
}
}
Output:
Enter number you want in array:5
Enter any number: 5 2 3 1
Ascending Order: 1 2 3 5
Enter last number: 4
New Array Position: 0 0 0 0
it should be like this 1 2 3 4 5 can guys help me thanks
Couple of things:
1.While printing arr[i] in the last for loop, you have never touched array arr after declaration
i.e. int arr[] = new int[50]; Therefore, output 0 0 0 0 is as expected.
2.After reading the last number i.e. num1= scan.nextInt();, you have not used it anywhere moving forward. How do you think you array will come to know about the last element which is to be added ? :)
Something of this sort will work:
1.After sorting array a, copy it into array arr:
for(int i=0;i<n;i++){
arr[i] = a[i];
}
2.Once you have all the old elements in array arr, read last element in array arr i.e. arr[n+1] = scan.nextInt();
3.Here you can again sort the array arr to take last element to the appropriate place.
4.Print array arr:
for(int j=0;j<n+1;j++){
System.out.print(arr[j]+" ");
}
NOTE: Make sure your n is less than 50. Otherwise you will run into java.lang.ArrayIndexOutOfBoundsException
There are several problems in your code,
This answer based on the output given
1) you are going to specify a size of your array:
According to the output it is: 5
but actually you are going to get 4 numbers from the command line, so the first for loop should be only for the 4 elements (Assume that you are going to add last element again, so all elements count in array = 5)
for (int i = 0; i < n-1; i++)
{
a[i] = scan.nextInt();
}
2) Second for loop should be goes until 4 elements
for (int i = 0; i < n-1; i++)
{
for (int num = i + 1; num < n-1; num++)
{
if (a[i] > a[num])
{
num1 = a[i];
a[i] = a[num];
a[num] = num1;
}
}
}
3) Ascending order of the array contains only 4 elements, therefore it also goes until 4 elements
for (int i = 0; i < n-1 ; i++)
{
System.out.print(a[i] + ",");
}
4) You are going to get last element from the command line, it should assign to the array
a[n-1] = num1= scan.nextInt();
5)You have to again re arrange the array
for (int i = 0; i < n; i++)
{
for (int num = i + 1; num < n; num++)
{
if (a[i] > a[num])
{
num1 = a[i];
a[i] = a[num];
a[num] = num1;
}
}
}
6) Then you have to print the array :
for(i=0; i<n; i++)
{
System.out.print(a[i] + " ");
}
Full code:
public class MyClass {
private static int i;
public static void main(String[] args)
{
int n,num1,num3;
int arr[] = new int[50];
Scanner scan = new Scanner(System.in);
System.out.print("Enter number you want in array:");
n = scan.nextInt();
int a[] = new int[n];
System.out.println("Enter any number:");
for (int i = 0; i < n-1; i++)
{
a[i] = scan.nextInt();
}
for (int i = 0; i < n-1; i++)
{
for (int num = i + 1; num < n-1; num++)
{
if (a[i] > a[num])
{
num1 = a[i];
a[i] = a[num];
a[num] = num1;
}
}
}
System.out.print("Ascending Order:");
for (int i = 0; i < n-1 ; i++)
{
System.out.print(a[i] + ",");
}
System.out.println("");
System.out.println("Enter Last number:" );
a[n-1] = num1= scan.nextInt();
for (int i = 0; i < n; i++)
{
for (int num = i + 1; num < n; num++)
{
if (a[i] > a[num])
{
num1 = a[i];
a[i] = a[num];
a[num] = num1;
}
}
}
System.out.print("New Array Position: ");
for(i=0; i<n; i++)
{
System.out.print(a[i] + " ");
}
}
}
Output:
Enter number you want in array:5
Enter any number:
5
3
2
1
Ascending Order:1,2,3,5,
Enter Last number:
4
New Array Position: 1 2 3 4 5

initialize only some elements of array in java

So I want to skip the first and last elements of the array to initialize. What am I doing wrong?
public static void main(String args[]) throws Exception {
//Write code here
Scanner sc = new Scanner(System.in);
System.out.println("Input Rows: ");
int m = sc.nextInt();
System.out.println("Input Columns: ");
int n = sc.nextInt();
System.out.println("Enter values: ");
int[][] arr = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (arr[i][j] == arr[0][0] || arr[i][j] == arr[m][n]) {
continue;
} else {
arr[i][j] = sc.nextInt();
}
}
System.out.println();
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
Here is my output:
Input Rows:
3
Input Columns:
3
Entered Values:
0 0 0
0 0 0
0 0 0
You need to change the if condition inside the loop like following:
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if ((i == 0 && j==0) || (i == m -1 && j == n -1)) {
continue;
} else {
arr[i][j] = sc.nextInt();
}
}
System.out.println();
}
In this line:
if (arr[i][j] == arr[0][0] || arr[i][j] == arr[m][n]) {
You are testing for the equality of values within your array. You should be comparing whether the indices you are looking at are the beginning or end of the array.
That is to say, you want to compare whether (in pseudo code):
i==0 and j==0, OR i==max index in its dimension and j==max index in its dimension
I have deliberately omitted the literal answer, because this looks a tiny bit like homework.
You compare the value of arr[i][j] with the value of arr[0][0]. You should instead compare i==0 && j==0 || i==m -1 && j==n -1
As your array was empty, and as you start the loop, arr[i][j] was equal to arr[0][0], skipping the first element. but for the next loop, arr[i][j] was still empty, and as you compare it to a non-initialised value, it's always true, skipping in each step
public static void main(String args[]) throws Exception {
//Write code here
Scanner sc = new Scanner(System.in);
System.out.println("Input Rows: ");
int m = sc.nextInt();
System.out.println("Input Coloumns: ");
int n = sc.nextInt();
System.out.println("Enter values: ");
int[][] arr = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i==0 && j==0 || i==m-1 && j==n-1) {
continue;
} else {
arr[i][j] = sc.nextInt();
}
}
System.out.println();
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
You don't need to check whether the array items are equal, you just want to check whether the row and column are equal to the last and first.

2D Array: Magic Square

The question I am working on is:
A square with the side length n is filled with numbers 1,2,3,...n2 is a magic square if the sum of elements in each row, column, and two diagonals is the same value.
Write a program that reads in a value of 16 values from the keyboard and tests whether they form a magic square when put into a 4 x 4 array. You need to test the following 2 features:
Does each number of 1,2,...16 occur in user input? Tell the user to try again if they enter a number that they've already entered.
When the numbers are put into a square, are the sums of rows, columns, and diagonals equal to each other?
It must be done using two-dimensional array
I am having trouble with asking the user to try again if they enter a number that they have previously entered. And, numbers in 4 x 4 do not print.
What am I doing wrong? How can I fix it?
This is the code I have so far:
Scanner in = new Scanner (System.in);
int n =4;
int[][] square = new int[n][n];
int number = 0;
int num = 0;
for (int i = 0; i <16; i++){
number = num;
System.out.print ("Enter a number: ");
num = in.nextInt();
int num_2 = 0;
if (number==num || number==num_2) {
System.out.println ("Try again.");
System.out.println ("Enter a number: ");
num_2 = in.nextInt();
}
if (num > 16){
System.out.println ("Try again.");
break;
}
}
for (int i= 0; i < n; i++){
for (int j = 0; j < n; j++) {
num+=square [i][j];
System.out.print(square[i][j] + "\t");
}
}
}
}
You can try this code for 1st feature and add code for 2nd one.
int ar[][] = new int[4][4];
System.out.println("Enter Numbers");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
boolean flag = false;
int num = sc.nextInt();
if (num > 16 || num < 1) {
System.out.println("Please Enter number between 1 to 16");
flag=true;
j--;
} else {
for (int k = 0; k <= i; k++) {
for (int l = 0; l <= j; l++) {
if (ar[k][l] == num) {
System.out.println("This number already inserted...Please give another");
j--;
flag = true;
}
}
}
}
if (!flag) {
ar[i][j] = num;
}
}
}
If you can't understand anything please ask.
Hope this help.

Loop not giving me desired matrix output

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();
}

How to make Bubble Sort in Java to output the sorted numbers?

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;
}
}
}

Categories

Resources