Related
I want to add numbers in sorted way before entering vector. But the result is not right and I am confused where the problem is ? Output is shown below.
I want to sort using some algorithm without any inbuilt methods.
import java.util.Vector;
public class Test {
public static void main(String ar[]){
//Numbers to enter in vector
int[] number = {5,2,98,3,10,1};
Vector<Integer> v = new Vector<Integer>();
v.add(number[0]);
for(int i=1;i<number.length;i++){
for(int j=v.size();j>0;j--){
System.out.println("Entered: "+number[i]);
if(number[i] <= v.get(j-1)){
v.add(j-1,number[i]);
break;
}else{
v.add(j,number[i]);
break;
}
}
}
for(int s:v)
System.out.print(s + " ");
}
}
OUTPUT:
Entered: 2
Entered: 98
Entered: 3
Entered: 10
Entered: 1
2 5 3 10 1 98
You have a second (inner) for loop based on the variable j, but that "loop" will only execute exactly one time. Both conditions inside the j loop cause the loop to exit (break;).
When you're adding each number, the only possibilities are last or next to last.
Your inner for loop doesn't actually loop.
Regardless of the condition number[i] <= v.get(j-1),
the loop will exit after one step.
What you want to do is,
iterate from the beginning of the vector,
and when you find an element that's bigger than the one you want to insert,
then insert it, and break out of the loop.
This is opposite of what you did so far, which is iterating from the end of the vector.
If the end of the loop is reached without inserting anything,
then append the value.
The program badly needs some other improvements too:
If you don't need the vector to be thread-safe, then you don't need Vector. Use ArrayList instead.
The special treatment for the first number is unnecessary.
The outer loop can be written in a more natural way using the for-each idiom.
No need to loop to print the elements, the toString implementation of Vector is already easy to read.
The variable names are very poor and can be easily improved.
The indentation is inconsistent, making the code very hard to read.
With the problem fixed and the suggestions applied:
List<Integer> list = new ArrayList<>();
for (int current : numbers) {
boolean inserted = false;
for (int j = 0; j < list.size(); j++) {
if (current <= list.get(j)) {
list.add(j, current);
inserted = true;
break;
}
}
if (!inserted) {
list.add(current);
}
}
System.out.println(list);
Last but not least, instead of searching for the insertion point by iterating over the list,
you could achieve much better performance using binary search,
especially for larger sets of values.
Another simple solution would be:
import java.util.Vector;
public class Test {
public static void main(String ar[]){
//Numbers to enter in vector
int[] number = {5,2,98,3,10,1};
Vector<Integer> v = new Vector<Integer>();
v.add(number[0]);
for(int i=1, j;i<number.length;i++){ //j declared here for better scope
for(j=v.size();j>0 && v.get(j-1)>number[i] ;j--); //<-- some changes here,
v.add(j,number[i]); //<-- and here
}
}
for(int s:v)
System.out.print(s + " ");
}
}
The inner for loop is simply used to find the right index for an element to be inserted.
Your inner loop seems to not looping more than one time. That's why the key is not being inserted into right place.
A more concise solution would be
public class Test {
public static void main(String ar[]){
//Numbers to enter in vector
int[] number = {5,2,98,3,10,1};
Vector<Integer> v = new Vector<Integer>();
v.setSize(number.length);
v[0] = number[0];
for(int i=1, vSize = 1; i < number.length; i++, vSize++){
int j = 0, k = 0;
for(j = 0; j < vSize; j++) {
if(v[j] < number[i]) {
break;
}
for(k = vSize; k > j; k--) {
v[k] = v[k -1];
}
v[k] = number[i];
}
for(int s:v)
System.out.print(s + " ");
}
}
I am yet again stuck at the answer. This program prints the unique values but I am unable to get the sum of those unique values right. Any help is appreciated
public static void main(String args[]){
int sum = 0;
Integer[] numbers = {1,2,23,43,23,56,7,9,11,12,12,67,54,23,56,54,43,2,1,19};
Set<Integer> setUniqueNumbers = new LinkedHashSet<Integer>();
for (int x : numbers) {
setUniqueNumbers.add(x);
}
for (Integer x : setUniqueNumbers) {
System.out.println(x);
for (int i=0; i<=x; i++){
sum += i;
}
}
System.out.println(sum);
}
This is a great example for making use of the Java 8 language additions:
int sum = Arrays.stream(numbers).distinct().collect(Collectors.summingInt(Integer::intValue));
This line would replace everything in your code starting at the Set declaration until the last line before the System.out.println.
There's no need for this loop
for (int i=0; i<=x; i++){
sum += i;
}
Because you're adding i rather than the actual integers in the set. What's happening here is that you're adding all the numbers from 0 to x to sum. So for 23, you're not increasing sum by 23, instead, you're adding 1+2+3+4+5+....+23 to sum. All you need to do is add x, so the above loop can be omitted and replaced with a simple line of adding x to sum,
sum += x;
This kind of error always occures if one pokes around in low level loops etc.
Best is, to get rid of low level code and use Java 8 APIs:
Integer[] numbers = {1,2,23,43,23,56,7,9,11,12,12,67,54,23,56,54,43,2,1,19};
int sum = Arrays.stream(numbers)
.distinct()
.mapToInt(Integer::intValue)
.sum();
In this way there is barely any space for mistakes.
If you have an int array, the code is even shorter:
int[] intnumbers = {1,2,23,43,23,56,7,9,11,12,12,67,54,23,56,54,43,2,1,19};
int sumofints = Arrays.stream(intnumbers)
.distinct()
.sum();
So this is my first time commenting anywhere and I just really wanted to share my way of printing out only the unique values in an array without the need of any utilities.
//The following program seeks to process an array to remove all duplicate integers.
//The method prints the array before and after removing any duplicates
public class NoDups
{
//we use a void static void method as I wanted to print out the array without any duplicates. Doing it like this negates the need for any additional code after calling the method
static void printNoDups(int array[])
{ //Below prints out the array before any processing takes place
System.out.println("The array before any processing took place is: ");
System.out.print("{");
for (int i = 0; i < array.length; i++)
{
System.out.print(array[i]);
if (i != array.length - 1)
System.out.print(", ");
}
System.out.print("}");
System.out.println("");
//the if and if else statements below checks if the array contains more than 1 value as there can be no duplicates if this is the case
if (array.length==0)
System.out.println("That array has a length of 0.");
else if (array.length==1)
System.out.println("That array only has one value: " + array[0]);
else //This is where the fun begins
{
System.out.println("Processed Array is: ");
System.out.print( "{" + array[0]);//we print out the first value as it will always be printed (no duplicates has occured before it)
for (int i = 1; i < array.length; i++) //This parent for loop increments once the all the checks below are run
{
int check = 0;//this variable tracks the amount of times an value has appeared
for(int h = 0; h < i; h++) //This loop checks the current value for array[i] against all values before it
{
if (array[i] == array[h])
{
++check; //if any values match during this loop, the check value increments
}
}
if (check != 1) //only duplicates can result in a check value other than 1
{
System.out.print(", " + array[i]);
}
}
}
System.out.print("}"); //formatting
System.out.println("");
}
public static void main(String[] args)
{ //I really wanted to be able to request an input from the user but so that they could just copy and paste the whole array in as an input.
//I'm sure this can be done by splitting the input on "," or " " and then using a for loop to add them to the array but I dont want to spend too much time on this as there are still many tasks to get through!
//Will come back and revisit to add this if I remember.
int inpArray[] = {20,100,10,80,70,1,0,-1,2,10,15,300,7,6,2,18,19,21,9,0}; //This is just a test array
printNoDups(inpArray);
}
}
the bug is on the line
sum += i;
it should be
sum += x;
As i am new to java i got a task to find duplicate word only and its count. i stuck in a place and i am unable to get the appropriate output. I can not use any collections and built in tool. i tried the below code. Need some help, Please help me out.
public class RepeatedWord
{
public static void main(String[] args)
{
String sen = "hi hello hi good morning hello";
String word[] = sen.split(" ");
int count=0;
for( int i=0;i<word.length;i++)
{
for( int j=0;j<word.length;j++)
{
if(word[i].equals(word[j]))
{
count++;
}
if(count>1)
System.out.println("the word "+word[i]+" occured"+ count+" time");
}
}
}
}
expecting output:-
the word hi occured 2 time
the word hello occured 2 time
but i am getting output like below :-
the word hi occured 2 time
the word hi occured 2 time
the word hi occured 2 time
the word hi occured 2 time
the word hello occured 2 time
the word hi occured 2 time
the word hi occured 2 time
the word hi occured 2 time
the word hi occured 2 time
the word hello occured 2 time
please help me to get the output like i am expecting. and please explain. so that i can understand too.
Thanks in advance
You need to print the result only for the outer loop. Also, you need to avoid checking the words that were already checked in previous iteration:
for (int i = 0; i < word.length; i++) {
int count = 0; // reset the counter for each word
for (int j = 0; j < word.length; j++) {
if (word[i].equals(word[j])) {
/* if the words are the same, but j < i, it was already calculated
and printed earlier, so we can stop checking the current word
and move on to another one */
if (j < i) {
break; // exit the inner loop, continue with the outer one
}
count++;
}
}
if (count > 1) {
System.out.println("the word " + word[i] + " occured " + count + " time");
}
}
UPDATE
Additional explanation around this code: if (j < i) { break; }
i is the index of the word we calculate duplicates for, j is the word we compare it against. Since we start always from beginning, we know that if the words are equal while j < i, it was already processed in earlier run of the outer loop.
In this case, using break, we interrupt the inner loop and the flow continues in the outer loop. As we didn't update count at all, it is still zero and thus the condition for printing the result if (count > 1) is not satisfied and the println is not executed.
Example for the word "hello", using simple pseudo-code in the following part.
For its first occurrence:
count = 0
i = 1, j = 0 --> hello != hi --> do nothing
i = 1, j = 1 --> hello == hello, j is not < i --> count++
i = 1, j = 2 --> hello != hi --> do nothing
i = 1, j = 3 --> hello != good --> do nothing
i = 1, j = 4 --> hello != morning --> do nothing
i = 1, j = 5 --> hello == hello, j is not < i --> count++
count > 1 --> print the result
For its second occurrence:
count = 0
i = 5, j = 0 --> hello != hi --> do nothing
i = 5, j = 1 --> hello == hello, j < i --> break, we have seen this pair earlier
count is not > 1 --> result not printed
Hope I didn't make things more complicated with this example
Print Outside first for loop,This will do the trick and initialize count=0 in for loop beginning
for( int i=0;i<word.length;i++)
{
count=0;
for( int j=0;j<word.length;j++)
{
if(word[i].equals(word[j]))
{
count++;
}
}
if(count>1)
System.out.println("the word "+word[i]+" occured"+ count+" time");
}
enter code here
import java.util.*;
class test{
public static void main(String[] args){
String s;
int count=0;
int count1=0;
System.out.println("Enter the Sentence");
Scanner scan=new Scanner(System.in);
s=scan.nextLine();
System.out.println(s);
String[] arr=s.split(" ");
String[] srr=new String[arr.length];
int[] rev=new int[arr.length];
for(int i=0;i<arr.length; i++)
{ if(arr[i]!="NULL"){
String temp=arr[i];
for(int j=i+1;j<arr.length; j++)
{
if(temp.equals(arr[j]))
{
arr[j]="NULL";
count++;
}
}
srr[count1]=temp;
rev[count1]=count;
count=0;
count1++;
}
}
for(int i=0;i<count1;i++)
System.out.println(srr[i]+" "+rev[i]);
}
}
I'm playing around with double arrays and am trying to set all the even elements of an array to 0 and all of the odd elements of the array to 1. Everything looks okay to me, but when I run it I get a bunch of errors. Not sure what's wrong; I've been looking at it for a while with no luck. Any advice on how to fix the errors it gives would be great, thanks!
Code:
public class SetOf0and1 {
public static void main(String[]args)
{
int [][] numbers1 = {{4,2,5}, {2,4,1}, {1,3}};
System.out.println("Before setting elements between 0 and 1: ");
displayArray(numbers1);
setEvenRowsTo0OddRowsTo1 (numbers1);
System.out.println("After setting the elements between 0 and 1");
displayArray(numbers1);
}
public static void setEvenRowsTo0OddRowsTo1(int [][]array)
{
for(int i=0; i<array.length;i++)
{
for(int j=0; j<array[i].length;j++)
{
if(i%2 == 0)
array[i][j]=0;
else
array[i][j]=1;
}
}
}
public static void displayArray(int [][]array)
{
for(int i=0;i<array.length;i++)
{
for( int j=0; j<array.length;j++)
{
System.out.println(array[i][j] + " " );
}
System.out.println();
}
}
}
Errors given:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at SetOf0and1.displayArray(SetOf0and1.java:38)
at SetOf0and1.main(SetOf0and1.java:10)
public static void displayArray(int [][]array)
{
for(int i=0;i<array.length;i++)
{
for( int j=0; j<array.length;j++)
^^^^^^^^^
{
System.out.println(array[i][j] + " " );
}
System.out.println();
}
Your inner loop should stop at array[i].length.
In the method displayArray, the line:
for( int j=0; j<array.length;j++)
Should be:
for( int j=0; j<array[i].length;j++)
array.length does not return the length you thing it does! You have a 2 dimentional array. So if we say you have array[x][y] then array.length will be x and array[i].length (for 0 <= i < x) will be y. This could be different depending on the length of the array on that index. (so the formula does not exactly apply like that)
int [][] numbers1 = {{4,2,5}, {2,4,1}, {1,3}};
this statement initializes an array with three arrays of the legthes 3, 3 and 2!!!
(in the third block you have only two elements !!! - {1,3})
In your displayArray-method you use two times ...
array.length
... to distinct the size of the loop
that sets the number of loops to 3 ... But last block is only two elements long -> errror.
Use this instead for the second loop:
for( int j=0; j<array[i].length;j++)
If you want to check if a number is odd, you can do it this way:
int answer = thenumber % 2;
'thenumber' is the integer to check if it is even.
Then 'answer' would be 0 if the number was even.
And if you want to loop through the array and do it:
for (int i = 0; i < numbers1.length(); i++)
{
if (numbers1[i] % 2 == 0) {
//EVEN
numbers1[i] = 0;
}
else if (numbers1[i] % 2 == 1) {
//ODD
numbers1[i] = 1;
}
}
And, even more compact:
for (int i = 0; i < numbers1.length(); i++)
{
numbers1[i] %= 2;
}
Edit: I forgot that it was an array you had! I was thinking about ArrayList! Fixed.
I need to produce a triangle as shown:
1
22
333
4444
55555
and my code is:
int i, j;
for(i = 1; i <= 5; i++)
{
for(j = 1; j <= i; j++)
{
System.out.print(i);
}
System.out.print("\n");
}
Producing a triangle the opposite way
1
22
333
4444
55555
What do i need to do to my code to make it face the right way?
You need 3 for loops:
Upper-level loop for the actual number to be repeated and printed
first inner level for printing the spaces
second inner level for to print the number repeatedly
at the end of the Upper-level loop print new line
Code:
public void printReversedTriangle(int num)
{
for(int i=0; i<=num; i++)
{
for(int j=num-i; j>0; j--)
{
System.out.print(" ");
}
for(int z=0; z<i; z++)
{
System.out.print(i);
}
System.out.println();
}
}
Output:
1
22
333
4444
55555
666666
I came across this problem in my AP CS class. I think you may be starting to learn how to program so heres what I'd do without giving you the answer.
Use a loop which removes the number of spaces each iteration. The first time through you would want to print four spaces then print 1 one time(probably done in a separate loop).
Next time through one less space, but print i one more time.
You need to print some spaces. There is a relation between the number of spaces you need and the number (i) you're printing. You can print X number of spaces using :
for (int k = 0; k < numSpaces; k++)
{
System.out.print(" ");
}
So in your code:
int i, j;
for(i = 1; i <= 5; i++)
{
// Determine number of spaces needed
// print spaces
for(j = 1; j <= i; j++)
{
System.out.print(i);
}
System.out.print("\n");
}
use this code ,
int i, j,z;
boolean repeat = false;
for (i = 1; i <= 5; i++) {
repeat = true;
for (j = 1; j <= i; j++) {
if(repeat){
z = i;
repeat = false;
while(z<5){
System.out.print(" ");
z++;
}
}
System.out.print(i);
}
{
System.out.print("\n");
}
}
You can use this:
int i, j;
int size = 5;
for (i = 1; i <= size; i++) {
if (i < size) System.out.printf("%"+(size-i)+"s", " ");
for (j = 1; j <= i; j++) {
System.out.print(i);
}
System.out.print("\n");
}
This line:
if (i < size) System.out.printf("%"+(size-i)+"s", " ");
Is going to print the left spaces.
It uses the old printf with a fixed sized string like 5 characters: %5s
Try it here: http://ideone.com/jAQk67
i'm having trouble sometimes as well when it's about formatting on console...
...i usually extract that problem into a separate method...
all about how to create the numbers and spacing has been posted already, so this might be overkill ^^
/**
* creates a String of the inputted number with leading spaces
* #param number the number to be formatted
* #param length the length of the returned string
* #return a String of the number with the size length
*/
static String formatNumber(int number, int length){
String numberFormatted = ""+number; //start with the number
do{
numberFormatted = " "+numberFormatted; //add spaces in front of
}while(numberFormatted.length()<length); //until it reaches desired length
return formattedNumber;
}
that example can be easily modified to be used even for Strings or whatever ^^
Use three loops and it will produce your required output:
for (int i=1;i<6 ;i++ )
{
for(int j=5;j>i;j--)
{
System.out.print(" ");
}
for(int k=0;k<i;k++)
{
System.out.print(i);
}
System.out.print("\n");
}
Your code does not produce the opposite, because the opposite would mean that you have spaces but on the right side. The right side of your output is simply empty, making you think you have the opposite. You need to include spaces in order to form the shape you want.
Try this:
public class Test{
public static void main (String [] args){
for(int line = 1; line <= 5; line++){
//i decreases with every loop since number of spaces
//is decreasing
for(int i =-1*line +5; i>=1; i--){
System.out.print(" ");
}
//j increases with every loop since number of numbers
//is decreasing
for(int j = 1; j <= line; j++){
System.out.print(line);
}
//End of loop, start a new line
System.out.println();
}
}
}
You approached the problem correctly, by starting with the number of lines. Next you have to make a relation between the number of lines (the first for loop) and the for loops inside. When you want to do that remember this formula:
Rate of change*line + X = number of elements on line
You calculate rate of change by seeing how the number of elements change after each line. For example on the first line you have 4 spaces, on the second line you have 3 spaces. You do 3 - 4 = -1, in other words with each line you move to, the number of spaces is decreasing by 1. Now pick a line, let's say second line. By using the formula you will have
-1(rate of change) * 2(line) + X = 3(how many spaces you have on the line you picked).
You get X = 5, and there you go you have your formula which you can use in your code as you can see on line 4 in the for loop.
for(int i = -1 * line +5; i >= 1; i--)
You do the same for the amount of numbers on each line, but since rate of change is 1 i.e with every line the amount of numbers is increasing by 1, X will be 0 since the number of elements is equal to the line number.
for(int j = 1; j <= line; j++){