Writing a bubble sort algorithm in java for school and randomly getting an extra line printed to the screen, and I can't figure out why it is doing this. Here is my code.Code result here
import java.util.Scanner;
public class Assignment7 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter the # of numbers to be sorted: ");
int number = input.nextInt();
System.out.print("Enter 1 for ints or 2 for doubles: ");
int intdou = input.nextInt();
if (intdou == 1) {
int x = 0;
int[] num = new int[number];
for (int q = 0; q < number; q++) {
System.out.print("Enter number: ");
num[q] = input.nextInt();
}
for (int w = 0; w < number; w++) {
for (int e = 1; e < (number - w); e++) {
if (num[e - 1] > num[e]) {
x = num[e - 1];
num[e - 1] = num[e];
num[e] = x;
for (int r = 0; r < number; r++) {
System.out.print(num[r] + ", ");
}
}
System.out.print("\n");
}
}
} else if (intdou == 2) {
double x = 0;
double[] num = new double[number];
for (int q = 0; q < number; q++) {
System.out.print("Enter number: ");
num[q] = input.nextInt();
}
for (int w = 0; w < number; w++) {
for (int e = 1; e < (number - w); e++) {
if (num[e - 1] > num[e]) {
x = num[e - 1];
num[e - 1] = num[e];
num[e] = x;
for (int r = 0; r < number; r++) {
System.out.print(num[r] + ", ");
}
}
System.out.print("\n");
}
}
}
}
}
Do you mean the extra blank line? Just move "System.out.print("\n");" inside the if block.
Related
import java.util.*;
public class Combination {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
String input = sc.next();
System.out.printf("You entered: %d\n", Integer.parseInt(input));
sc.close();
int[] arr = new int[100];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
for (int i = 0; i <= 97; i++) {
int num_i = arr[i];
for (int j = i + 1; j <= 98; j++) {
int num_j = arr[j];
for (int k = j + 1; k <= 99; k++) {
int num_k = arr[k];
if (num_i + num_j + num_k == Integer.parseInt(input))
System.out.printf("(%d, %d, %d)", num_i, num_j, num_k);
}
}
}
}
}
When I get a number input, I want to make a code that represents this number as the sum of three numbers.
The code is complete, but there are several combinations. I want to print out only one combination. How can I edit it?
First, some important suggestions:
Do not parse input inside the nested loop as it will hit the performance. Do it once outside the nested loops.
Do not close Sacnner for System.in as it also closes System.in and there is no way to open it again without restarting JVM. It means that if it is being used in some other part of your application, your application will crash.
Always follow Java naming conventions e.g. you could name numJ instead of num_j.
Coming back to your problem, there are many ways to solve it and I have listed below just a couple of them:
Use break <<label>> to exit the nested loops:
import java.util.Scanner;
public class Combination {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
String input = sc.next();
System.out.printf("You entered: %d\n", Integer.parseInt(input));
int num = Integer.parseInt(input);
int[] arr = new int[100];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
start: for (int i = 0; i <= 97; i++) {
int numI = arr[i];
for (int j = i + 1; j <= 98; j++) {
int numJ = arr[j];
for (int k = j + 1; k <= 99; k++) {
int numK = arr[k];
if (numI + numJ + numK == num) {
System.out.printf("(%d, %d, %d)", numI, numJ, numK);
break start;
}
}
}
}
}
}
A sample run:
Enter a number : 123
You entered: 123
(1, 22, 100)
Put the logic in a method and return:
import java.util.Scanner;
public class Combination {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
String input = sc.next();
System.out.printf("You entered: %d\n", Integer.parseInt(input));
int num = Integer.parseInt(input);
printFirstCombination(num);
}
static void printFirstCombination(int num) {
int[] arr = new int[100];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
for (int i = 0; i <= 97; i++) {
int numI = arr[i];
for (int j = i + 1; j <= 98; j++) {
int numJ = arr[j];
for (int k = j + 1; k <= 99; k++) {
int numK = arr[k];
if (numI + numJ + numK == num) {
System.out.printf("(%d, %d, %d)", numI, numJ, numK);
return;
}
}
}
}
}
}
You can create a seperate function for that and after you find a combination, print it and return there and then to the main function. In case you didn't find a combination you return 1 which can be handled in the main function,
public class Combination {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
String input = sc.next();
System.out.printf("You entered: %d\n", Integer.parseInt(input));
int res = printCombination(input);
if(res == 1) {
// Do something
}
sc.close();
}
private static int printCombination(String input) {
int[] arr = new int[100];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
for (int i = 0; i <= 97; i++) {
int num_i = arr[i];
for (int j = i + 1; j <= 98; j++) {
int num_j = arr[j];
for (int k = j + 1; k <= 99; k++) {
int num_k = arr[k];
if (num_i + num_j + num_k == Integer.parseInt(input)) {
System.out.printf("(%d, %d, %d)", num_i, num_j, num_k);
return 0;
}
}
}
}
return 1;
}
}
I write a TicTacToe game.
Here I create a 3x3 table with char [][] board, then call method printBoard(). I input for example X_X_O____, and print this table with these characters.
In the changeBoard() method I want to input coordinates of board[][] and if there is char _ this will be replaced with X. I give the coordinates at compile to see that the coordinate is _ but when call method printBoard(), the console prints the same board without any changes. Can you please help me as I don't know what I am doing wrong?
import java.util.Scanner;
public class TicTacToe {
private char[][] board = new char[3][3];
private String state;
private int n;
private int m;
private int i;
private int j;
Scanner sc = new Scanner(System.in);
public TicTacToe() {
System.out.print("Enter cells: ");
this.state = sc.nextLine();
}
public void printBoard() {
int nextChar = 0;
System.out.println("---------");
for (i = 0; i < 3; i++) {
System.out.print("| ");
for (j = 0; j < 3; j++) {
board[i][j] = state.charAt(nextChar++);
System.out.print(board[i][j] + " ");
}
System.out.println("|");
}
System.out.println("---------");
}
public void changeBoard() {
while (true) {
System.out.print("Enter the coordinates: ");
n = sc.nextInt();
m = sc.nextInt();
if (n < 1 || n > 3 || m < 1 || m > 3) {
System.out.println("Coordinates should be from 1 to 3!");
} else {
int x = n - 1;
int y = m - 1;
this.i = x;
this.j = y;
if (board[i][j] == '_') {
this.board[i][j] = 'X';
break;
} else {
System.out.println("This cell is occupied! Choose another one!");
}
}
}
// printBoard();
}
}
Why you use fields for your n, m, i, j? If you remove it, code will be cleaner.
Also, you change your board in changeBoard, but then in line board[i][j] = state.charAt(nextChar++); you erase your changes. You can move this from printBoard to constructor.
I think want to write something like this
class TicTacToe {
private char[][] board = new char[3][3];
Scanner sc = new Scanner(System.in);
public TicTacToe() {
int nextChar = 0;
System.out.print("Enter cells: ");
String state = sc.nextLine();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = state.charAt(nextChar++);
}
}
}
public void printBoard() {
System.out.println("---------");
for (int i = 0; i < 3; i++) {
System.out.print("| ");
for (int j = 0; j < 3; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println("|");
}
System.out.println("---------");
}
public void changeBoard() {
while (true) {
System.out.print("Enter the coordinates: ");
int n = sc.nextInt();
int m = sc.nextInt();
if (n < 1 || n > 3 || m < 1 || m > 3) {
System.out.println("Coordinates should be from 1 to 3!");
} else {
int x = n - 1;
int y = m - 1;
if (board[x][y] == '_') {
this.board[x][y] = 'X';
break;
} else {
System.out.println("This cell is occupied! Choose another one!");
}
}
}
printBoard();
}
}
just wanting to know how do i set an input range for the scanner object, which then transfers the values and inputs them into a 2d array.
I was able to set a range for random number generator but i do not know how to apply the same concept to my scanner object
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random random = new Random();
int rows = 3;
int columns = 5;
System.out.println("Enter array elements : ");
int arry1[][] = new int[rows][columns];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns-2; j++)
{
arry1[i][j] = sc.nextInt();
}
}
arry1[0][3] = random.nextInt(50-10+1)+10;
arry1[1][3] = random.nextInt(50-10+1)+10;
arry1[2][3] = random.nextInt(50-10+1)+10;
int sum1 = 0;
int sum2 = 0;
int sum3 = 0;
sum1 = arry1[0][0]+arry1[0][1]+arry1[0][2]+arry1[0][3];
sum2 = arry1[1][0]+arry1[1][1]+arry1[1][2]+arry1[1][3];
sum3 = arry1[2][0]+arry1[2][1]+arry1[2][2]+arry1[2][3];
arry1[0][4] = sum1;
arry1[1][4] = sum2;
arry1[2][4] = sum3;
System.out.print("DISPLAYING ARRAY:");
System.out.println();
for (int[] x1 : arry1) {
for (int y1 : x1) {
System.out.print(y1 + " ");
}
System.out.println();
}
}
}
Add checking if the value is within range.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random random = new Random();
int rows = 3;
int columns = 5;
System.out.println("Enter array elements : ");
int arry1[][] = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns - 2; j++) {
int input;
do {
input = sc.nextInt();
} while (input < 0 || input > 3);
arry1[i][j] = input;
}
}
arry1[0][3] = random.nextInt(50 - 10 + 1) + 10;
arry1[1][3] = random.nextInt(50 - 10 + 1) + 10;
arry1[2][3] = random.nextInt(50 - 10 + 1) + 10;
int sum1 = 0;
int sum2 = 0;
int sum3 = 0;
sum1 = arry1[0][0] + arry1[0][1] + arry1[0][2] + arry1[0][3];
sum2 = arry1[1][0] + arry1[1][1] + arry1[1][2] + arry1[1][3];
sum3 = arry1[2][0] + arry1[2][1] + arry1[2][2] + arry1[2][3];
arry1[0][4] = sum1;
arry1[1][4] = sum2;
arry1[2][4] = sum3;
System.out.print("DISPLAYING ARRAY:");
System.out.println();
for (int[] x1 : arry1) {
for (int y1 : x1) {
System.out.print(y1 + " ");
}
System.out.println();
}
}
I checked out the questions that were already posted, but I still couldn't find a solution.
My output for the code is:
Enter the number of integers: 5
Enter 5 integers: 1
2
3
4
5
Enter the number to be deleted: 2
-1
package array;
import java.util.*;
//import java.util.ArrayLists;
public class DeleteFromArray {
public static void main(String[] args) {
int n = 0; // number of integers
int d = 0; // the number to be deleted
int count = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number of integers: ");
n = scan.nextInt();
if (n <= 0) {
System.out.println("Invalid input");
System.exit(-1);
}
int[] buffer = new int[n];
System.out.print("Enter " + n + " integers: ");
for (int k = 0; k < buffer.length; k++) {
buffer[k] = scan.nextInt();
}
System.out.print("Enter the number to be deleted: ");
d = scan.nextInt();
for (int i = 0; i < buffer.length; i++) {
if (buffer[i] == d) {
for (int j = 0; j < (buffer.length) - 1; j++) {
buffer[j] = buffer[j + 1];
}
count++;
break;
}
}
if(count ==0) {
System.out.println("Element not found!");
}
else {
System.out.print("Element Deleted Successfully..!!");
System.out.print("\nNow the New Array is :\n");
for (int i = 0; i < (buffer.length)-1; i++) {
System.out.println(buffer[i]+ " ");
}
}
scan.close();
}
}
Your for loop
for (int j = 0; j < (buffer.length) - 1; j++) {
buffer[j] = buffer[j + 1];
}
will not work properly because it will replace the value at 0 index with the value at index 1 and so on. What you want to do is just intialize the j=i where i is the index of d. and it will replace this value with the next.
for (int j = i; j < (buffer.length) - 1; j++) {
buffer[j] = buffer[j + 1];
}
Try this loop it will work.
In the blow code the inner 3rd while loop not working please tell me why ?
Here I tried with for loop by replacing the 3rd inner while loop it is working correctly but why not working with while loop .....? can you give me genuine reason...?
import java.util.Scanner;
public class MergeArray {
void arrayInitialization(Scanner arg) {
//entering test cases
System.out.println("enter test cases");
int t = arg.nextInt();
int k, l, i;
k = 0;
l = 0;
i = 0;
//outer while loop
while (t-- > 0) {
//initializing a1[]'s size
System.out.println("enter a1[]'s size");
int as1 = arg.nextInt();
int a1[] = new int[as1];
//inner while loop-1
while (as1-- > 0) {
System.out.println("enter a1[]'s elements");
a1[i] = arg.nextInt();
System.out.print(a1[i]);
i++;
}
i = 0;
//initializing a2[]'s size
System.out.println("enter a2[]'s size");
int as2 = arg.nextInt();
int a2[] = new int[as2];
//inner while loop-2
while (as2-- > 0) {
System.out.println("enter a2[]'s elements");
a2[i] = arg.nextInt();
System.out.print(a2[i]);
i++;
}
System.out.println();
int a3[] = new int[a1.length + a2.length];
int size = as1 + as2;
//inner while loop-3
while (size-- > 0) {
if (k < a1.length)
a3[l] = a1[k];
if (k < a2.length)
a3[l + 1] = a2[k];
k++;
l += 2;
}
for (int j = 0; j < (a1.length + a2.length); j++) {
System.out.print(a3[j]);
}
}
}
public static void main(String[] args) {
MergeArray ma = new MergeArray();
Scanner sc = new Scanner(System. in );
ma.arrayInitialization(sc);
}
}
I tried so much but not found solution. Here I am using while loop because I know that while loop will work fast instead of for loop.
It does not work because you are decrementing the sizes of as1 and as2. Which will be
int size = as1 + as2; // size = 0 + 0;
Instead you can make use of the array length e.g.
int size = as1.length + as2.length;
Murat K's Answer is right, but try to init the arrays like this:
//init a1
System.out.println("enter a1[]'s size");
int a1[] = new int[arg.nextInt()];
//fill a1
for (int i = 0; i < a1.length; i++) {
System.out.println("enter element " + i + " of a1[]");
a1[i] = arg.nextInt();
}
//init a2
System.out.println("enter a2[]'s size");
int a2[] = new int[arg.nextInt()];
//fill a2
for (int i = 0; i < a2.length; i++) {
System.out.println("enter element " + i + " of a2[]");
a2[i] = arg.nextInt();
}
//init a3
int a3[] = new int[a1.length + a2.length];
//merge a1 and a2 into a3
for (int i = 0; i < a1.length; i++) {
a3[i] = a1[i];
}
for (int i = 0; i < a2.length; i++) {
a3[a1.length + i] = a2[i];
}
//print
for (int i : a3) {
System.out.print(i);
}