I have to make a Java Program, where a user type in the total numbers of students, so I made this code:
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int numReaders = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of magazin readers:");
numReaders = scan.nextInt();
Now, after adding the total number of students, we should add their names into an array:
//Creating an array of names, where the length is the total number entered by the user
String[] nameStr = new String[numReaders];
int[] ages = new int[numReaders];
for(int i=0; i<numReaders; i++)
{
Scanner n = new Scanner(System.in);
System.out.println("Enter the name of reader: "+i);
nameStr[i] = n.next();
}
After that, we should add correspondingly the age of each name, so I made this portion of code:
for(int i=0; i<numReaders; i++)
{
Scanner a = new Scanner(System.in);
System.out.println("Enter the age of reader: "+i);
ages[i] = a.nextInt();
}
//Display the results
System.out.println("Number of readers is: "+numReaders);
for (int i=0; i<numReaders; i++)
{
System.out.println("The name of reader "+i+" is "+nameStr[i]+ " and his age is "+ages[i]);
}
After making this code, I tested it using Ideone and Command Prompt and it works properly:
Now, I need to call method according to selection of the user:
if he typed 'a' a method should be called to specify the name and the age of the oldest student.
If he typed 'b' a method called to see how many students have an age specified by the user and If he typed 'c', a function called to calculate the average age of them all.
I am new to methods so I don't know how to add arrays into methods and make statements.
Here is the full code:
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int numReaders = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of magazin readers:");
numReaders = scan.nextInt();
//Creating an array of names, where the length is the total number entered by the user
String[] nameStr = new String[numReaders];
int[] ages = new int[numReaders];
for(int i=0; i<numReaders; i++)
{
Scanner n = new Scanner(System.in);
System.out.println("Enter the name of reader: "+i);
nameStr[i] = n.next();
}
for(int i=0; i<numReaders; i++)
{
Scanner a = new Scanner(System.in);
System.out.println("Enter the age of reader: "+i);
ages[i] = a.nextInt();
}
//Display the results
System.out.println("Number of readers is: "+numReaders);
for (int i=0; i<numReaders; i++)
{
System.out.println("The name of reader "+i+" is "+nameStr[i]+ " and his age is "+ages[i]);
}
//Choosing a statistic
//if a:
System.out.println("Please choose a, b or C:");
Scanner stat = new Scanner(System.in);
char X;
X = stat.next().charAt(0);
if(X=='a')
System.out.println(X+X);
else if(X=='b')
//System.out.println(X);
//Scanner newAge = new Scanner(System.in);
//int ageToSearchFor = newAge.nextInt();
//maxAge(ageToSearchFor);
else
System.out.println(X);
}
}
Right, so to start with your user enters an input, for example 'a', so let's go with this:
Firstly, you need to create the method where the name of the oldest student is displayed, so let's call it 'getOldestStudent' - when naming methods this is the typical naming convention, starting lowercase and then moving to uppercase for each new word - try and make them as intuitive as possible.
When making the method signature, you need to give it its visibility and also what it is going to return. In this case, as you are only using one class, we will give it private, so it is only visible by this class.
Now we need to return 2 things, so we can either put these into a string or put them into an array, which is what I would recommend, so we are going to return an array. However, you want to input an array to search through, so this goes in tbe brackets as parameters (or arguments). Therefore our method signature is the following:
private String[] getOldestStudent(String[] students, int[] ages)
Then inside this method, you can simply do the code you need to find the oldest student, add their name and age to the array and then return this.
Need anymore help just drop a comment.
On a side note, you would have been better off creating a 'Student' object and then giving this object a 'name' property and an 'age' property and then simply making an array of students and getters and setters (or accessors and mutators) for these properties.
James Lloyd's covers your question pretty well, I thought I might add some input as I think you are struggling with some principles.
At first, I would do as James advised and create a class Student that stores the values for each person.
public class Student {
public String name;
public int age;
// Constructors allow you to create a new Object and set some variables
// when you create it.
public Student (String name) {
this.name = name;
}
}
I used public to avoid getters and setters for this explanation, but I'd use private most had I to write it by myself.
Anyways, that way you only have to use one instead of two arrays (and name and age are connected with each other, e.g., you know the age of a student you know the name of, whereas with two different arrays it could happen that you don't know if nameArray[0] belongs to ageArray[0].
So you have an array Student[] students = new Student[numReaders]; and you can set each Student after reading the input, i.e., after reading the name you call students[i] = new Student(name); If you want to set the age of a Student afterwards you can do so by using student[i].age = age.
Now that we have filled our array, we can advance to your actual question.
char method;
method = stat.next().charAt(0);
// I think switch is a little easier to read for such cases
switch(method) {
case 'a': Student oldest = getOldestStudent(students);
if (oldest != null)
System.out.println(oldest.name);
break;
case 'b': //another method
break;
default: // equals to else as if none of the other cases was fulfilled
break;
}
Now you can write your own method for each scenario you have to cover.
public Student getOldestStudent(Student[] students) {
// at first we check some cases that do not require further checks
if (students.length == 0) {
System.out.println("No students have been specified");
return null; // this might lead to a NullPointerException so check the return Object whether it is null before doing anything with it
} else if (students.length == 1)
return students[0];
// no we have to see which students if the oldest in the regular case
// the first student will be used for comparison
Student oldestStudent = students[0];
for (int i = 1; i < students.length; i++) {
// see if our current student is older
if (oldestStudent.age < students[i].age)
oldestStudent = students[i];
}
return oldestStudent;
}
This way you can easily access the Students name afterwards (see above in the switch). You can build all your methods like this by passing the array to the methods and iterating through it. Depending on whether you want to return one or more Students (as it might vary between the different methods) you have to change the return type from Student to Student[].
Related
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
}
}
I'm in a Java class and I'm having extreme difficulty getting started on the assignment. I do not want the answer but I really would appreciate any and all help on getting going and a basic outline of what to do.
A supermarket wants to reward its best customer of each day, showing the customer’s name on a screen in the supermarket. For that purpose, the customer’s purchase amount is stored in an ArrayList<Double> and the customer’s name is stored in a corresponding ArrayList<String>.
Implement a method
public static String nameOfBestCustomer(
ArrayList<Double> sales,
ArrayList<String> customers)
that returns the name of the customer with the largest sale.
Write a program that prompts the cashier to enter all prices and names, adds them to two array lists, calls the method that you implemented, and displays the result. Use a price of 0 as a sentinel.
You can use a Scanner to get the values that the cashier enters (an int for the purchase amount and a String for the customer's name, use conditions and throw exceptions to guarantee the values' types). Those values are put in two ArrayList (Lists of Integer and String).
Once the supermarket closes, you can use a loop on the list of purchases amounts to find the max purchase amount and its position in the list and use this position to find the best customer in the other list.
This is what you can do :
package com.assignments;
import java.util.ArrayList;
import java.util.Scanner;
public class MaxSalesCustomer {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<String> customerNameArray = new ArrayList<String>();
ArrayList<Integer> customerSalesValue = new ArrayList<Integer>();
String continueAdding = "Y";
Scanner sc=new Scanner(System.in);
while(continueAdding.equals("Y")){
System.out.println("Please Enter the customer Name:");
String name = sc.next();
customerNameArray.add(name);
System.out.println("Please Enter the sales value:");
Integer sales = sc.nextInt();
customerSalesValue.add(sales);
System.out.println("Do you want to continue 'Y/N' ?" );
continueAdding = sc.next();
}
String maxSalesCustomerName = getMaxSalesCustomerName(customerNameArray,customerSalesValue);
System.out.println(maxSalesCustomerName);
}
public static String getMaxSalesCustomerName(ArrayList<String> customerNameArray,ArrayList<Integer> customerSalesValue){
Integer maxValue = 0;
String maxSalesCustomerName = new String();
for (int i = 0; i < customerSalesValue.size(); i++){
if (maxValue < customerSalesValue.get(i)){
maxValue = customerSalesValue.get(i);
maxSalesCustomerName = customerNameArray.get(i);
}
}
return maxSalesCustomerName;
}
}
I am trying to create a program for an assignment in Java and are looking for a push in the right direction. I am currently taking the class online so asking a teacher for help is not an option for me.
I am trying to create a simple java program that allows a user to enter their first name and last name, and their requested seat number. If the seat is taken, the program is supposed to find the nearest available seat. So far I have succeeded at getting all the input from the user (albeit in a roundabout way) and creating and printing an array.
Question
Can I store boolean values in an array? I just want to store false if the seat is taken and then have and if else statement test for true or false, and store a false if the value returned is true(very confusing but thats my train of thought) is there an easier way to go about this? Also how would I also store the persons first and last name with that boolean value? Do I have to create a seperate array? I have attached my code so far that succeeds in getting the user info and printing out an array.
//Import scanner and arrays
package airlinereservations;
import java.util.Scanner;
import java.util.Arrays;
public class AirlineReservations {
public static void main(String[] args) {
//Print the header
System.out.println("___________________________________");
System.out.println("|WELCOME TO FLY BY NIGHT AIRLINES!|");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
// Promt user for first and last name
System.out.println("Please enter your first name:");
Scanner scan= new Scanner(System.in);
String first = scan.nextLine();
System.out.println("Please enter your last name:");
String last = scan.nextLine();
//Greet the user
System.out.println("Hello! " + first + " "+ last);
//Get the requested seat
System.out.println("Please enter your requested seat row number 1-9:");
int rowz = scan.nextInt();
System.out.println("Please enter your requested seat column number 1-4:");
int colz = scan.nextInt();
//Tell the user if the seat is already taken
if(int rowz == rowz, System.out.println("This seat is already taken!"));
else(return true);
//Print out the array
int[][] Seating= new int[9][4];
for(int row=0; row<Seating.length; ++row){
for(int col=0; col<Seating[row].length; ++col){
Seating[row][col] = (row + col) % 9 + 1;
for(int ro=0; ro<Seating.length; ++ro);
}
System.out.println();
for(int col=0; col<Seating [row].length; ++col)
System.out.print(Seating[row][col]);
}
System.out.println();
}
}
For a push in the right direction, as you said, I see two quick options to consider:
One would be to add a Map. This would allow you to store a bunch of key-value pairs which you could use to represent seats, and whether or not they are taken.
Another option is to create a Seat class, that has a field for seatName and whether or not it is taken, and you could create an Array of these seat objects.
If you don't know where to begin on implementing either of those, I will help you, but I challenge you to at least try implementing one or the other first.
EDIT
Or, even more simply, you could create a two-dimensional array holding strings, like this:
String[][] seats = new int[numberofseats][2];
seats[0][0] = "Seat Number 1";
seats[0][1] = "true";
And you can force that second dimension to only hold values true or false, and later check them like this:
if(seats[0][1].equals("true")) // Then seat number 1 is taken
This might not be the best solution as far as error handling, but it is a possibility.
EDIT 2 If you were to create a seat class, I would set it up like this:
public class Seat{
private String seatName;
private boolean isTaken;
public Seat(String s, boolean t){
this.seatName = s;
this.isTaken = t;
}
public boolean isSeatTaken(){
return this.isTaken;
}
}
Then, later you can do something like this:
ArrayList<Seat> myArrayList = new ArrayList<Seat>(); // Or a regular array if you prefer
// Add elements
// Below checks if first seat in list is taken
boolean firstSeatTaken = myArrayList.get(0).isSeatTaken();
I need to check the array to see if the user input is already present, and display a message as to whether it is or isn't there. The first part is working, but I tried to create a method for the word check, and I'm not sure if I'm on the right path or not, cheers.
import java.util.Scanner;
public class InputLoop {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String array[] = new String[10];
int num = array.length, i = 0;
System.out.println("Enter a word");
for (i = 0; i < num; i++) {
while (scan.hasNextInt()) // while non-integers are present...
{
scan.next(); // ...read and discard input, then prompt again
System.out.println("Bad input. Enter a word");
}
array[i] = scan.next();
WordCheck();
}
}
public void WordCheck(String[] i) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter another word");
if (scan.next().equals(array[i])) {
System.out.println("The word has been found");
} else {
System.out.println("The word has not been found");
}
}
}
Right. You've clearly gone down a bad thought process, so let's just clear the slate and have a re-think.
Step one: You want to take some user input
Step two: Compare it with all previous user inputs to see if it's present.
If it is present, return a message indicating that value has been inputted.
otherwise ignore the input and continue execution
Repeat step one.
The solution
So, let's review what you've got, and how you need to change it.
public static void main(String[] args)
If I were you, I would avoid calling methods directly from here. If you do, every method will need to be static, which is a pointless adjustment in scope for the functionality of your class. Create a new instance of your class, inside the main method, and move this code to the class' constructor. This will remove the need to make every single method static.
Scanner scan = new Scanner(System.in);
String array[] = new String[10];
Okay, so you've created a scanner object that takes input from the System.in stream. That's a reasonable thing to do when taking input from the keyboard. You've also created an array to contain each item. If you only want the user to be able to type in 10 values, then this is fine. Personally, I would use an ArrayList, because it means you can take in as many user inputs as the user desires.
Secondly, you want a function to compare the input, with all other inputs. What you have at the moment clearly isn't working, so let's have another go at it.
You will need some input, userInput, and a collection to compare it against, allInputs.
allInputs needs to be accessible from any point in the program, so it's probably wise to make it into a field, rather than a local variable.
Then, because you're comparing userInput against all values, you're going to need a foreach loop:
for(String s : allInputs)
{
if(s.equals(userInput))
{
// Output message code.
}
}
Now the trick is fitting this inside a loop that works with this program. That is up to you.
One simple solution is to use a Set:
Set<String> words = new HashSet<String>();
Add words with the add() method and check if a word is already added with contains(word) method.
EDIT
If you must use Arrays you can keep the array sorted and do a binary search:
Arrays.sort(words);
boolean isAlreadyAdded = Arrays.binarySearch(words, newWord) >= 0;
You're going to have to loop through the entire array and check if scan.next() equals any of them - if so return true - as such:
String toCheck = scan.next();
for (String string : i) { //For each String (string) in i
if (toCheck.equals(i)) {
System.out.println("The word has been found");
return;
}
}
System.out.println("The word has not been found");
This supposes you call WordCheck(), passing the array to it - this method also has to be static for you to call it from the main() method.
You can use the arraylist.contains("name") method to check if there is a duplicate user entry.
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();
}
}