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]);
}
Related
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();
}
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.
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);
}
}
}
}
import java.util.Scanner;
public class diamond {
public static void main (String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter an integer");
int lines = scan.nextInt();
for(int counter = 1; counter <= lines; counter++)
{
if (counter%2 != 0)
{
for(int count2 = 1; count2 <= counter; count2++){
System.out.print("*");
}
System.out.println();
}
}
}
}
I am supposed to ask the user for a number of lines and output a diamond made of asterisks that number of lines tall. I need some help figuring out how to center the asterisks. I know for strings there is some String.utils method or something, but the output comes in pieces based on a for loop, so I don't think that really works here. If it does, by all means let me know though.
You need to print a certain amount of spaces before each line. Then, you would need another for loop for the opposite.
Try this code:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter an integer ");
int lines = scan.nextInt();
for (int counter = 1; counter <= lines; counter++) {
if (counter % 2 != 0) {
for (int i = 0; i < lines - (counter / 2) - 3; i++) {
System.out.print(" ");
}
for (int count2 = 1; count2 <= counter; count2++) {
System.out.print("*");
}
System.out.println();
}
}
for (int counter = lines - 1; counter >= 1; counter--) {
if (counter % 2 != 0) {
for (int i = 0; i < lines - (counter / 2) - 3; i++) {
System.out.print(" ");
}
for (int count2 = 1; count2 <= counter; count2++) {
System.out.print("*");
}
System.out.println();
}
}
}
I think you should prepare a string to print out on each line, then you will know exactly how many characters it has, when the line increases, remove the two '*' in center of the string and add one " " in front of it, then print it out again.
Basically, I am given an array of numbers and I have to count all the negative numbers.
Then make a new array that contains all of the positive numbers from the previous with the length of the array being firstarray-numberOfNegatives
Here is my code:
public void removeNegatives()
{
int numberOfNegative = 0;
for(int i = 0; i < numbers.length-1; i++)
{
if (numbers[i] < 0) numberOfNegative++;
}
int [] numbers2 = new int[numbers.length-numberOfNegative];
int count = 0;
for(int i = 0; i < numbers2.length; i++)
{
if (numbers[count] > 0) numbers2[i] = numbers[count];
count++;
System.out.println(numbers2[i]);
}
numbers = numbers2;
}
I am getting the wrong result: negative numbers are replaced with 0s
At first write i < numbers.length; or i <= numbers.length-1; instead of i < numbers.length-1;
And then fix code.
Also note that you can have zeros in your 'numbers' array, so in if() in first for() you should write <=0 instead of <0
for(int i = 0; i < numbers.length; i++)
{
if (numbers[i] > 0) numbers2[count] = numbers[i];
count++;
System.out.println(numbers2[count-1]);
}
Firstly: you have an off-by-one error in your first for loop. Walk through some small example arrays in your head or on paper and you'll see.
Secondly: I think you are using your two index counters backwards in the second section. The count is supposed to be used in your new array, and i in your old one.
public void removeNegatives()
{
int numberOfNegative = 0;
for(int i = 0; i < numbers.length; i++) //
{
if (numbers[i] < 0) numberOfNegative++;
}
int [] numbers2 = new int[numbers.length-numberOfNegative];
int count = 0;
for(int i = 0; i < numbers.length; i++)
{
if (numbers[i] >= 0) numbers2[count++] = numbers[i]; //
}
numbers = numbers2;
}
Run through a debugger and watch this line...
That -1 is suspicious
for(int i = 0; i < numbers.length-1; i++)
:)
Need to reverse your index variables in the second pass. Also the first loop had a length-1 instead of length. The second loop should go over the full length of the original array not the resulting array.
public void removeNegatives()
{
int numberOfNegative = 0;
for(int i = 0; i < numbers.length; i++)
if (numbers[i] < 0)
numberOfNegative++;
int [] numbers2 = new int[numbers.length-numberOfNegative];
int count = 0;
for(int i = 0; i < numbers.length; i++)
{
if (numbers[i] >= 0) {
numbers2[count] = numbers[i];
System.out.println(numbers2[count]);
count++;
}
}
numbers = numbers2;
}
In
for(int i = 0; i < numbers2.length; i++)
{
if (numbers[count] > 0) numbers2[i] = numbers[count];
count++;
System.out.println(numbers2[i]);
}
numbers = numbers2;
}
You are iterating as many times as numbers2 has positions, however, you increase i at every pass (in the for loop) regardless of whether you fund a positive number or not. Your output arrray would therefore have the first numbers2.length positive integers of numbers interleaved with a bunch of 0s!