I am new to learning about parallel arrays and want to know how to effectively print content/elements using parallel array only, I tried but couldn't get it to work and function the way I want.
The task is: The program inputs an integer from the user representing how many peoples’ information will be entered. Then, the program inputs the information one person at a time (name first, then age), storing this information in two related arrays.
Next, the program inputs an integer representing the person on the list whose information should be displayed (to get information for the first person, the user would enter ‘1’). The program makes a statement about the person’s name and age.
Although I got the name and age to work until the integer the user inputs, but after that I am not sure how to do
Sample input:
4
Vince
5
Alexina
8
Ahmed
4
Jorge
2
2 // I am confused about this part, how would I make it so that it prints the desired name,
//for example with this input, it should print:
Sample output:
Alexina is 8 years old
My code:
import java.util.Scanner;
class Example {
public static void main (String[] args) {
Scanner keyboard = new Scanner(System.in);
int[] numbers = new int[keyboard.nextInt()];
for (int x = 0; x < num.length; x++){
String[] name = {keyboard.next()};
int[] age = {keyboard.nextInt()};
}
int num2 = keyboard.nextInt();
System.out.println(); // what would I say here?
}
}
You need to rewrite your code so your arrays aren't being assigned within the loop. You want to add values to the arrays, not reset them each time, and you want to be able to access them afterwards. Below is a modified version of your code:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int num = keyboard.nextInt();
keyboard.nextLine(); //you also need to consume the newline character(s)
String[] name = new String[num]; //declare the arrays outside the loop
int[] age = new int[num];
for (int x = 0; x < num; x++){
name[x] = keyboard.nextLine(); //add a value instead of resetting the array
age[x] = keyboard.nextInt();
keyboard.nextLine(); //again, consume the newline character(s) every time you call nextInt()
}
int num2 = keyboard.nextInt() - 1; //subtract one (array indices start at 0)
System.out.println(name[num2] + " is " + age[num2] + " years old"); //construct your string with your now-visible arrays
}
As I think you have to think about the local and global variable usage in java.In brief,
Local variables can only use within the method or block, Local variable is available only to method or block in which it is declared.
For example:
{
int y[]=new Int[4];
}
this y array can be accessed within the block only.
Global Variable has to be declared anywhere in the class body but not inside any method or block. If a variable is declared as global, it can be used anywhere in the class.
In your code you try to create arrays and use them out of the For loop. But your arrays are valid only inside the For loop. After every loop runs all info is lost.there will be new array creation for every iteration of For loop.
therefore, In order to access and save the information you have to declare your arrays before the For loop and access and store data using iteration number as the index. finally, to print the data you gathered, you have to scan new input as integer variable.then you can access your arrays as you wanted.
//For example
int [] age=new int[4]; //global -Can access inside or outside the For loop
int[] numbers = new int[keyboard.nextInt()];
for (int x = 0; x < 4; x++){
age[x] = keyboard.nextInt(); //Local
}
int num2 = keyboard.nextInt();
System.out.println(age[num2]); // Here you have to access global arrays using num2 num2
}
}
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 new to JAVA and this is what I have to do:
Accept a set of marks (out of 100). The user should press the Enter button after each mark is entered and the mark should then be added to an ArrayList of Integers.
This is what I have so far:
int score = Integer.parseInt(marksinput.getText());
ArrayList<Integer> marks = new ArrayList();
Collections.addAll(marks, score);
String out = "";
String Out = null;
int[] studentmarks = {score};
for (int item : studentmarks) {
marksoutput.setText(""+item);
}
if (score > 100) {
marksoutput.setText("Enter marks\n out of 100");
}
This only adds one mark in the arraylist and I need user to input as many marks he wants. I know that my arraylist is wrong, which is why it only takes 1 number but I do not know how to make all the input numbers go in arraylist. What I have is that it takes the number and if user inputs another number, it just replaces the older number. I want it to display both the numbers not just one. Any help is appreciated and thank you in advance!☻☻
(This is not a duplicate even though others have the same title)
In case what you are after is a program that adds any integer typed by the user into an ArrayList, what you would have to do is the following:
Scanner scanner = new Scanner(System.in);
List<Integer> ints = new ArrayList<Integer>();
while(true)
ints.add(scanner.nextInt());
What this program will do, is let the user input any number and automatically puts it into an ArrayList for the user. These integers can then be accessed by using the get method from the ArrayList, like so:
ints.get(0);
Where the zero in the above code sample, indicates the index in the ArrayList from where you would like to retrieve an integer.
Since this website is not there to help people write entire programs, this is the very basics of the ArrayList I have given you.
The ArrayList is a subclass of List, which is why we can define the variable using List. The while loop in the above example will keep on going forever unless you add some logic to it. Should you want it to end after executing a certain amount of times, I would recommend using a for loop rather than a while loop.
Best regards,
Since it seems you are really new,
What you are looking for is a for-loop
From the Java documentation, he is the syntax of a for-loop in Java
for (initialization; termination; increment) {
statement(s)
}
Initialization: Obviously you want to start from 0
Termination: you want to stop after 100 inputs, so that's 99 (starting from zero)
Increment: you want to "count" one by one so count++
for(int counter = 0; counter < 100; counter++) {
//Ask user for input
//read and add to the ArrayList
}
So before you enter the for-loop you need to initialize the ArrayList, and a Scanner to read input:
Scanner sc = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList();
for(int counter=0; counter < 100; counter++) {
System.out.println("please enter the " + counter + " number");
int x = sc.nextInt();
list.add(x);
}
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();
}
}