How to get one result out of the for statement? - java

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

Related

How do I shorten my main method to where it still functions?

I have a java code to read the length of an integer array, output the range, length of the gap, and any distinct elements inside. Additionally, it will output the numbers again with none repeated.
I would like to shorten the length of my main method.
My code produces the correct output, it is just very lengthy. Additionally, is there a way I can edit this main method to where it won't require a drastic change to my other methods? Thank you so much!
package ArrayPrograms;
import java.util.Scanner;
public class WIP{
static int LargestGap(int [] a, int n)
{
int diff = Math.abs(a[1] - a[0]);
for(int i = 1; i < a.length-1; i++)
if(Math.abs(a[i+1]-a[i]) > diff)
diff = Math.abs(a[i+1] - a[i]);
return diff;
}
int range(int a[], int n)
{
int max1 = Integer.MIN_VALUE;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (Math.abs(a[i] - a[j]) > max1)
{
max1 = Math.abs(a[i] - a[j]);
}
}
}
return max1;
}
int numberOfDistinctElement(int a[], int n)
{
int num = 1;
for (int i = 1; i < n; i++)
{
int j = 0;
for (j = 0; j < i; j++)
if (a[i] == a[j])
break;
if (i == j)
num++;
}
return num;
}
int[] distinctElements(int a[], int n,int numberofDistinct)
{
int index = 0;
int[] distinct= new int[numberofDistinct];
for (int i = 0; i < n; i++)
{
int flag = 0;
for (int j = 0; j < i; j++){
if (a[i] == a[j]){
flag = 1;
break;
}
}
if (flag == 0){
distinct[index] = a[i];
index++;
}
}
return distinct;
}
***public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int num;
WIP obj=new WIP();
System.out.print("Enter the length of the array:");
num = in.nextInt();
int array[] = new int[num];
System.out.print("Enter the elements of the array: ");
for(int i = 0; i < num; i++)
{
array[i] = in.nextInt();
}
System.out.println("The largest gap in the array is "+WIP.LargestGap(array,num)+".");
System.out.println("The range of the array is "+obj.range(array,num)+".");
int numberofDistinct=obj.numberOfDistinctElement(array,num);
System.out.println("The number of distinct elements is "+numberofDistinct+".");
int[] distinctArray=obj.distinctElements(array,num,numberofDistinct);
System.out.print("The array of distinct elements is [");
for (int i = 0; i < distinctArray.length; i++)
if(i== distinctArray.length-1)
{
System.out.print(distinctArray[i]+"]");
}
else {
System.out.print( distinctArray[i]+ ",");
}
in.close();
}
}***
Sure thing. Here you go:
package arrayprograms;
import java.util.Scanner;
public class WIP{
static int LargestGap(int [] a, int n)
{
int diff = Math.abs(a[1] - a[0]);
for(int i = 1; i < a.length-1; i++)
if(Math.abs(a[i+1]-a[i]) > diff)
diff = Math.abs(a[i+1] - a[i]);
return diff;
}
int range(int a[], int n)
{
int max1 = Integer.MIN_VALUE;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (Math.abs(a[i] - a[j]) > max1)
{
max1 = Math.abs(a[i] - a[j]);
}
}
}
return max1;
}
int numberOfDistinctElement(int a[], int n)
{
int num = 1;
for (int i = 1; i < n; i++)
{
int j = 0;
for (j = 0; j < i; j++)
if (a[i] == a[j])
break;
if (i == j)
num++;
}
return num;
}
int[] distinctElements(int a[], int n,int numberofDistinct)
{
int index = 0;
int[] distinct= new int[numberofDistinct];
for (int i = 0; i < n; i++)
{
int flag = 0;
for (int j = 0; j < i; j++){
if (a[i] == a[j]){
flag = 1;
break;
}
}
if (flag == 0){
distinct[index] = a[i];
index++;
}
}
return distinct;
}
static void showResults(int[] array, int num, WIP obj){
System.out.println("The largest gap in the array is "+WIP.LargestGap(array,num)+".");
System.out.println("The range of the array is "+obj.range(array,num)+".");
int numberofDistinct=obj.numberOfDistinctElement(array,num);
System.out.println("The number of distinct elements is "+numberofDistinct+".");
int[] distinctArray=obj.distinctElements(array,num,numberofDistinct);
System.out.print("The array of distinct elements is [");
for (int i = 0; i < distinctArray.length; i++)
if(i== distinctArray.length-1)
{
System.out.print(distinctArray[i]+"]");
}
else {
System.out.print( distinctArray[i]+ ",");
}
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int num;
WIP obj=new WIP();
System.out.print("Enter the length of the array:");
num = in.nextInt();
int array[] = new int[num];
System.out.print("Enter the elements of the array: ");
for(int i = 0; i < num; i++)
{
array[i] = in.nextInt();
}
in.close();
showResults(array, num, obj );
}
}
There's not a whole lot you can do, like most of the comments say, but you can remove and edit some of the braces around that aren't necessary for the bodies. Here is a rough draft of it. The only things you could change besides that is to store all of the WIP.tests in variables in one code block and then print them all out in another code block; which would improve readability.
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
WIP obj = new WIP();
System.out.print("Enter the length of the array:");
int num = in.nextInt();
int array[] = new int[num] ;
System.out.print("Enter the elements of the array: ");
for(int i = 0; i < num; i++)
array[i] = in.nextInt();
System.out.println("The largest gap in the array is " + WIP.LargestGap(array,num) + ".");
System.out.println("The range of the array is " + obj.range(array,num) + ".");
int numberofDistinct = obj.numberOfDistinctElement( array, num );
System.out.println("The number of distinct elements is "+numberofDistinct+".");
int[] distinctArray = obj.distinctElements(array,num,numberofDistinct);
System.out.print("The array of distinct elements is [");
for (int i = 0; i < distinctArray.length; i++)
if(i== distinctArray.length-1)
System.out.print(distinctArray[i]+"]");
else
System.out.print( distinctArray[i]+ ",");
in.close();
}

How can I print a simple multiline numeric pattern opposite of how it is emitted now?

This is the output of the following code:
1
23
345
4567
But I want the output to be in the opposite direction like this.
Not sure how to achieve that.
1
23
345
4567
Code:
import java.util.Scanner;
public class numPattern1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int i = 1;
while (i <= n) {
int space = n - i + 1;
while (space <= n) {
System.out.print(" ");
space++;
}
int j = 1;
int p = i;
while (j <= i) {
System.out.print(p);
p++;
j++;
}
System.out.println();
i++;
}
}
}
For each line, there are two spaces times the length of the longest line minus the current line number. Then, you count from the current line number one plus the current line number values. Like,
int len = (n / 2) + 1;
for (int i = 0; i < len; i++) {
for (int j = 0; j < 2 * (len - i - 1); j++) {
System.out.print(' ');
}
for (int j = 0; j <= i; j++) {
System.out.print(j + i + 1);
}
System.out.println();
}
Outputs (as requested)
1
23
345
4567
Here it is:
public class numPattern1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int i = 1;
int k = 0;
while (i <= n) {
int space = 2*n - i - k ;
k++;
int l=0;
while (l <= space) {
System.out.print(" ");
l++;
}
int j = 1;
int p = i;
while (j <= i) {
System.out.print(p);
p++;
j++;
}
System.out.println();
i++;
}
}

How to print results of matched numbers with a space

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.

why do I get -1 when i try to delete an element in an array

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.

Trying to repeat this program if user says Y

I have tried the other questions like this but none seem to match it. I want it to repeat if the user enters Y after the numbers are sorted in the console.
Here is the code:
package compsorter;
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("In Ascending Order:");
for (int i = 0; i < n - 1; i++)
{
System.out.print(a[i] + ",");
}
System.out.print(a[n - 1]);
s.close();
}
}
Thanks!
Like this,
do{
//code here
//take input from user 'Y' or 'N'
}while(condition);
try do while for this reason.here is example of that : link
You can put
do { after
Scanner s = new Scanner(System.in);
and
} while(s.readLine().equals("Y"))
before
s.close();
You can do it with while loop.
Below is main method program you should have.
public static void main(String[] args) {
String flag = "Y";
Scanner s = new Scanner(System.in);
while (true) {
if ("Y".equalsIgnoreCase(flag)) {
int n, temp;
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("In Ascending Order:");
for (int i = 0; i < n - 1; i++) {
System.out.print(a[i] + ",");
}
System.out.print(a[n - 1]);
System.out.println();
System.out.print("Do you want to continue Y/N?");
flag = s.next();
} else {
break;
}
}
s.close();
}

Categories