How to print results of matched numbers with a space - java

Just thought of a simple program to practice java coding and am stuck at the end part.,..
the code prints out the required answer (what numbers match from input compared to results for a 5 number lottery) but the answer is printed without spaces. I thought perhaps to add a "" when += to matchingNumbers but that didnt do anything!
import java.util.Scanner;
import java.util.Arrays;
public class LottoChecker
{
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
int [] yourNumbers = new int [5];
int yourInput, resultsInput;
int [] results = new int [5];
int currentNumber = 0;
String matchingNumbers = "";
for (int i=0; i<yourNumbers.length; i++)
{
System.out.println ("Enter your main numbers: " );
yourInput = in.nextInt();
yourNumbers[i]=yourInput;
}
for (int j=0; j<results.length; j++)
{
System.out.println("Enter the results from the main numbers: ");
resultsInput = in.nextInt();
results[j] = resultsInput;
}
System.out.println("Your Numbers: " +
Arrays.toString(bubbleSort(yourNumbers)));
System.out.println("The Results are: " +
Arrays.toString(results));
for (int i =0; i<yourNumbers.length;i++)
{
currentNumber = yourNumbers[i];
for (int j=0;j<results.length;j++)
if (currentNumber == results[j])
matchingNumbers += currentNumber + "";
}
System.out.println("Your matching numbers are: " +
matchingNumbers);
}
public static int [] bubbleSort(int arr[])
{
int n = arr.length;
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
{
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
return arr;
}
}

An elegant solution would be using StringJoiner(" ") and then add the numbers on each iteration.

Related

How to get one result out of the for statement?

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

not able to sort array by ascending order

I have just started to do programming ...I am trying to sort an array in ascending order.. but not getting desired result , please point where i am doing wrong..
public static void main(String[] args) {
int count, temp;
// User inputs the array size
Scanner scan = new Scanner(System.in);
System.out.print("Enter number of elements you want in the array: ");
count = scan.nextInt();
int num[] = new int[count];
System.out.println("Enter array elements:");
for (int i = 0; i < count; i++) {
num[i] = scan.nextInt();
}
scan.close();
{
int i = 0;
while (i <= count) {
for (int j = i + 1; j < count; j++) {
if (num[i] > num[j]) {
temp = num[i];
num[i] = num[j];
num[j] = temp;
i++;
}
}
}
}
System.out.print("Array Elements in Ascending Order: ");
for (int i = 0; i < count - 1; i++) {
System.out.print(num[i] + ", ");
}
System.out.print(num[count - 1]);
}
you should increment the i outside the for loop or you can get rid of the while loop and use for loop too, you can find the code below :
import java.util.Scanner;
public class Ascending _Order
{
public static void main(String[] args)
{
int n, temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.print("Ascending Order:");
for (int i = 0; i < n - 1; i++)
{
System.out.print(a[i] + ",");
}
System.out.print(a[n - 1]);
}
}
Output:
Enter no. of elements you want in array:5
Enter all the elements: 4 3 2 6 1
Ascending Order:1,2,3,4,6
or you can use the method sort :
import java.util.Scanner;
import java.util.Arrays;
public class Ascending_Order {
public static void main(String[] args) {
int n, temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
}
Arrays.sort(a);
System.out.print("Ascending Order:");
for (int i = 0; i < n - 1; i++) {
System.out.print(a[i] + ",");
}
System.out.print(a[n - 1]);
}
}
Output:
Enter no. of elements you want in array:5
Enter all the elements: 4 3 2 6 1
Ascending Order:1,2,3,4,6

Sort random array in ascending order without arrays.sort

I am trying to sort an array of random numbers without using the arrays.sort. I have the code, but it doesn't work. not sure where is the error. Any kind of help is appreciated.
import java.util.*;
public class Sort
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("How many numbers do you want? ");
int howMany = in.nextInt();
int [] myArray = getRandomArray(howMany);
}
/* public static int bsearch(int[] arr, int key)
{
}*/
public static int[] getRandomArray(int howMany) {
int[] returnMe = new int[howMany]; // Assume size >= 0
Random rand = new Random();
for (int i = 0; i < howMany ; i++)
returnMe[i] = rand.nextInt(Integer.MAX_VALUE) + 1;
//System.out.print(returnMe[i] + " ");
for (int i = 1; i <= (howMany - 1); i++)
{
for (int j = 0; j < howMany - i -1; j++)
{
int tmp = 0;
if (returnMe[j] > returnMe[j+1])
{
tmp = returnMe[j];
returnMe[j] = returnMe[j + 1];
returnMe[j + 1] = tmp;
}
}
}
for ( int i = 0; i < howMany; i++)
System.out.println(returnMe[i] + " ");
return returnMe;
}
}
Your line
for (int j = 0; j < howMany - i -1; j++)
should be
for (int j = 0; j <= howMany - i -1; j++)
or alternatively, remove the "-1" and keep "<". Otherwise, you will ignore the last number in the array. Everything else looks fine to me.

program that reads in ten numbers and displays the number of distinct numbers and the distinct numbers separated by one space

I know that this question has been asked before, but not in the the format that I'm writing my code.. Just started taking java classes so I am not familiar with any complex java.. the code below consists of basically all the java I know. Please help! Thanks in advance.
import java.util.Scanner;
public class problem2try {
public static void main(String[] args) {
//declarations
Scanner keyboard = new Scanner (System.in);
int [] inputList = new int [10];
int [] distinctArray = new int [10];
int num;
int counter = 0;
//input
System.out.print("Please enter in 10 integers: ");
for (int i = 0; i < inputList.length; i++)
{
num = keyboard.nextInt();
inputList[i] = num;
}
//processing
distinctArray[0] = inputList[0];
for (int i = 1; i < inputList.length; i++)
{
for (int j = 0; j < inputList.length; j++)
{
if (inputList[i] == inputList[j])
{
counter++;
continue;
}
else
{
distinctArray[i] = inputList[i];
}
}
}
//output
System.out.println("The number of distinct numbers is " + counter);
System.out.print("The distict numbers are: ");
for (int x=0; x<distinctArray.length; x++)
{
if (distinctArray[x] != 0)
System.out.print(distinctArray[x] + " ");
}
}
}
Your logic in the "processing" block seemed off. I modified it to check the current number (outer loop) to all of the known numbers (inner loop). If no match was found, it is appended to the list of known numbers and the count is incremented.
I also modified the "output" code to print the first counter numbers from the list of known numbers. Values past that index are uninitialized.
import java.util.Scanner;
public class problem2try {
public static void main(String[] args) {
//declarations
Scanner keyboard = new Scanner (System.in);
int [] inputList = new int [10];
int [] distinctArray = new int [10];
int num;
int counter = 0;
//input
System.out.print("Please enter in 10 integers: ");
for (int i = 0; i < inputList.length; i++)
{
num = keyboard.nextInt();
inputList[i] = num;
}
//processing
for (int i = 0; i < inputList.length; i++)
{
boolean found = false;
for (int j = 0; j < counter; j++)
{
if (inputList[i] == distinctArray[j])
{
found = true;
break;
}
}
if (!found)
{
distinctArray[counter++] = inputList[i];
}
}
//output
System.out.println("The number of distinct numbers is " + counter);
System.out.print("The distict numbers are: ");
for (int x=0; x<counter; x++)
{
System.out.print(distinctArray[x] + " ");
}
}
}

Trying to swap array elements based on user input

So I have to swap two elements in an array with 5 values but the two to swap have to be taken from the keyboard. The previous question was to swap to specific ones and I got it done but I'm not sure how to get the numbers from the keyboard to be used in the swap. Some of this is left from the previous one where I knew the elements I had to swap.
import java.util.Scanner;
public class Swap2 {
public static void main(String []args) {
Scanner keyboardIn = new Scanner (System.in);
int[] numbers = new int []{12,9,33,28,5};
int temp = 0, first, second;
System.out.println ("Before the swap: ");
for(int i=0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
System.out.println();
System.out.println ("Enter the first number to swap:");
first = keyboardIn.nextInt();
System.out.println ("Enter the second number to swap:");
second = keyboardIn.nextInt();
System.out.println ();
temp = numbers[3];
numbers [3] = numbers [1];
numbers [1] = temp;
System.out.println ("After the swap:");
for (int i = 0; i < numbers.length; i++) {
System.out.print (numbers[i] + " ");
}
}
}
you have to define index...
import java.util.Scanner;
public class Swap {
public static void main(String[] args) {
Scanner keyboardIn = new Scanner(System.in);
/* enter code here */int[] numbers = new int[] { 12, 9, 33, 28, 5 };
int temp = 0, first, second;
int index1 = 0 , index2 = 0;
int j , k ;
System.out.println("Before the swap: ");
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
System.out.println();
System.out.println("Enter the first number to swap:");
first = keyboardIn.nextInt();
System.out.println("Enter the second number to swap:");
second = keyboardIn.nextInt();
System.out.println();
for(k = 0 ; k < numbers.length; k++){
if(numbers[k] == first)
index1 = k;
}
for(j = 0 ; j < numbers.length; j++){
if(numbers[j] == second)
index2 = j;
}
temp = numbers[index1];
numbers[index1] = numbers[index2];
numbers[index2] = temp;
System.out.println("After the swap:");
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
}
}
You're not actually swapping the numbers which user enters, you're always swapping 4th element with the 1st.
To swap the elements you need to find out the index where they belong.
public static int indexOf(int []arr, int ele)
{
for(int i = 0; i < arr.length; ++i)
if(arr[i] == ele)
return i;
return -1;
}
Now to swap those elements, call this function.
int first = sc.nextInt();
int firstIndex = indexOf(arr, first);
int second = sc.nextInt();
int secondIndex = indexOf(arr, second);
int temp;
temp = arr[firstIndex];
arr[firstIndex] = arr[secondIndex];
arr[secondIndex] = temp;
Why don't you try this. Please keep in mind that array indices start at 0.
import java.util.Scanner;
public class Swap2
{
public static void main(String []args)
{
Scanner keyboardIn = new Scanner (System.in);
int[] numbers = new int []{12,9,33,28,5};
int temp, first, second;
System.out.println ("Before the swap: ");
for(int i=0; i < numbers.length; i++)
{
System.out.print(numbers[i] + " ");
}
System.out.println ();
System.out.println ("Enter the first number to swap:");
first = keyboardIn.nextInt();
System.out.println ("Enter the second number to swap:");
second = keyboardIn.nextInt();
System.out.println ();
temp = numbers[first];
numbers [first] = numbers [second];
numbers [second] = temp;
System.out.println ("After the swap:");
for (int i = 0; i < numbers.length; i++)
{
System.out.print (numbers[i] + " ");
}
}
}

Categories