How to loop block of code in Java programming - java

I am writing code to display an array of numbers in ascending order. I have completed the first part which is the actual commands to get the array. The second part is that I have to make the program initialize after it has arranged an array of numbers. Here is my code.
package ascendingorder;
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]);
}
}
When the code is compiled and executed, the program prompts the user to enter the array size and on entering it, the program then asks the user to enter the elements of the array. After that, the user presses enter and the program displays the result in ascending order.
After that the program is supposed to loop back and prompt the user to enter arrays size, followed by elements and so on. Also, the program is supposed to terminate when the user enters a value like 'n' or 'x'. Kindly help me with this part as I don't have any idea or how to place the for loop in order to loop the block of code from 'System.out.print("Enter no. of elements you want in array:");'. Thank you.

May be the below link can be helpful
[java program to loop back to start
boolean isRunning = true;
String tryAgain = "";
while (isRunning) {
// All your code you have in your example.
// Ask user if he wants to retry with a scanner.
tryAgain = <use scanner here>;
if (tryAgain.equals("no") || tryAgain.equals("No") ) isRunning = false;
}
Or
String tryAgain = "";
while (true) {
// All your code you have in your example.
// Ask user if he wants to retry with a scanner.
tryAgain = <use scanner here>;
if (tryAgain.equals("no") || tryAgain.equals("No") ) break;
}

First you have the program taking nextInt so if you entered the chars it would create an exception, you should instead use nextLine and then check/parse it.
As for the loop, a simple while loop would work, and don't forget to close the scanner at the end.
public static void main(String[] args) {
String in;
int temp, n;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
in = s.nextLine();
while (!in.equals("x") || !in.equals("n")) {
n = Integer.parseInt(in);
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]);
in = s.nextLine();
}
s.close();
}

Related

How could I add a binary search method using user input in a sorted array

This is a expense sorter which I need to make for my class. I need a binary search method but don't know where to start. I know that binary searching works from the middle of a sorted array but the explanations from websites such as Wikipedia are very confusing.
The code consists of two sorting methods. Linear and selection sort. I have a user input in the variable size which tells the program about the size of the array.Can someone give me an example and explain it in the code using comments.
I want a user to give an input which will be the number that they are looking for. If the number is 57 then the array will scan the middle of the array and determine the number. lets say that number is 56. 56 is less than 57 so it will count upwards from that point until it finds that number
package project;
import java.io.*;
import java.util.*;
import java.util.Scanner;
public class project {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int Size;
int order;
System.out.println("Put in the amount of expenses you have");
Size = sc.nextInt();
System.out.println("put in all your expenses");
int userInput[] = new int[Size];
for (int i = 0; i < userInput.length; i++)
userInput[i] = sc.nextInt();
System.out.println(
"do you want it ascending or descending order. If you want it in ascending press 1 or if you want descending press 2");
order = sc.nextInt();
System.out.print("expenses not sorted : ");
printExpenses(userInput);
if (order == 1) {
expensesAscending(userInput);
} else if (order == 2) {
expensedescending(userInput);
}
}
public static void printExpenses(int[] arr) {
// this is were it is printed
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i] + "$");
}
}
public static void expensedescending(int arr[]) {
// This is were the selection sort starts
int N = arr.length;
for (int i = 0; i < N; i++) {
int small = arr[i];
int pos = i;
for (int j = i + 1; j < N; j++) {
if (arr[j] > small) {
small = arr[j];
pos = j;
}
}
int temp = arr[pos];
arr[pos] = arr[i];
arr[i] = temp;
System.out.println(": ");
// Printing array after pass
printExpenses(arr);
}
}
public static void expensesAscending(int arr[]) {
int N = arr.length;
for (int i = 1; i < N; i++) {
int j = i - 1;
int temp = arr[i];
while (j >= 0 && temp < arr[j]) {
arr[j + 1] = arr[j];
j--;
;
}
arr[j + 1] = temp;
System.out.println(": ");
// Printing array after pass
printExpenses(arr);
}
}
}

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

Program stops after while loop

I am writing a small program that reads the input and sets an array size, fills in the array and adds the numbers. My problem is that while I don't get any errors the program stops after the while. Any pointers as to what I am doing wrong would be very appreciated.
public class test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] numbers = new int[in.nextInt()];
int sum = 0;
System.out.println("\n" + "numbers: " + numbers.length);
while (in.hasNextLine()) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = in.nextInt();
// System.out.println(numbers[i]);
}
}
for (int i = 0; i <= numbers.length; i++) {
sum += numbers[i];
}
System.out.println(sum);
}
}
As the JavaDoc for Scanner.hashNextLine() states:
Returns true if there is another line in the input of this scanner.
This method may block while waiting for input. The scanner does not
advance past any input.
So your while loop will never finish:
while (in.hasNextLine())
Just remove this loop, your for loop inside is already doing the right job.
PS: And as jipr311 stated fix your second for loop or you will face an ArrayIndexOutOfBoundsException:
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
the while loop is not needed
for (int i = 0; i < numbers.length; i++) {
if(in.hasNextInt())
numbers[i] = in.nextInt();
// System.out.println(numbers[i]);
}
There is no use of while loop. Remove that.
And edit the for loop like
for (int i = 0; i < numbers.length; i++)
This should work:
public static void main(String[] args) {
Scanner in = null;
try{
in = new Scanner(System.in);
int[] numbers = new int[in.nextInt()];
int sum = 0;
System.out.println("\n" + "numbers: " + numbers.length);
int count = 0;
while (count < numbers.length) {
numbers[count] = in.nextInt();
count++;
}
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
System.out.println(sum);
}finally{
if(null != in){
in.close();
}
}
}
There also was a resource leak in the program as scanner object was not closed. I have corrected it.

Trying to Identify the non repeating values from the console and print the non-repeating values to output

I am trying to print the non repeated values when user enter some numbers it should display the numbers which are not duplicate. i am getting all the values and my program is as below
public class Compare {
public static void main(String[] args){
Scanner sc= new Scanner(System.in);
System.out.println("enter the string:");
int[] array = new int[7];
for (int i=0; i<array.length;i++) {
array[i] = Integer.parseInt(sc.nextLine());
}
for (int i = 0; i < array.length; i++) {
boolean found = false;
for (int j = i+1; j < array.length; j++)
if (array[i] == array[j]) {
found = true;
break;
}
if(!found)
System.out.println(array[i]);
}
}
}
Instead of boolean found, take a int count=0 for counting the numbers and print the numbers which have count == 1
Change the code accordingly as shown
for (int i = 0; i < array.length; i++) {
int count=0;
for (int j = 0; j < array.length; j++)
if (array[i] == array[j]) {
count++;
}
if(count==1)
System.out.println(array[i]);
}
Input:
1
2
2
3
3
4
5
Output:
1
4
5
You only have to change two things:
Check the whole array for duplicates. int j = 0 instead of int j = i
Don't compare the the value with itself. Add && i != j to your if condition.
Now your code will work.
Input: 1,2,3,3,4,5,6
Output: 1,2,4,5,6
How about using, HashSet?
It will only contain non duplicate values.
You could do this quicker with a map counting the number of values:
public class Compare {
public static void main(String[] args){
Scanner sc= new Scanner(System.in);
System.out.println("enter the string:");
Map<int, int> values = new HashMap<int, int>();
for (int i=0; i<7;i++) {
value = Integer.parseInt(sc.nextLine());
if (!values.contains(value)) {
values.put(value, 1);
} else {
values.put(value, values.get(value) + 1);
}
}
for (int value : values.keySet()) {
if (values.get(value) == 1) {
System.out.println(value);
}
}
}
}

Limiting my output with an array

My question has to do with counting integers in an array. This is my code so far.
import java.util.Scanner;
public class Frequency {
public static void main(String[]args) {
Scanner kbd = new Scanner(System.in);
System.out.print("enter numbers: ");
int[] arr = new int[51];
for(int i = 0; true; i++) {
int in = kbd.nextInt();
if(in < 0)break;
else if(in > 50)break;
else arr[in]++;
}
for(int i = 0; i < arr.length; i++) {
System.out.println(i+" occurrences of "+arr[i]);
}
}
}
The way the problem outputs is correct except I need some way of filtering out all the numbers that have an occurrence of 0 so that only numbers that were in the input show in the output; instead of every number between 0 and 50.
You have already written an if statement, to stop your first loop when user enters a negative number. Simply write the same thing for your second loop:
for(int i = 0; i < arr.length; i++) {
if (arr[i] > 0) {
System.out.println(arr[i]+" occurrences of "+i);
}
}
Side-note: I have also swapped arr[i] and i
for(int i = 0; i < arr.length; i++) {
if(!(i==0 || i%10==0) && arr[i]!=0)
System.out.println(i+" occurrences of "+arr[i]);
}

Categories