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);
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;
}
When I try to run this program in java it will not work even though there are no errors in eclipse.
import java.util.Scanner;
public class Project1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter how many numbers: ");
int x = input.nextInt();
double[] numbers = new double[x];
double[] orderednumbers = new double[x];
double total = 0;
for (int i = 0; i < numbers.length; i++) {
System.out.print("Please enter number " + (i + 1) + ": ");
numbers[i] = input.nextDouble();
total += numbers[i];
}
double mean = (total / x);
System.out.println("Mean: " + mean);
orderednumbers[x] = 0;
for (int counter = 0; counter < numbers.length; counter++) {
if (numbers[counter] > orderednumbers[x]) {
orderednumbers[x] = numbers[counter];
orderednumbers[x] = orderednumbers[x];
}
}
System.out.println("Maximum: " + orderednumbers[x]);
}
}
This is what's called a runtime error. Sure, it compiles... but for this code you need to be careful with how you handle the array. Your code gave me an ArrayOutOfBoundsException.
Note that you set x early in the code to the length of the array, then go and set orderednumbers[x] to 0. This will give you an ArrayIndexOutOfBoundsException, as since Java array indices are zero-based (i.e. element #1 has index 0, and can be accessed with orderednumbers[0]), the length of an array isn't a valid index.
Also, your code for swapping the two numbers in the sort is incorrect; you'll need a temporary variable to store the result. Otherwise, you'll end up making the two places in the array hold the same value.
Try making it this:
int temp = orderednumbers[x];
orderednumbers[x] = numbers[counter];
orderednumbers[x] = temp;
Note that your statement at the end of the if block:
orderednumbers[x] = orderednumbers[x];
won't accomplish anything.
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]++;
}
This is part of a larger assignment. Here, I basically need to accept user input until the user types 0. These doubles need to be added to an array. For some reason, they aren't being added to the array right now. Any help?
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
double[] inputArray = new double[3];
double input;
do{
input = scanner.nextDouble();
for(int i = 0; i < 3; i++){
inputArray[i] = input;
}
}
while(input != 0);
System.out.println("Element 0:" + inputArray[0]);
System.out.println("Element 1:" + inputArray[1]);
}
You're keeping on iterating until input is 0... so on the last iteration of the loop before it terminates, we know that input will be 0.
Now look at what you're doing in the while loop:
for(int i = 0; i < 3; i++){
inputArray[i] = input;
}
You're replacing all the elements in the array with the current value of input.
So by the time you exit the loop, you've just replaced all the elements with 0.
It would be much better to use a List<Double> with a suitable implementation (e.g. ArrayList<Double>) and just call list.add(input) within the while loop.
Then to print out every element of the list:
for (Double value : list) {
System.out.println(value);
}
Or if you really want the index:
for (int i = 0; list.size(); i++) {
System.out.println("Element " + i + ": " + list.get(i));
}
If you have to use an array, you should keep track of how many items you've already set (with a counter incremented in the while loop) and only set one value in the array for each iteration of the loop. Don't forget to terminate the loop if you run out of space in the array, too!
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 ] );
}
}