Printing an array after user input - java

I'm working on a class that will take user input to assign values to an object created in a source class. Those objects will then be added to an array, which then prints the values on it. However, the "list" under print : list is telling me that I need to initialize the variable. Why is it not recognizing that this is an array even though it seems to work fine in my do loop?
import java.util.Scanner;
import name.Names;
public class NameTester {
public static void main(String[] args) {
// TODO Auto-generated method stub
String entry;
Scanner firstscan = new Scanner(System.in);
Scanner lastscan = new Scanner(System.in);
Scanner codescan = new Scanner(System.in);
Scanner entryscan = new Scanner(System.in);
String first;
String last;
int code;
System.out
.println("This program will prompt you to input first name, +"
+ "last name, and zip code for an individual. Hit \"x\" when finished\n");
do {
System.out.println("Enter first name:");
first = firstscan.nextLine();
System.out.println("Enter last name:");
last = lastscan.nextLine();
System.out.println("Enter zip code:");
code = codescan.nextInt();
Names nm = new Names(first, last, code);
Names[] list = new Names[25];
int count = 0;
list[count] = nm;
count++;
System.out
.println("To quit hit \"X\" or any other key followed by enter to continue:");
entry = entryscan.nextLine();
} while (!(entry.equalsIgnoreCase("x")));
for (Names print : list)
System.out.println(print + "");
}
}

For one, you are instantiating your array inside your loop, that means every time your loop runs through, it creates a new array instead of updating the old one. Then, once you leave your loop, you leave its "scope". That means everything you declare inside the loop is not available outside. The solution is to declare your array outside the loop.
Every block in java has its own scope (defined through brackets). While you can access variables that have been declared outside your block while inside it, it does not work the other way around; as you can see. Just google java scope, and you will understand more. Hope that helps ;)

You will need a method in the class Name that return the first, last name and the zip code because if you just use:
System.out.println(print + "")
You are printing the object Name and no the String that represents the attributes saved in the object.
For example you can have the method in the class Name:
String getFirst()
{
return this.first;
}
And the last line in your class Nametester can be
System.out.println(print.getFirst() + "");

Related

How to read a file and pass the information to separately saved class objects?

I'm setting a java application that has 3 separately saved classes WordApp, WordProcessor, and WordType. WordApp reads the file and is suppose to pass the data to the other classes. I can read the file but I can't the data to pass to the other classes. How to pass the information via a string?
I've searched this and every example I find has all the classes saved to the same file. I'm using textpad and I tried passing the string to the WordProcessor class which has constructs an ArrayList of WordType objects. This method is not working for me.
This is the first part of the WordApp class for reading the file.
import java.io.*; // Import IO package
import java.util.Scanner; // Import Scanner utility
import java.util.ArrayList; // Import ArrayList utility
public class WordApp // Declared WordApp Class
{
public static void main (String[] args) // Main
{
// Declared Variables
String again;
String initial = "";
String inputFileName;
String outputFileName;
// Declared Objects
Scanner input = new Scanner(System.in);
do
{
try
{
System.out.println(" Welcome to the Word Processor App! ");
System.out.println("**********************************************************************\n");
System.out.println("Enter file names with .txt extension.");
System.out.print("Please Enter File Name to Read: ");
inputFileName = input.nextLine().trim();
File mcFile = new File(inputFileName);
Scanner scan = new Scanner(mcFile);
System.out.println("Enter file names with .txt extension.");
System.out.print("Please Enter File Name to Save: ");
outputFileName = input.nextLine().trim();
File deFile = new File(outputFileName);
PrintWriter out = new PrintWriter(deFile);
System.out.println("Reading file...\n");
while(scan.hasNext())
{
initial = scan.next();
}
scan.close();
System.out.println("Scanning Paragraph.....\n");
WordProcessor x = new WordProcessor();
x.addWord(initial);
I'm trying to pass the words in the file here:
import java.util.ArrayList;
import java.util.Collections;
public class WordProcessor
{
private ArrayList<WordType> words;
private int totSentences;
private int totUnique;
public WordProcessor()
{
words = new ArrayList<WordType>();
totSentences = 0;
totUnique = 0;
}
and here:
public class WordType implements Comparable
{
// instance data
private String word;
private int count;
private int syllables;
// Constructors
public WordType(String newWord)
{
word = newWord;
count = 1;
syllables = countSyllables();
}
I'm expecting that that words pass to the other classes but when I save the file it is blank. Sorry if I didn't post the code correctly
You're reading the file and getting the items it holds but discarding all but the last.
while(scan.hasNext()) {
initial = scan.next();
// You do **nothing** with the String read in
}
scan.close();
System.out.println("Scanning Paragraph.....\n");
WordProcessor x = new WordProcessor();
x.addWord(initial); // until here where you add the last one
Instead create the WordProcessor object before the while loop, and add words within the while loop
WordProcessor x = new WordProcessor();
while(scan.hasNext()) {
initial = scan.next();
x.addWord(initial);
}
scan.close();
There may be other errors, especially problems in your code not shown (addWord(...) comes to mind), but this error was immediately obvious.
Also what type of looping are you doing and why? You appear to have a do-while loop -- why? Again if this does not solve your problem, then you still will need to create and post a valid mcve so we don't have to guess what the problem truly is. Please understand that I am not asking for all your code but rather for something completely different -- please read the link and understand it fully if your problem has not been solved and you still need help.

Do I have to assign the data from sc.nextLine() to a variable before I use it?

So far, every time I have used a scanner object I have assigned the input to a new string variable like:
String word = reader.nextLine();
and then if I want to use the input in an if statement I would write:
if(word.isEmpty()){}
but this seems almost like an extra step instead of just doing:
if(reader.nextLine().isEmpty()){}
however, when I try this I usually get some kind of problem in my program function. Is there a way to do this by skipping the String that I will never use again?
This is the code that I am trying to use without the String objects:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class WordsInReverseOrder {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ArrayList<String> words = new ArrayList<String>();
while(true){
System.out.println("Type a word: ");
if(reader.nextLine().isEmpty()){
Collections.reverse(words);
for(String word1 : words){
System.out.println(word1);
}
break;
}
else{
words.add(reader.nextLine());
}
}
}
}
If you need to do something with the scanned word and want to check isEmpty() than you need a variable to access the word twice.
So, if you do more than one thing, you need a variable. If you do just one thing, you can 'inline' the variable.
The answer to your question is 'Yes'. When you do not need the content of the first word / line, the you can 'inline' your variable, which means that there is no need for a variable.

creating a new line for string

made a program that counts and outputs users based on user input. I want the program to display the names one below the other with the line break but stuck on how to. the code is below:
package uk.ac.reading.cs2ja16.Glen.Stringtest;
import java.util.Arrays;
import java.util.Scanner;
public class stringnames {
public static String[] countNames (String names) {
// Create Scanner object
#SuppressWarnings("resource")
Scanner names1 =new Scanner(System.in);
// Read a string
String read= names1.nextLine();
// Split string with space
String numPeople[]=read.trim().split(" ");
System.out.println("The Number of names inputted is: "+ numPeople.length);
return numPeople;
}
public static void main(String[ ] args){
System.out.println("Enter the amount of names you want(make sure you make space for each name):\n");
String[] namesout = countNames(null);
System.out.println(Arrays.toString(namesout));
}
}
First of all, the countNames method does not need a parameter, so delete that String names thingy in the method declaration. And delete the word null in your method call.
Now, you can either use a for loop or use one of the methods in the new Stream API if you're using Java 8.
I'll show you both ways.
For loop:
for (String name: namesout) {
System.out.println(name);
}
the println method automatically adds a new line character at the end of the string that you want to print.
Stream API:
Arrays.stream(namesout).forEach(System.out::println);

Implementing classes and objects in java, calling a method

I'm having trouble with calling a method. The basis of the program is to read in data from data.txt, grab the name token given, then all of the grades that follow, then implement some operations on the grades to give details of the person's grades. I do all of the methods in a separate file named Grades.java, which has the Grades class. I'm just having trouble because I MUST have the testGrades method in my code (which I don't find necessary). I have done everything I need to do for the results to be perfect in a different program without having two different .java files. But it's necessary to do it this way. I think I have mostly everything pinned down, I'm just confused on how to implement and call the testGrades method. I commented it out and have the question on where it is in the program. Quite new to classes and objects, and java in general. Sorry for the lame question.
public class Lab2 {
public static void main(String[] args) {
Scanner in = null; //initialize scanner
ArrayList<Integer> gradeList = new ArrayList<Integer>(); //initialize gradeList
//grab data from data.txt
try {
in = new Scanner(new File("data.txt"));
} catch (FileNotFoundException exception) {
System.err.println("failed to open data.txt");
System.exit(1);
}
//while loop to grab tokens from data
while (in.hasNext()) {
String studentName = in.next(); //name is the first token
while (in.hasNextInt()) { //while loop to grab all integer tokens after name
int grade = in.nextInt(); //grade is next integer token
gradeList.add(grade); //adding every grade to gradeList
}
//grab all grades in gradeList and put them in an array to work with
int[] sgrades = new int[gradeList.size()];
for (int index = 0; index < gradeList.size(); index++) {
sgrades[index] = gradeList.get(index); //grade in gradeList put into grades array
}
//testGrades(sgrades); How would I implement this method call?
}
}
public static void testGrades(Grades grades) {
System.out.println(grades.toString());
System.out.printf("\tName: %s\n", grades.getName());
System.out.printf("\tLength: %d\n", grades.length());
System.out.printf("\tAverage: %.2f\n", grades.average());
System.out.printf("\tMedian: %.1f\n", grades.median());
System.out.printf("\tMaximum: %d\n", grades.maximum());
System.out.printf("\tMininum: %d\n", grades.minimum());
}
}
This is a little snippet of the beginning of the Grades.java file
public class Grades {
private String studentName; // name of student Grades represents
private int[] grades; // array of student grades
public Grades(String name, int[] sgrades) {
studentName = name; // initialize courseName
grades = sgrades; // store grades
}
public String getName() {
return studentName;
} // end method getName
public int length() {
return grades.length;
}
well your test grades take a Grades object so you need to construct a Grades object using your data and pass it to your test grades method
i.e.
Grades myGrade = new Grades(studentName,sgrades);
testGrades(myGrade);
It looks like what you need to do is have some type of local variable in your main method, that would hold your custom Grade type. So you need add a line like..
Grades myGrades = new Grades(studentName, sgrades);
Then you can call your testGrades method with a line like...
testGrades(myGrades);
Looks like you may also need a toString method in your Grades class.
Seems like homework, so I tried to leave a bit to for you to figure out :)

Static method not executing completely in Try-Catch

My static method to add an Object to an Arraylist of Objects.
public static void addObject() {
int id;
String name;
try{
System.out.print("Id: ");
id = Integer.parseInt(sc.next());
System.out.print("Name: "); //when the program gets here, he just skips back to my main class...
name = sc.nextLine();
Object o = new Object(id, name);
l.addObject(o); //adds the object to this list (l) of objects
}
catch(NumberFormatException nfe){
System.out.println("Not a valid id!");
addObject();
}
}
My main method which contains a switch in do-while-loop, which adds, deletes and edits objects.
public static void main(String[] args){
int choice;
do{
try{
choice = Integer.parseInt(sc.next());
switch (choice){
case 0: break; //ends the program
case 1: addObject(); break; //starting static method to add an object with a name and an id
//here are some more cases with similar static methods (left them out for simplicity)
default: System.out.println("Not a valid choice!");break;
}
}
catch(NumberFormatException nfe){
System.out.println("Not a valid choice!");
choice = -1; //to keep the loop running, and prevent another exception
}
}while (choice != 0);
System.out.println("Good bye!");
}
My Object class
public class Object{
private int id;
private String name;
public Object(int id, String name) {
this.id = id;
this.name = name;
}
}
My ObjectList class
import java.util.*;
public class ObjectList {
private List<Object> objects;
public ObjectList() {
objects = new ArrayList<Object>();
}
public void addObject(Object o){
objects.add(d);
}
}
When I try to run the static method to add an Object, it records the id of the object just fine, but when I enter the objects id, it goes back to my main method, starting the loop all over.
It reacts just fine when I enter a string in the switch(restarting the loop).
But I can't seem to add objects properly.
This is also a school assignment, in which they gave us all this code (except for the try-catch methods), and asked us to write a try-catch for the static method and the main method.
I could probably find a workaround for the main method with an if-clause, but I was wondering if this is possible with a try-catch method.
Issues:
When using a Scanner, you must be aware of how it does and doesn't handle the end of line token, especially when you combine method calls that handle this token (nextLine() for instance) and those that don't (nextInt() for instance). Note that the former, nextLine() swallows the end of line (EOL) token while nextInt() and similar methods don't. So if you call nextInt() and leave an end of line token tangling, calling nextLine() will not get your next line, but will rather swallow the dangling EOL token. One solution is to call sc.nextLine() right after calling sc.nextInt() just to hande the EOL token. Or else where you call sc.next(), change that to sc.nextLine().
Don't use recursion (having your addObject() method call itself) as you're doing where a simple while loop will work better, will be cleaner, and safer.
If you truly have a class named "Object", please change it as that name conflicts with the key base class of all Java classes.
For example, if you had this code:
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = sc.nextInt();
System.out.print("Enter name: ");
String name = sc.nextLine();
You'll find that the name is always "", and that is because the sc.nextLine() is swallowing the end of line (EOL) token left over from the user's entering a number. One way to solve this is to do:
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = sc.nextInt();
sc.nextLine(); // ***** to swallow the dangling EOL token
System.out.print("Enter name: ");
String name = sc.nextLine();

Categories