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!
Related
What I have is a program that prints out 4000+ random digits in the range of 1 to 99999. After printing, it shows the range, and a couple of other things, and then asks user for 5 numbers to be input and tells how many times it had to run the loop, but I'm getting an exception in main upon print, it's coming from the main for loop. Screenshot is attached. Desired should look something like:
(Randomly generated numbers):
25
192
33
(User Enters) Please enter number: 33
(System Response) It took 3 times to find the number.
If the number is not listed, as it is over 4000 integers, it will say, not found.
Here is code and screenshot:
Screenshot
Exception in Main java.lang.ArrayIndexOutOfBoundsException:0
Thank You!
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int[] input = new int[0];
int[] arrayone = new int[4096];
int loop = 0;
for(int i = 0; i < arrayone.length; i++) {
arrayone[i] = (int)(Math.random() * 99999 + 1);
for(int in = 0; in<input.length; in++) {
if (arrayone[i] == input[in]) {
loop++;
}
}
}
for (int i = 0; i < 5; i++) {
System.out.println("Please enter a number between " + min + " and " + max);
input[0] = s.nextInt();
if (min <= input[0] && input[0] <= max) {
System.out.println("It took " + loop + " time(s) to find the number " + input);
}
}
}
The problem with your input array is that you initialize it with a size of 0, so when you try to access the first location [0], you run out of the bounds since your array has a size of 0. In your answer you were also trying to determine the loops before asking the question. While doing this you were also trying go past the bounds of your input array with a size 0. What you should do is initialize your array of numbers first then for each guess loop through and determine if it's within the bounds of your max and min. Also note that just because the numbers are within the max and min doesn't guarantee the number is contained in the array because the numbers are not going to be sequential from max to min. You should check where you end up after your for-loop check for the input.
public static void main(String random[])
{
Scanner s = new Scanner(System.in);
int input = new int[5];
int[] arrayone = new int[4096];
int loop = 0;
//don't do anything here except fill the array with values
for(int i = 0; i < arrayone.length; i++) {
arrayone[i] = (int)(Math.random() * 99999 + 1);
}
//ask the user for 5 inputs
for (int index = 0; index < input.length; index++) {
System.out.println("Please enter a number between " + min + " and " + max);
input[index] = s.nextInt();
//check to see if the number is valid
if (min <= input[index] && input[index] <= max) {
//loop through the arrayone to determine where it is
for(int i = 0; i < arrayone.length; i++) {
//if it is not in the current index at i increment the loop count
if (arrayone[i] != input[index]) {
loop++;
}
//we have found where it is and should break out of the loop
else {
break;
}
}
//check if we found it based on how much we incremented
if(i != arrayone.length)
{
//output how long it took to find the number
System.out.println("It took " + loop + " time(s) to find the number " + input[index]);
}
else
{
System.out.println(input[index] + " not found!");
}
//now reinitialize the loop to 0 for the next guess
loop = 0;
}
}
//always remember to close your scanners
s.close();
}
}
int[] input = new int[0];
This creates an array with size of 0, so when you try save value it throws an exception because you are exceeding array size.
Solution: set valid size of array or use list.
The ArrayList is (simplifying) resizeable version of array. Use it like this:
List<Integer> input = new ArrayList<>();
input.add(5); //Adds 5 to list
input.get(0); //Read object of index 0
for(int value : list) { //Loop: for each element in list ...
System.out.println(value);
}
//Checks whether list contains 5
System.out.println(list.contains(5));
Also, do you actually need input to be an array? Because right now it looks like you don't need it at all.
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;
In my program, I want to display an array using Scanner, i.e the user enters the array values during runtime.
public class NameComparator {
public static void main(String args[]) {
Scanner sn = new Scanner(System.in);
int n = sn.nextInt();
System.out.println("the array size is" + n);
int[] a = new int[7];
for (int i = 0; i >= a.length; i++) {
a[i] = sn.nextInt();
System.out.println("the value of a[i]" + a[i]);
}
sn.close();
System.out.println("array values are");
}
}
Here, I have got the array size from Scanner and then using for loop to get each array value, but I don't know why the array block hasn't executed. JVM just skips the for loop. Scanner works well
This:
for(int i=0;i>=a.length;i++)
should be:
for (int i = 0; i < a.length; i++)
You want to loop as long as i is smaller than a.length (i.e. the size of the array).
The for loop will be exited (or skipped) if the termination condition returns false. Since you're initializing i with 0, i>=a.length (i.e. 0 >= 7) will be instantly false.
Please note, that I've wrote i < a.length and not i <= a.length. The array size is currently set to 7, therefore the valid indices are from 0 to 6. You'll get an ArrayIndexOutOfBoundsException if you try to access index 7.
And you forgot to use your variable n to set the array size:
int[] a= new int[n];
There are few issues:
int[] a= new int[7];//<-- why hard coded?
int[] a= new int[n];// try, you already have array size from user
for(int i=0;i>=a.length;i++)//<-- condition fails, i is 0 for the first time
for(int i=0; i < a.length; i++)//try this
Take a close look at your for loop.
for(int i=0;i>=a.length;i++)
Notice that you are using a greater than sign.
Since i equals 0, the length of a would have to be 0 for this loop to run, and we already know that you declared a with a length of 7.
I would do some searching around because there's plenty of questions similar to this.
Regardless, you have a couple things incorrect. You prompt the user for an array size but then throw it out and use 7 instead:
int[] a= new int[7];
So, this should be:
int[] a= new int[n];
Second, your loop condition:
for(int i=0;i>=a.length;i++)
will be true as long as i is greater than a, which will never happen as long as a is a positive integer (because i starts at zero). So, if we're using less than, we should also remember that arrays are zero indexed, so if you input a value of 3, you only want to populate indexes 0, 1 and 2.
So, this should instead be:
for(int i=0;i < a.length;i++)
Finally, remember to prompt the user, even if this is just a learning exercise it's good practice. Put that all together and you'll get something like this:
public static void main(String args[])
{
Scanner sn=new Scanner(System.in);
System.out.println("Please enter an array size:" );
int n=sn.nextInt();
System.out.println("the array size is "+ n);
int[] a= new int[n];
System.out.println("Please enter your " + n + "array values:");
for(int i=0;i < a.length;i++)
{
a[i]= sn.nextInt();
System.out.println("The value of a[" + i + "] is " + a[i]);
}
sn.close();
System.out.println("Array values are " );
for (int arrayValue : a)
System.out.println(" " + arrayValue);
}
change the below code
for(int i=0;i>=a.length;i++) with for(int i=0;i<a.length;i++)
the condition should be < instead of >=
also use sn.hasNext() can simplify the solution.
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);
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 ] );
}
}