Java noob here. My instructor told me specifically to "instantiate the scanner INSIDE the constructor". The problem is, i am not seeing a constructor in our ScannerLab class. Nor am i seeing any inheritance. I have a field named scan which is of type java.util.Scanner that i need to use. How do i instantiate the scanner inside the constructor?
code:
public class ScannerLab {
private java.util.Scanner scan;
public void echoStrings() {
String word;
// create a new storage array
String[] myList = new String[5];
// set for loop
for(int i = 0; i < 5; i ++) {
// prompt for the value
System.out.print("Enter word " + i + ": ");
// get the input value
word = scan.next();
// echo the input value
System.out.println("You entered " + word);
// store the input value into the array
myList[i] = word;
}
String line = "";
// loop through the array and concatenate the values
// put a space between the words
System.out.println("The words you entered are: " + line);
System.out.println("list is" + myList);
}
public void echoIntsAndTotal() {
int inputValue;
// declare an array to hold the 5 values
for(int i = 0; i < 5; i ++) {
// prompt for the value
System.out.print("Enter integer value " + i + ": ");
// get the input value
inputValue = 23;
// echo the input value
System.out.println("You entered " + inputValue);
// store the input value into the array
}
int total = 0;
// loop through the array and add the values
System.out.println("The total of your values is " + total);
}
public static void main(String[] args) {
ScannerLab lab;
lab = new ScannerLab();
lab.echoStrings();
// lab.echoIntsAndTotal();
}
}
i have tried:
setting the scan field as a reference variable to:
private java.util.Scanner scan = new java.util.Scanner(System.in);
then in my application method i used:
public static void main(String[] args) {
ScannerLab lab;
lab = new ScannerLab(scan);
didnt work. The only way it would compile and run is if i switch my field to:
private static java.util.Scanner scan = new java.util.Scanner(System.in);
but he wont allow us to use static fields, and that is still not being instantiated inside the constructor.
where is the constructor, and how do i instantiate a new scanner in it?
Thank you
If there is no constructor in your class yet, you have an implicit default constructor available (see this question too). You can choose to override it at any point:
public class ScannerLab {
public ScannerLab() {
scan = new java.util.Scanner(System.in);
}
...
}
From https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html:
The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass.
How about writing a constructor then?
// Constructor
public ScannerLab() {
scan = new java.util.Scanner(System.in);
}
Other than that, this line
System.out.println("list is" + myList);
doesn't work. It will give you the class name and hashcode, since that is the default implementation.
Try something like this:
System.out.println("\nThe words you entered are:");
System.out.println(Arrays.toString(myList));
which will give you an output like:
The words you entered are:
[apple, banana, carrot, dududu, elephant]
Related
I am stuck on how to call my method.
I get a cannot find symbols (playerName,battingArray) error message.
-Am I not calling it correctly?
-Is the method set up to populate the arrays properly?
I am not even sure if this is the best way to go about doing this.
ANY HELP IS SO GREATLY APPRECIATED!!
//Import util to accept input
import java.util.Scanner;
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
//Assign number of players to variable and call method readNumPlayers
int numPlayers = readNumPlayers();
System.out.println(numPlayers);
//Call readData method
readData(playerName, numPlayers, battingArray);
}//end main
//readNumPlayers method
public static int readNumPlayers() {
System.out.println("Number of players: ");
int numPlayers = input.nextInt();
if (numPlayers <=0) {
System.out.println(" Error- Try again ");
System.out.println("Number of players: ");
numPlayers = input.nextInt();
}//end catch to ensure entry is positive integer
return numPlayers; //return
}//end readNumPlayers
//readData method
public static void readData(String[] playerName, int numPlayers,
double[] battingArray) {
playerName = new String[numPlayers];
System.out.println("Enter player's last name: ");
for (int i = 0; i < playerName.length; i++) {
playerName[i] = input.next();
} //end for loop
battingArray = new double[numPlayers];
System.out.println("Enter player's batting average: ");
for (int i = 0; i < battingArray.length; i++) {
battingArray[i] = input.nextDouble();
}// end for loop
}//end readData
}
When you pass the arrays as parameters the caller of readData is supplying references to the arrays to fill in, and, while you can affect the contents of the array referenced you can't change the reference itself — so you should not allocate arrays in your method - for example, your line:
battingArray = new double[numPlayers];
When you allocate a new array and fill that in, the caller has no access to that array, and you have not put anything in the array that the caller passed (and does have access to)
Just use the double[] battingArray parameter that the caller passed in.
Here are two versions of a very simple example; in the first the readData method allocates it's own array and fills it in. You'll see that when main prints the array content you get null because the array filled by readData is not the same array that was passed.
In the second, readData just puts values into the array that the caller passed.
First:
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
int count = 2;
String[] names = new String[count];
double[] avgs = new double[count];
readData(names, avgs, count);
System.out.println("names[0] in main: " + names[0]);
}
public static void readData(
String[] playerNames,
double[] battingAvg,
int numPlayers
)
{
Scanner in = new Scanner(System.in);
// allocating a new array
String[] playerNames2 = new String[numPlayers];
for (int i = 0; i < numPlayers; i++)
{
System.out.print("Players name: ");
String line = in.nextLine();
// putting the value into the newly allocated array
playerNames2[i] = line.trim();
}
System.out.println("playerNames2[0] in readData: " + playerNames2[0]);
}
}
Second:
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
int count = 2;
String[] names = new String[count];
double[] avgs = new double[count];
readData(names, avgs, count);
System.out.println("names[0] in main: " + names[0]);
}
public static void readData(
String[] playerNames,
double[] battingAvg,
int numPlayers
)
{
Scanner in = new Scanner(System.in);
// no array allocated this time
for (int i = 0; i < numPlayers; i++)
{
System.out.print("Players name: ");
String line = in.nextLine();
// put the value into the array that was passed
playerNames[i] = line.trim();
}
System.out.println("playerNames[0] in readData: " + playerNames[0]);
}
}
Since the caller is telling you how big the arrays are (numPlayers parameter), let's say "10", if the caller's arrays aren't actually big enough (say they did new String[5]) it's possible that you get an ArrayIndexOutOfBoundsException, so readData would probably want to catch that and return without finishing the loop.
(I've created a Java repl where you can see version 2)
I'm brand new to Java, and also new to this site, so please go easy on me. :)
I'm attempting to write a program which will ask the user for several pieces of information. After gathering the information from the user, I then need to call another method to print the information back to the console screen.
The problem that I'm having is that my final method to reprint all of the information to the screen is a wreck, and I don't know where to start to fix it. I ran my code prior to writing and calling the final method (printToScreen), and the program worked as expected with no errors or anomalies. Code is below, and I really REALLY appreciate any assistance.
import java.util.*;
public class Program5 {
//Create constants
public static final int TOTAL_SEATS = 50;
public static Scanner console = new Scanner(System.in);
public static void main (String[] args) {
//Create variables and objects
String courseCode, courseName;
int studentsReg;
int openSeats;
//Call method to print three lines of 55 asterisks to screen
screenBreak();
//Call method to prompt the user for input
promptCodeName();
//Call method to ask for pre-requisites
getPrereqs();
//Call method to ask how many students are currently registered
numStudents();
screenBreak();
printToScreen();
}//Close the main method
public static void screenBreak() {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 55; j++) {
System.out.print("*");
} //Close inner for loop
System.out.println();
} //Close outer for loop
} //Close screenBreak method
public static void promptCodeName() {
String courseCode, courseName;
System.out.print("Please enter the course code: ");
courseCode = console.nextLine();
System.out.print("Please enter the course name: ");
courseName = console.nextLine();
}//close promptCodeName method
public static void getPrereqs() {
int numPrereqs;
String listPrereq;
System.out.print("How many pre-requisites does the course have? ");
numPrereqs = console.nextInt();
console.nextLine();
for (int i = 1; i <= numPrereqs; i++) {
System.out.print("List Pre-requisite #" + i + "? ");
listPrereq = console.nextLine();
}//Close for loop
}//Close getPrereqs method
public static void numStudents() {
int studentsReg;
System.out.print("How many students are currently registered for this course? ");
studentsReg = console.nextInt();
}//Close numStudents method
public static int calcAvail (int seatsTaken) {
return (TOTAL_SEATS - seatsTaken);
}//Close calcAvail method
public static void printToScreen () {
String courseCode = console.nextLine;
String courseName = console.nextLine;
numPrereqs = console.nextLine;
int studentsReg = console.nextInt;
String listPrereq = console.nextLine;
System.out.println(courseCode + ": " + courseName);
System.out.print("Pre-requisites: ");
for (int i = 1; i <= numPrereqs; i++) {
System.out.print(listPrereq);
}//Close for loop
System.out.println("Total number of seats = " + TOTAL_SEATS);
System.out.println("Number of students currently registered = " + studentsReg);
openSeats = calcAvail(studentsReg);
System.out.println("Number of seats available = " + openSeats);
if (openSeats >= 5) {
System.out.println ("There are a number of seats available.");
}//Close if loop
else {
if (openSeats <= 0) {
System.out.println ("No seats remaining.");
}//Close if loop
else {
System.out.println ("Seats are almost gone!");
}//Close else
}//Close printToScreen method
}//Close Program5 class
Your problem is becouse courseCode, courseName are local variables which means they are only available in this promptCodeName (for example ofc) method.
If You want to store informations from user in variables, u should create fields in Your class and store informations user in it.
So create fields at the beginning of class (e.q. private String courseCode;)
and then, method should looks like that:
public static void promptCodeName() {
String courseCode, courseName;
System.out.print("Please enter the course code: ");
courseCode = console.nextLine();
this.courseCode = courseCode;
System.out.print("Please enter the course name: ");
courseName = console.nextLine();
this.courseName = courseCode;
}
Read more about "this" word, i think it will let You understand this. :)
Don't forget about scope of your variables. For example in method promptCodeName() you declare local variables courseCode and courseName and assign them to input from console, but you never use this variables (their values). So you have to declare class variables (in the same way as TOTAL_SEATS and scanner) and assign respective values to them or use your local variables from main method, but in this case you have to send them to respective methods as method parameters.
I want to know how I can loop a new object within the same class, so that I can repeat the code to have several different objects with different details entered via the Scanner class.
It will probably make sense if I show what I am trying to do:
public class Students
{
private String studFirstName; // Student's first name
private String studSurname; // Student's surname
private String courseName; // Course name
public Students(String sFirstName, String sSurname, String cName)
{
studFirstName = sFirstName;
studSurname = sSurname;
courseName = cName;
}
public String getStudFirstName() // Getter for student's first name
{
System.out.println("Enter in student's first name: "); // Prompts end user for input
Scanner In = new Scanner(System.in); // Creating a new object
studFirstName = In.next(); // Accepts a one word input only
return studFirstName;
}
public String setStudFirstName(String sFirstName) // Setter for student's first name
{
return studFirstName;
}
public static void main (String [] args)
{
Students first[] = new Students[5];
for(Students a : first)
{
}
Students first[] = new Students("", "", "");
String studFirstName = first.getStudFirstName();
}
}
You need a regular for loop in order to assign values within the array.
int numStudents = 5;
Student students[] = new Student[numStudents]; // creates an array of 5 nulls
Scanner scan = new Scanner(System.in);
for(int i = 0; i < numStudents; i++) {
System.out.println("Enter your first name: "); // Prompt
String fname = scan.nextLine(); // Read
Student s = new Student(fname); // Assign
first[i] = s; // Store
}
You really don't need the get methods since you have access to set the values in the constuctor.
int numberOfStudents = 3;
// create an array that can hold up to 3 students
Student[] students = new Student[numberOfStudents];
// create the Scanner to read from console.
Scanner scanner = new Scanner(System.in);
// create the 3 students and store them in the array
for(int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter name: ");
// read the next line from the console
String name = scanner.nextLine();
// ...
// if you have anything you need to create the student object (e.g. name, and so on).
Student s = new Student(studFirstName);
students[i] = s; // store the student object in the array.
}
// you should evt. close the scanner
// scanner.close();
// you can now do anything with your 3 stored students.
System.out.println("The Students first name is: " + students[0].getStudFirstName());
}
}
First, you should take a look at encapsulation. A getter is not meant to take user input. Getter should return the value of a private field. Setters should set the value of a private field.
// This is a field
private String myField;
// This will return the current value for the field 'myField'
public String getMyField() {
return this.myField;
}
// This will asign a new value to the field 'myField'
public void setMyField(String myField) {
this.myField = myField;
}
Answer
You will need a regular for loop to create as many students a you want. I renamed your class 'Students' to Student to fit javas naming conventions.
int numberOfStudents = 3;
// create an array that can hold up to 3 students
Student[] students = new Stundent[numberOfStudents];
// create the Scanner to read from console.
Scanner scanner = new Scanner(System.in);
// create the 3 students and store them in the array
for(int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter name: ");
// read the next line from the console
String name = scanner.nextLine();
// ...
// if you have anything you need to create the student object (e.g. name, and so on).
Student s = new Student(name, .....);
students[i] = s; // store the student object in the array.
}
// you should evt. close the scanner
// scanner.close();
// you can now do anything with your 3 stored students.
System.out.println("The Students first name is: " + students[0].getStudFirstName());
My program is supposed to output labels. All of the input works when I run it but the output is wrong and all that it outputs is null, for every part of the label except for the box number.
import javax.swing.JOptionPane;
public class MailOrderpractice {
static String nameAddressArray[] = new String[7];
public static void main(String[] args) {
// declare variables
String nameAddressArray[] = new String[7];
String numBoxesInput;
int numBoxes;
String enterAnother = "Y";
int counter;
getLabelData();
numBoxesInput = JOptionPane.showInputDialog("Enter number of boxes in the order:");
numBoxes = Integer.parseInt(numBoxesInput);
// begin outer loop logic that determines when user is finished entering mail orders
while (enterAnother.equalsIgnoreCase("Y")) {
counter = 1;
// begin the inner loop to display a label and increment the counter
while (counter <= numBoxes) {
System.out.println(nameAddressArray[0] + " " + nameAddressArray[1] + " " + nameAddressArray[2]);
System.out.println(nameAddressArray[3]);
System.out.println(nameAddressArray[4] + ", " + nameAddressArray[5] + " " + nameAddressArray[6]);
System.out.println("Box " + counter + " of " + numBoxes);
System.out.println();
counter = counter + 1;
}
enterAnother = " "; // initialize the variable to something other than "Y" before sending the prompt
enterAnother = JOptionPane.showInputDialog("Do you want to produce more labels? Y or N");
while (!enterAnother.equalsIgnoreCase("Y") && !enterAnother.equalsIgnoreCase("N")) {
enterAnother = JOptionPane.showInputDialog(null, "Invalid Response. Please enter Y or N.",
"DATA ENTRY ERROR", JOptionPane.ERROR_MESSAGE);
} // end while
if (enterAnother.equalsIgnoreCase("Y")) {
getLabelData();
numBoxesInput = JOptionPane.showInputDialog("Enter number of boxes in the order:");
numBoxes = Integer.parseInt(numBoxesInput);
} // end if
} // end while
System.exit(0);
}
public static void getLabelData() {
nameAddressArray[0] = JOptionPane.showInputDialog("Enter title (Mr., Ms., Dr., etc.): ");
nameAddressArray[1] = JOptionPane.showInputDialog("Enter first name: ");
nameAddressArray[2] = JOptionPane.showInputDialog("Enter lastname: ");
nameAddressArray[3] = JOptionPane.showInputDialog("Enter street address: ");
nameAddressArray[4] = JOptionPane.showInputDialog("Enter city: ");
nameAddressArray[5] = JOptionPane.showInputDialog("Enter state (IL, MO, etc.): ");
nameAddressArray[6] = JOptionPane.showInputDialog("Enter zip (e.g., 62025): ");
}
The array nameAddressArray is declared twice. You have a static field
static String nameAddressArray[] = new String[7];
You also have a local variable with the same name in the main method.
String nameAddressArray[] = new String[7];
Your main method is putting values into the second array, whereas your getLabelData method is using the values from the static field, and these are all the initial value (null).
One way to solve this problem is to just get rid of the local variable. Then both parts of the code will use the same array.
Alternatively, you could get rid of the static field, and pass the array as a parameter to the getLabelData method. This is probably a better solution, as mutable static fields are generally not a good idea.
you just need to comment this line into Main method(),
// String nameAddressArray[] = new String[7];
I have a program that accepts a number that represents an array index and a
String to replace the array element corresponding to the index.
Here is my code:
public static void main(String args[]){
String names[]={"Alvin", "Einstein", "Ace", "Vino", "Vince"};
for(int i=0; i<names.length;i++)
System.out.println(i + " - " + names[i]);
replaceArrayElement(names);
}
public static void replaceArrayElement(String name[]){
int index = 0;
String value = "";
Scanner scan = new Scanner(System.in);
System.out.print("\nEnter the index to be replaced:");
index = scan.nextInt();
if(index<name.length){
System.out.print("Enter the new value:");
value = scan.nextLine();
name[index] = scan.nextLine();
System.out.println("\nThe new elements of the array are");
for(int j=0; j<name.length;j++)
System.out.println(name[j]);
}
else{
System.out.println("Error!");
}
}
What I need to do is to put the int index variable and String value variable inside the method replaceArrayElement as a parameters. But I don't know how to call a method with different data type parameters. Can somebody show me how?? Thank you.
Well it's not clear where you'd get the values to pass in from, but here's how you would declare the method:
public static void replaceArrayElement(String[] name, int index, String value)
You'd call it with:
// Get the values from elsewhere, obviously
replaceArrayElement(array, 5, "fred");
Note that I've used String[] name instead of String name[] - while the latter syntax is permitted, it's strongly discouraged as a matter of style.
Declare replaceArrayElement as follows -
public static void replaceArrayElement(int index, String value, String[] name)
and call it as -
replaceArrayElement(2, "Einstein2", names);
public static void main(String args[]){
String names[]={"Alvin", "Einstein", "Ace", "Vino", "Vince"};
for(int i=0; i<names.length;i++)
System.out.println(i + " - " + names[i]);
replaceArrayElement(3,"alpesh",names);
}
public static void replaceArrayElement(int index, String replacename, String names[]){
if(index<names.length){
names[index] = replacename;
System.out.println("\nThe new elements of the array are");
for(int j=0; j<names.length;j++)
System.out.println(names[j]);
}
else{
System.out.println("Error!");
}
}