I'm trying to take an input from the user for the array size and then ask the user for the array contents. This part seems to work fine but the outprint isn't working. It out prints 0's for the marks. Thanks for any help provided.
public static void getExamMarks()
{
int x,mark;
System.out.println("Please enter the number of exam marks: ");
x=Keyboard.readInt();
int javastudents[]=new int[x];
for (int i=0;i<javastudents.length;i++)
{
System.out.println("Please enter an intiger for the mark: ");
mark=Keyboard.readInt();
}
printArray(javastudents);
}
public static void printArray(int [] javastudents)
{
for (int i=0;i<javastudents.length;i++)
{
System.out.println(javastudents[i]);
}
}
You are reading the value from the keyboard into the mark variable, but you are not using the mark variable anymore afterwards. At the same time, you are not storing anything into your javastudents array, so all array elements remain at their initial value of 0. Hence, when printing the array later, you get all 0's.
You need to store the read value into your array, like
...
mark = Keyboard.readInt();
javastudents[i] = mark;
...
In fact, you do not need the mark variable at all and you can do
...
javastudents[i] = Keyboard.readInt();
...
Related
I want to create a method that returns a double array of user input values. I've figured out how to create a method to ask the user to pick how many elements an array should hold, then pass off the size to next method, which is to spit out a double array of user's input values.
My goal here is to practice learning how to use basic methods (just public static methods) to divide and conquer the problem at hand.
...java
package array_exercises;
import java.util.Scanner;
public class Array_Exercises {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// Get number of elements to store values from the user
int number = numOfElements();
System.out.println(valueOfElements(number));
}
public static int numOfElements () {
// Create a Scanner object to get the user's input
Scanner input = new Scanner (System.in);
// Get the input from the user
System.out.print("Enter how many number of the type double do you want"
+ " to store in your array? ");
return input.nextInt();
}
public static double[] valueOfElements (int num) {
// Create a Scanner object to get the user's value for each element
Scanner input = new Scanner (System.in);
// Declare an array of doubles
double[] double_array = new double[num];
// Loop through the elements of double array
for (int i = 0; i < double_array.length; i++) {
System.out.print("Enter a value #" + (i + 1) + ": ");
double_array[i] = input.nextDouble();
}
return double_array;
}
}
The expected output should print out all values of the double array in the main method.
All I got was this:
run:
Enter how many number of the type double do you want to store in your array? 2
Enter a value #1: 1.234567
Enter a value #2: 2.345678
[D#55f96302
Why is this? What am I doing wrong here? I'm only a beginner, I'm taking a class on Java this semester, so everything is new to me.
An array is an object in java and therefore it is printed by calling its toString() method. This method is not very helpful for the array class and doesn't print the arrays contents. To print the array content you can call Arrays.toString(yourArray) which will return a string representation of the array contents.
You should replace
System.out.println(valueOfElements(number));
with
System.out.println(Arrays.toString(valueOfElements(number)));
and add the following import statement:
import java.util.Arrays;
First you have to understand that in java an array variable is a reference. This means that when you try an print out an array variable, it prints out a memory address, not elements of the array. The way to fix your issue is to save the return value of the function into the array, and then for loop through every element in the array.
double[] values = valueOfElements(number);
for(int i = 0; i < values.length; i++){
System.out.println(values[i]);
}
The [] dereferences the double, so you are accessing the double value, and not the memory address value.
I am trying to generate an arraylist in java by first inputting the default size desired of the said arraylist. Then I want to get the user to input the string to fill the arraylist. I have made one that almost works. The only problem is that for some reason I get a default value at the start.
For example, if I set the list length to 3 the list returned is: [,example,value,here]. I understand a value of 3 means 4 values in a list but I feel like that just doesn't look too nice. The problem I think lies in the way I set the size of the list but I don't see any other way.
When I set the list value manually in the for loop I don't get this problem. It only happens when I want the user to input the length. Where is the small error?
import java.util.*;
public class ListsPractice {
public static void main(String[] args) {
Scanner userin = new Scanner(System.in);
System.out.println("Enter length of desired list: ");
int lenlist = userin.nextInt();
ArrayList list1 = new ArrayList();
for(int counter = 0; counter <= lenlist; counter++) {
System.out.println("Enter an element: ");
String value=userin.nextLine();
list1.add(value);
}
System.out.println("the result is: "+list1.subList(1, lenlist+1));
}
}
I have an issue for creating an array based on the total amount of numbers entered into the array.
Essentially the program is expected to work as the following: the user is prompted for n numbers to enter into an array. So until the user types '000' as their input, the user will be prompted for a new number.
Note: for this array, I do not want the user to input the amount of numbers they want to enter for the array size. Instead, I want the user to continue inputting random numbers until '000' has been inputted, then, the total amount of numbers that has been entered into the array, is the size of such array.
For example: this would work if we have int array[] = {1, 2, 4, 6}, this will automatically set array size to 4, without actually explicitly declaring the array size as 4 elements. Similarly, with my code, I want it where the numbers that the user enters is added to the array, and then the array size is automatically given from the amount of numbers the user has entered like above.
It is important to note that we do not know the length of the array until the user has entered all n numbers.
I have attempted a skeleton, but it returns a cannot find symbol error:
Code:
//Array Code
import java.util.*;
class setArray {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int stopInput = 000;
int number;
System.out.print("Enter a number: ");
number = input.nextInt();
while(number != stopInput) {
System.out.print("Enter a number: ");
number = input.nextInt();
int array[] = {number};
}
System.out.print("Array size: " + array.length);
} // Main brace
} // Class brace
setArray.java:19: error: cannot find symbol
System.out.print("Array Size: " + array.length);
symbol: variable array
location: class setArray
1 error
You have a few errors here. The first is understanding why you get your immediate error. The variable array is declared within the scope of the while loop. It can not be seen outside of this loop. That is why the compiler is complaining.
The second is that the size of the array (if declared outside of the loop) will always be 1. From my understanding of what you have written as an attempt to solve the problem you have describe shows that you are not tackling the problem correctly.
While you don't known the the final length of the array to be entered; you do need to store the values entered (my inference) to populate the final array. To store the value entered by the user you need a list that will grow with the input.
List<Integer> values = new ArrayList<>();
while (number != stopInput) {
System.out.print("Enter a number: ");
values.add(Integer.valueOf(input.nextInt()));
}
Integer[] array = values.toArray(new Integer[values.size()]);
Firstly, the compilation error is because the array variable is not visible from the System.out.println line. This is because it's declared inside the while loop, so is only visible inside the while loop.
To make it visible to the whole method, declare it before the while loop.
Secondly, arrays cannot be resized. You declare an array to be a certain size, and you cannot add or remove elements.
My suggestion would be to use an ArrayList. Declare one before your loop, and add the new number inside the loop. After the loop, the size should be how many numbers were entered.
Finally, there's no difference between 000 and 0. Is 0 a valid input number?
You can use
List<Integer> array=new ArrayList<Integer>();
while(number != stopInput) {
System.out.print("Enter a number: ");
number = input.nextInt();
array.add(number);
}
This sounds like a job for java.util.ArrayList - this is the array that doesn't have a fixed size and is growing as you add values to it automatically under the covers.
The error is caused because you are creating the array only within the scope of the while loop. You need to create it outside the loop. Secondly, standard arrays are not dynamic, so you would need to either set the size and increase it as needed, or just simply use an ArrayList.
Psuedo:
ArrayList<Integer> list = new ArrayList<Integer>()
...
while(not stop number)
list.add(number)
...
print(list.size())
If you really want to use an Array, here is how you can do it
public static void main(String[] args){
STOP_ENTRY = "000";
scan = new Scanner(System.in);
entry = "";
while(true){
System.out.print("Enter #: ");
String tempS = scan.nextLine();
if(tempS.equals(STOP_ENTRY)) break;
else entry += tempS + ":";
}
String[] split = entry.split(":");
int[] intArray = new int[split.length];
System.out.println("Length of created intArray = " + intArray.length); //length of created array
for(int i = 0; i < intArray.length; i++){
intArray[i] = Integer.parseInt(split[i]);
System.out.println("intArray[" + i + "] => " + String.valueOf(intArray[i]));
}
}
I would recommend an ArrayList, as it dynamically changes is size when you add an element, but do whatever you'd like.
An important note, this does not handle any malicious entry that you might not want (characters, symbols), and will error if they are entered, something you can easily add if you need
I am making a program that prompts the user for 3 integers and prints out the biggest one chosen. I am stuck with 2 problems at the moment. I would like to know how I can make the program so that the user can only choose integers from the array. I would also like to know how to find and print out the biggest integer from the ones that the user chose. I'm quite new to programming so all feedback is appreciated.
Thanks!
import java.util.Scanner;
public class Lab14C // name of class file
{
public static void main(String [] args)
{
int[] array = {0,1,2,3,4,5,6,7,8,9};
for(int i=0; i<array.length; i++)
{
System.out.print(array[i] + " ");
}
System.out.println("\n");
Scanner array1 = new Scanner(System.in);
System.out.println("What is your first integer? ");
double array11 = array1.nextInt();
Scanner array2 = new Scanner(System.in);
System.out.println("What is your second integer? ");
double array22 = array2.nextInt();
Scanner array3 = new Scanner(System.in);
System.out.println("What is your third integer? ");
double array33 = array3.nextInt();
System.out.println("\n");
}
}
I don't think there is a way to force a user to input an element. Few things you could do is :
Tell the user he has to select a number in a particular range.
Keep the input statement in a loop. If the entered element exists in array , go ahead. Else tell the user to enter again.
Printing the biggest integer can be done using Math.max(double,double) function. For three elements you can try System.out.println("Max of three is "+Math.max(array11,Math.max(array22,array33)))
You can do it yourself if you want instead of built in function like:
if(array1>array2&&array1>array3)
//print max as array1
else if(array2>array1&&array2>array3)
//print max as array2
else //print array3 as max
Also change your element types to int as you are reading integer.
1) There is no need to create a new Scanner all the time.
Just create one Scanner (which I would just call input or scanner or something that makes sense).
2) If you're reading int's why are you storing them in doubles?
3) To check for a certain condition you use if(*condition*) { /*do something */ }. So if you want to check if x is smaller than y you do if(x < y) { /* do something */ }. (In your case you'll want to check if current input is greater than biggest input and if so set the biggest input to current input.)
4) For a sorted array you can use Arrays.binarySearch(array, elementToSearch) which will return the index of the element when found, or a negative number if not found (the negative number is (-(insertionPoint)-1)). (So you can check if the number entered by the user is in the array and keep asking for a new number if is not.)
1) How I can make the program so that the user can only choose integers from the array.?
You are declaring array variable as int[] so it stores only integer values. Whenever you retrives the value from this array, it returns int value only so you don't have to worry about it.
2)how to find and print out the biggest integer from the ones that the user chose.?
To find the maximum or minimum from a set of values, Java provide a function name Math#max(). You can use it like this :
int maxValue = Math.max(Math.max(array11,array22),array33);
Here is the doc for Math library.
I am doing java programming practice from a website. I have to display this out put using arrays.
Enter the number of students: 3
Enter the grade for student 1: 55
Enter the grade for student 2: 108
Invalid grade, try again...
Enter the grade for student 2: 56
Enter the grade for student 3: 57
The average is 56.0
This is my source code so far, it is raising error The local variable grades may not have been initialized. How do I recover this? I have to make this program using arrays.
package array;
import java.util.Scanner;
public class GradesAverage {
public static void main(String[] args) {
int numStudents = 0;
int[] grades;
Scanner in = new Scanner(System.in);
System.out.print("Enter number of students : ");
numStudents = Integer.parseInt(in.next());
for (int i = 0; i < numStudents; i++) {
System.out.print("Enter grade of student "+i+" :");
grades[i] = Integer.parseInt(in.next());
}
}
}
When you write
int[] grades;
you declare a variable called grades, that can hold a value of type int[]. However, before you can use it you also have to initialize it, eg create the actual data structure. This is done like this:
int[] grades = new int[numStudents];
Note that you need to know the size beforehand when you declare an array, so you will have to move the creation of the array to just before the for loop.
All variables declared in methods have to be assigned a value before you read them to avoid trash values.
Also in java arrays are objects, that means that you have to create an array instance with new and assign it to grades before you can store anything in it.
grades = new int[numStudents];
An array doesn't have a constant memory allocation, therefor you must allocate memory to the new array.
for example
int[] grades = new int [numStudents]
This of course should be written only after you know the value of numStudents
There's not much to add to what Keppil already said, but I'd like to add a little 'why'.
You see, when int[] grades is created, it is nothing but an 'empty pointer', pointing to a random location in memory.
By assigning the return value of 'new int[numGrades]', the value of the pointer points to the location in memory, which has been assigned. This memory is in the exact size of 'size of an integer multiplied by the number of grades', and can be accessed safely.
If this array is dimensioned too small (or not at all), a memory violation exception usually gets triggered, because you're writing memory you have no access to, often causing your program to crash or other undefined behavior.
Please remember: Arrays are different from normal variables.
So yeah, to make it short:
grades = new int[numGrades]; is what you're looking for.
Straight below the line, where you're parsing the the input number of students.
As an additional advice: User input is ALWAYS a source for error.
Make sure to include error handling for invalid output. (For example if some wiseguy decides to input 'John Smith' instead of a grade.
You have to initialise variable before its usage.
Please see one of correct version of your code:
package array;
import java.util.Scanner;
public class GradesAverage {
public static void main(String[] args) {
int numStudents = 0;
int[] grades;
Scanner in = new Scanner(System.in);
System.out.print("Enter number of students : ");
numStudents = in.nextInt();
// this line was added
grades = new int[numStudents];
for (int i = 0; i < numStudents; i++) {
System.out.print("Enter grade of student "+i+" :");
grades[i] = Integer.parseInt(in.next());
}
// closing used resources is a good practice
in.close();
}
}