I keep trying to add (many times) +1 to a number (the number is zero) already in an array which is zero but it is not working.
int i=0;//var for arrays
int [] countArray = new int[10];
/////////////////////
//__________ ask for values --------------
System.out.println("Hello please enter the number you would" +
" like to be sorted separated by commas. \n" +
"Example: \" 2,3,5,83,2 \".\t only use" +
" commas. to separate numbers\n");
//----------- save values -----
Scanner scan = new Scanner(System.in);
String allInput = scan.nextLine();//single string object with all input
String [] arr = allInput.split(",");//string array that holds all values
//as String
int [] numbersArray =new int[arr.length] ;//numbers
for ( String w: arr){//change Strings to Int
numbersArray[i]= Integer.valueOf(arr[i]);
i++;
}
//__ set all number in count to zero because necessary
i=0;
for ( int x: countArray){//set all numbers to zero
countArray[i]=0;
i++;
} //everything zeroed
i=0;
This works now, thank you guys:
for (int x = 0; x < numbersArray.length; x++){
if (numbersArray[x] >=10 && numbersArray[x] <=100) {
countArray[(numbersArray[x]-1)/10]++;}
else{
if (numbersArray[x] >=0 && numbersArray[x] <=10)
{
countArray[1 -1]++;}
}
}
Instead of using a for-each loop to edit all the values, try to iterate through them using a standard for loop. Here is a shorthand version of what you wrote. Try this:
for (int x = 0; x < numbersArray.length; x++){
countArray[(numbersArray[x]-1)/10]++;
}
Related
I am trying to count the number of occurrences in an array of integers and return the amount of times each number was displayed. My code counts the right amount of occurrences, but it displays them more than once.
Here is the relevant code:
int num = input.nextInt();
int count = 0;
int[] integers = new int[num];
for(int i = 0; i < num; i++) {
System.out.print("Enter int 1-50: ");
integers[i] = input.nextInt();
}
for(int i = 0; i < num; i++) {
for(int j = 0; j < num; j++) {
if(integers[i] == integers[j]) {
count++;
}
}
System.out.println(integers[i] + " occurs "+count+" times.");
count = 0;
}
The issue is that if a number occurs more than once, it displays that number more than once. For example, {1, 2, 2, 3} would print "2 occurs 2 times" twice. I understand why this happens but I'm wondering if there's a simple way to make sure these statements only print once.
Your problem is the print statement. You call print at every iteration. Instead, you can store that count value in a map:
1 -> 1
2 -> 2
3 -> 1
Where the key is the integer value you are counting, and the value is how many times it appears in the array. At the end you can just print the map:
for(int key : map.keySet()) {
int value = map.get(key);
System.out.println(key + " occurs "+value+" times.");
}
You can find a more elegant solution here [link]
Without using Map :
If you input numbers will be within 1-50
then my approach will work
int a[]=new int[51];
int b[]={4,7,8,5,4,50,5,5,4,44};
for(int c:b){
a[c]++;
}
for(int c:b){
if(a[c]!=-1){
System.out.println("value: "+c+" "+"count"+ a[c]);
}
a[c]=-1;
}
import java.util.Scanner;
public class Project10C {
public static void main ( String [] args ) {
Scanner reader = new Scanner(System.in);
int [] finalarray = new int [5];
int [] test = new int [1000];
int x = 1000;
int temp1;
for ( int i = 0; i <= 4;i++){
System.out.println ( "Input a number between 1 and 25 inclusive: " );
temp1 = reader.nextInt();
test[i] = temp1;
if ( i > 0 ){
if ( temp1 == test[i] ) {
System.out.print ("Sorry that number has already been entered.");
break;
}
else {
finalarray[i]= temp1;
Did not include brackets in this question. Point of this code is check if numbers inputted have already been entered. I'm having difficulty trying checking if the number they input is equal to values in an already existing array. In this:
if (temp1 == test[i] ){
From my own knowledge this will only check the current array going through this if statement every time. Should I be using another for statement? If so what would I put for the second parameter of the for statement?
There are many ways to do this. The easiest way is probably using another loop inside the main loop, as follow:
for ( int i = 0; i <= 4;i++){
System.out.println ( "Input a number between 1 and 25 inclusive: " );
temp1 = reader.nextInt();
boolean repeated = false;
for(int j = 0; j < i; j++) {
if(finalarray[j] == temp1) {
// the number is already entered.
repeated = true;
break;
}
}
if(repeated)
break;
// number is not entered before
finalarray[i] = temp1;
}
Actually when you're reading i-th number, you have to check every number from 0 to (i - 1) in the array to not be equal with entered number.
However, if there are a lot of numbers, using a data structure like Set is preferable. Just add every number to the set and then you can easily check if a new number is previously entered:
Set<Integer> numbers = new TreeSet<Integer>();
for(int i = 0; i < n; i++) {
temp1 = reader.nextInt();
if(numbers.contains(temp1)) {
// already entered
break;
}
// number is not entered before
// add it to our array
finalarray[i] = temp1;
// also put it in the set for future checks
numbers.add(temp1);
}
You need another for-loop to compare previous elements of final-array with the entered input as recommended in my solution. Also, the loop would iterate always from 0 to i---the key thing!
The solution goes as :-
for ( int i = 0; i <= 4;i++){
System.out.println ( "Input a number between 1 and 25 inclusive: " );
temp1 = reader.nextInt();
for( int j=0;j<i;j++){
if(temp1==finalarray[j]){
System.out.println("Sorry that number has already been entered.");
break;
}
else
finalarray[i]= temp1;
}
}
Do you have to use a primitive array, or can you use an ArrayList? If you can use an ArrayList:
List<int> myArrayList = new ArrayList();
for (int i = 0; i <= 4; i++){
System.out.println ( "Input a number between 1 and 25 inclusive: " );
temp1 = reader.nextInt();
/* The array list already has the input number. */
if (myArrayList.contains(temp1)) {
System.out.print ("Sorry that number has already been entered.");
break;
/* The array list does not contain the input number. */
} else
myArrayList.add(temp1);
}
Also, are you only trying to allow 4 digit numbers to be input?
sNums = scanString.nextLine();
String[] num = sNums.split(" ");
for (int i = 0; i < num.length; ++i)
{
numbers = new double[i+1];
numbers[i] = Double.valueOf(num[i]);
}
for(double item: numbers)
out.print(item + " ");
I'm trying to change the String of numbers I have which is "num" in this case into an array of double. I'm pretty sure this should work but for some reason it's storing "0.0" into every element entered except for the last one. For example if I enter "1 5 7 90 52[enter]" the output should be "1.0 5.0 7.0...etc" but instead what I get is "0.0 0.0 0.0 0.0 52.0"
The problem you have is that you create a new array in loop. You should take it out and initialized.
String[] num = sNums.split(" ");
double[] numbers = new double[num.length]; // The valid place for loop
for (int i = 0; i < num.length; ++i)
{
numbers[i] = Double.valueOf(num[i]);
}
for(double item: numbers) {
out.print(item + " ");
}
You're recreating the array each time in the for loop. Also you're using a for each at the second for and not using it, using i instead. That would not compile since i was never declared in that scope.. Anyway I suggest you forget about arrays in Java and use Lists, they're much more convenient.
sNums = scanString.nextLine();
final String[] num = sNums.split(" ");
final List<Double> numbers = new ArrayList<Double>();
for (final String cur: num) {
numbers.add(Double.valueOf(cur));
}
for(final Double item: numbers) {
out.print(item + " ");
}
You're simple creating a new array with the increasing size in the loop on every iteration. You just need to create a new array once and populate the values in it, in the loop.
numbers = new double[num.length];
for (int i = 0; i < num.length; ++i) {
// numbers = new double[i+1]; // Not needed
numbers[i] = Double.valueOf(num[i]);
}
You are misnaming among num and number.
you are creating a new array each time the first for loop body. rather remove it from the loop body and place it before the loop statement as you were doing.
String[] number = sNums.split(" ");
for (int i = 0; i < number.length; ++i)
{
// numbers = new double[i+1]; <-- commented out
numbers[i] = Double.valueOf(num[i]);
}
You are printing it wrong with enhanced-for loop:
for(double item: numbers)
out.print(numbers[i] + " ");
// <-- i may already have the value of number.length
Rather directly print with item:
for(double item: numbers)
out.print(item + " ");
Using 'args' from command line arguments you can use:
List<Double> numbers = new ArrayList<Double>();
for(String a:args){
numbers.add(Double.valueOf(a));
}
System.out.println(numbers);
The problem is :
Write a program that reads a number n and then declares an array of n elements. The program then fills the array with the first n numbers, where each number is two to the power of the previous. Finally, display array’s contents.
My code :
import java.util.*;
public class Q1 {
static Scanner scan = new Scanner (System.in);
public static void main(String args [] ) {
int num;
int i = 0;
System.out.println("Enter a number :");
num = scan.nextInt();
double [] a=new double[num];
a[0]= num ;
for ( ;i<=a.length-1 ; i++) {
a[i+1] = Math.pow(2,a[i]);
System.out.println((int)(a[i]) );
}
}
}
The error is :
----jGRASP exec: java Q1
Enter a number :
4
4
16
65536
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at Q1.main(Q1.java:16)
----jGRASP wedge2: exit code for process is 1.
why it says that?
And the number by user printed twice!
a[i+1] = Math.pow(2,a[i]); // issue here
When i=a.length-1, i+1 is a.length. So there is no index value match in this array.
Suggestion:
Create an array witch has lenght= a.length+1
double powArray[] =new double[a.length+1];
Now
powArray[0]=a[0];
for(int i=1;i<powArray.length;i++){
powArray[i]=Math.pow(2,a[i-1]);
}
Issue is on line.16 as per compiler : a[i+1] = Math.pow(2,a[i]); The problem is indexes are not properly matched here.So it gives ArrayIndexOutOfBound Exception.Here i=a.length-1, i+1=a.length.So it is giving ArrayIndexOutOfBound Exception.
You should check that your index is not negative and not higher than the array length before accessing an array item.
Refer this : Avoiding index out of bounds exceptions
Concentrate on below portion of your code, its easy and you'll feel good if you figure out yourself:
for ( ;i<=a.length-1 ; i++) // check from where i starts and where it ends
{
a[i+1] = Math.pow(2,a[i]); // check what value of i would be here on each iteration
System.out.println((int)(a[i]) );
}
Also you could use a debugger and check every iteration
Few things to look upon here.
You have written a[0]= num ; which means the first value in the array is the same as the number entered by the user. Thus, you can see the number printed again. Thus,
a[0] = 1; // initial value has to be 1, contrary to what you've used
Next, your loop to generate the array values needs to be fixed. When you have i+1, the array index goes out of bounds in the last iteration, where your i is a.length - 1. Thus change your loop to something like this
for (int i = 1; i < a.length; i++) {
a[i] = Math.pow(2, a[i-1]);
}
Now, print the array values in a separate loop, as the previous loop won't print the value of the first index of the array.
for (int i = 0; i < a.length; i++) {
System.out.println((int)a[i]);
}
Change the upper limit to a.length-2 .Rest code remain same
import java.util.*;
public class Q1 {
static Scanner scan = new Scanner (System.in);
public static void main(String args [] ) {
int num;
int i = 0;
System.out.println("Enter a number :");
num = scan.nextInt();
double [] a=new double[num];
a[0]= num ;
for ( ;i<=a.length-2 ; i++) {
a[i+1] = Math.pow(2,a[i]);
System.out.println((int)(a[i]) );
}
}
}
int num ;
System.out.println("Enter a number :");
num = scan.nextInt();
double [] a=new double[num];
a[0]= num ; //Assign First Element To Array
double prev = a[0];
for(int i=1;i<a.length;i++){
a[i] = Math.pow(2,prev);
prev = a[i];
}
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
Output
Enter a number :
3
3.0
8.0
256.0
Just change the loop to :
for(;i < a.length-1;i++)
since when you assign 4 as a length for a[]..
you have a[0],a[1],a[2],a[3]... 4 slots.
Now a.length gives 4.
so for your a[i+1] for i=a.length-1 (i.e 3 ) .. a[i+1] = a[4]... which is out of the array bound for you array.
import java.util.*;
public class Q1 {
static Scanner scan = new Scanner (System.in);
public static void main(String args [] ) {
int num;
int i = 0;
System.out.println("Enter a number :");
num = scan.nextInt();
double [] a=new double[num];
for ( ;i<a.length ; i++) {
a[i] = Math.pow(2,i);
System.out.pri``nt((int)a[i]+ " ");
}
}
}
I have gotten 10 values from the user, and I am suppose to put that into an array and call it into a method, and then call another method which contains an array that reverses the integers of the first array without using global variables. For example, the user gives me values 1,2,3, etc.. and I store that in the first array, then in the second array I output 3,2,1.
I have part of the code that gets the integers from the user, but I don't know how to reverse the array without using global variables. The code doesn't run when it gets to the second method at values[i];
Here is what I have so far:
public static void main(String[] args) {
getInput();
reverseInput();
System.exit(0);
}
public static void getInput() {
Scanner keyboard = new Scanner(System.in);
int[] values;
values = new int[10];
//Ask the user to enter 10 integers
System.out.println("Please enter ten numbers.");
for (int i = 0; i<values.length; i++) {//for loop to display the values entered
values[i] = keyboard.nextInt();
System.out.println("Value" + (i +1) + " is " + values[i]);
}
}
public static void reverseInput() {
System.out.println("Now we are going to reverse the numbers.");
Scanner keyboard = new Scanner(System.in);
int [] values;
values = new int[10];
for (int i = (values.length -1); i>= 0; i--) {//for loop to display integers in reversed order
values[i];
System.out.println(values[i]);
}
}
First, if you are not going to be using global variables, then you will need to pass the array from the get input method to the reverseInput method. Something like this:
int[] values = getInput();
reverseInput(values);
Then to output the array in your reverseInput method, it would have to look like this:
public static void reverseInput(int[] values) {
for(int i = (values.length - 1); i >= 0; i--){
System.out.println(values[i]);
}
}
You can use the ArrayUtils.reverse from Commons Lang:
ArrayUtils.reverse(values);
Ok, you understand how to display the elements in reference order. As you wrote:
for (int i = (values.length - 1); i >= 0; i--) {
System.out.println(values[i]);
}
So given that, how would you put the elements of values (say it has 5 elements) in another array (call it reversedValues) such that values[4] was put into reversedValues[0] and so on up to values[0] being put into reversedValues[4]?
use the "getInput" as basis to get the 10 numbers, then after the "for" loop, just do another for loop in reverse
public static void reverseInput()
{
Scanner keyboard = new Scanner(System.in);
int[] values;
values = new int[10];
//Ask the user to enter 10 integers
System.out.println("Please enter ten numbers, we are going to reverse the numbers");
for (int i = 0; i<values.length; i++) //for loop to display the values entered
{
values[i] = keyboard.nextInt();
};
int[] revValues;
revValues = new int[10];
for (int i = (values.length -1); i>= 0; i--) //for loop to display integers in reversed order
{
revValues[ revValues.length -1 -i ] = values[ i ];
System.out.println( revValues[ i ] );
}
}