Checking for errors from Scanner? - java

So I decided to make a program that makes Orc objects that each have a name.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
for (int x = 0; x < 10; x++){
System.out.println("Input the name of your Orc here:");
String name = input.nextLine(); //THIS is where the inputed name is registerd.
Orcmaker Orc = new Orcmaker(name);
System.out.println(Orc);
input.close();
}
System.out.println("Fire");
//Find a way to run validation code while not obstructing the for loop to make multiple orc objects.
}
}
So I made that for loop to go through the code so that I can make a name for each orc until eventually I make 10 orcs. The problem is that I'm having issues now injecting input validation that won't make certain lines of code go blank because the loop swallowing up vital code.
Also I just don't know how to make it so that my if statement can see a number or special character to invalidate. Because these are NAMES I only want a String.
Just for completeness' sake here is my constructor. This is the only other class in this mini-project I have made myself.
public class Orcmaker {
private String name;
private int age;
private String weapon;
public Orcmaker(String OrcName){
this.name = OrcName;
}
#Override
public String toString() {
return String.valueOf(name);
}
}

Related

How to Create Objects Using Records in a Text File (Java)

I'm working on a program for my Java class where I'm using a file of objects (clothing items) that represents inventory for a store. Each Retail_Item has four attributes: int itemNumber, String description, int numInInventory, and double price.
What I'm trying to figure out is how to read in each line from the file and turn each line into an object. My first thought was to create a while loop with vars like currentItemNumber, currentDescription, etc. So I tried this:
while (file.hasNextLine()) {
currentItemNumber = file.nextInt();
currentDescription = file.next
} // end while
But I got stuck there because every other time I've read in a String to a Scanner, I've always used nextLine. Can't use that here though, because each line contains multiple attributes of the object, not a String within a line. Is there a way to do this in the structure I'm trying to use, or should I be doing this a different way? I know I've seen and done some things where I parsed a String into separate pieces which I've seen people refer to as "tokens." Would people recommend reading each line in and then parsing it into separate tokens, then assigning each token to its appropriate attribute? Then I guess I'd have to cast those tokens into the appropriate object, since I think reading the whole line in and then parsing it would make each piece a String.
Here's a sample of what's in the text file (which can't be changed in any way, per the professor's instructions):
1000 Pants 10 19.99
2000 Jeans 2 25.95
3000 Shirt 12 12.50
Thanks in advance for your sage wisdom if you've got it.
The following code fulfills your requirement as stated in your question, namely how to create an instance of class RetailItem from a line of text from your text file. I presume it uses things that you may not have learned yet, like class Paths and try-with-resources. This is just used to scan through your file.
First, class RetailItem contains the members you described in your question. Next, I wrote a constructor for class RetailItem that creates a new instance and initializes the instance members. Then I wrote a toString() method that displays the contents of a RetailItem object in "human readable" form. Finally a main() method that reads your text file (which I named "clothes.txt"), line by line - using a Scanner. For each line read, the code splits it using a delimiter which consists of at least one whitespace character. (I presume you haven't yet learned about regular expressions in java.) Then I convert the elements of the String array returned by method split() into appropriate data types that are required by the RetailItem constructor. Then I call the constructor, thus creating an instance of class RetailItem (as you requested) and I print the created instance.
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Scanner;
public class RetailItem {
private static final int FIELDS = 4;
private int itemNumber;
private String description;
private int numInInventory;
private double price;
public RetailItem(int itemNumber, String description, int numInInventory, double price) {
this.itemNumber = itemNumber;
this.description = description;
this.numInInventory = numInInventory;
this.price = price;
}
#Override // java.lang.Object
public String toString() {
return String.format("%4d %-5s %2d %2.2f", itemNumber, description, numInInventory, price);
}
public static void main(String[] args) {
try (Scanner file = new Scanner(Paths.get("clothes.txt"))) {
while (file.hasNextLine()) {
String record = file.nextLine();
String[] fields = record.split("\\s+");
if (fields.length == FIELDS) {
int itemNumber = Integer.parseInt(fields[0]);
String description = fields[1];
int numInInventory = Integer.parseInt(fields[2]);
double price = Double.parseDouble(fields[3]);
RetailItem item = new RetailItem(itemNumber, description, numInInventory, price);
System.out.println(item);
}
}
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
I think the way that I would do is, like you said, parse each line into separate strings and then assign each piece to instance variables of the object you are building.
I have done something like this before, maybe it can be helpful.
Scanner fileScan;
File babyNameFile = new File("yob2015.txt");
try {
fileScan = new Scanner(babyNameFile);
} catch (FileNotFoundException e) {
System.out.println("File does not exist");
return;
}
String currentLine;
int numberOfGirlsNames = 0;
while (fileScan.hasNextLine()) {
String[] values;
currentLine = fileScan.nextLine();
values = currentLine.split(",");
if (values[1].equals("F")) {
numberOfGirlsNames = numberOfGirlsNames+1;
}
}
System.out.println("Number of female names was "+numberOfGirlsNames);

entering multiple values in link list in java

Using LinkedList I want to access the data members of the class StudData. StudData should have an array of object. This code doesn't show errors but doesn't execute successfully either.
import java.util.LinkedList;
import java.util.Scanner;
public class StudData {
public int roll_no;
public String name;
private Scanner sc;
void enter() {
sc = new Scanner(System.in);
System.out.println("enter:");
sc.nextInt(roll_no);
sc.next(name);
}
public static void main(String[] args) {
StudData p= new StudData();
LinkedList <StudData> ll=new LinkedList<StudData>();
for (int i=0; i<20; i++) {
p.enter();
ll.add(p);
}
}
}
The code shared should compile ideally. But there would be a possible exception at:
sc.nextInt(roll_no); // roll_no is 0 by default
Hence this would throw an java.lang.IllegalArgumentException: radix:0. In case you want to take roll_no as an input from user, you can change the code to:
roll_no = sc.nextInt();
It looks to me like you made a mistake (although I am on the train working with my phone)
sc.nextInt(roll_no);
sc.next(name);
Should be:
roll_no = sc.nextInt();
name = sc.next();
The variables can't be set by passing them as arguments, because a String is immutable and an int is a primitive.

Server/Client classes with two dimensional array (Java)

I am EXTREMELY new to Java and completely lost on the concept of ARRAYS. I need to create a "World" class to display a two dimensional array that is user specified in size, using a constructor that accepts two values [rows] and [columns] with a character (Lets say "P") located in the array. A separate "Driver" class will hold the main method. Other methods (moveUp, moveDown, moveLeft, and moveRight) need to be created to move the character around inside the array. There needs to be a fifth method to display the world array. I currently have the following code, but nothing is working so I got rid of it. even this code itself won't compile - says "identifier expected before the parenthesis of my second println. I have no idea why this won't go any further. This is the only place I have to seek help since the college offers no tutors for Java, youtube videos are extremely vague and use terminology I do not know, library books I've checked out don't show me the actual code needed to perform these tasks, and the class textbook shows code close, but not quite what is needed. and since I'm extremely new to Java, my last questions garnered me the threat of losing the ability to post on this site, so that would take away my only recourse for help if this is also dubbed inferior. I do not know what to do at this point.
import java.util.*;
public class World
{
public static void main(String[] args)
{
System.out.println(array);
}
Scanner input = new Scanner(System.in);
System.out.println("Enter number of row: ");
private int crow = input.nextInt();
System.out.println("Enter number of columns: ");
private int ccol = input.nextInt();
private String[][] array = newString[crow][ccol];
public int displayWorld()
{
}
public int moveUp()
{
}
public int moveDown()
{
}
public int moveLeft()
{
}
public int moveRight()
{
}
}
Compling problems-> use an IDE (eclipse netbeans idea jdeveloper ...) for developing java applications.
Here you have part of one solution, since you are learning, play with this code before implementing the rest of methods.
Regarding java learning, there are plenty of good tutorials by searching on google.
import java.util.*;
public class World{
private static final String P="P";
private String[][] array;
public World(){
Scanner input = new Scanner(System.in);
System.out.println("Enter number of row: ");
int crow = input.nextInt();
System.out.println("Enter number of columns: ");
int ccol = input.nextInt();
array = new String[crow][ccol];
array[0][0]=P;
}
public void displayWorld(){
System.out.println();
for(int i=0;i<array.length;i++){
for (int j=0;j<array[i].length;j++){
System.out.print(array[i][j]+" ");
}
System.out.println();
}
}
public void moveUp(){
}
public void moveDown(){
for(int i=0;i<array.length;i++){
for (int j=0;j<array[i].length;j++){
if ((array[i][j])!=null){
if (i<array.length-1){
array[i][j]=null;
array[i+1][j]=P;
}
return;
}
}
}
}
public void moveLeft(){
}
public void moveRight(){
}
public static void main(String[] args){
World world=new World();
world.displayWorld();
world.moveDown();
world.displayWorld();
}
}

How to pass a String value to another class in Java

Currently, I am running into a problem in my Java code. I am somewhat new to Java, so I would love it if you kept that in mind.
My problem is with passing a String value from one class to another.
Main Class:
private static void charSurvey()
{
characterSurvey cSObj = new characterSurvey();
cSObj.survey();
System.out.println();
}
Second:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class characterSurvey
{
public void survey(String character)
{
Scanner s = new Scanner(System.in);
int smartChina = 0,smartAmerica = 0,dumbAmerica = 0;
String answer;
System.out.println("Are you good with girls?");
System.out.println("y/n?");
answer = s.nextLine();
if(answer.equalsIgnoreCase("y"))
{
smartChina = smartChina - 3;
smartAmerica = smartAmerica + 2;
dumbAmerica = dumbAmerica + 4;
}
//...
//ASKING SEVERAL OF ABOVE ^
List<Integer> charSelect = new ArrayList<Integer>();
charSelect.add(smartChina);
charSelect.add(smartAmerica);
charSelect.add(dumbAmerica);
Collections.sort(charSelect);
Collections.reverse(charSelect);
int outcome = charSelect.get(0);
if(smartChina == outcome)
{
character = "smartChina";
}
else if(smartAmerica == outcome)
{
character = "smartAmerica";
}
else if(dumbAmerica == outcome)
{
character = "dumbAmerica";
}
System.out.println(character);
s.close();
}
}
When I call the first class I am trying to grab the value of the second.
Disclaimer* the strings in this class were not meant to harm anyone. It was a joke between myself and my roommate from China, thanks.
It seems as if you want to obtain the character in your main class after the survey has completed, so it can be printed out in the main method.
You can simply change your void survey method to a String survey method, allowing you to return a value when that method is called:
class CharacterSurvey {
public String takeSurvey() {
//ask questions, score points
String character = null;
if(firstPerson == outcome) {
character = "First Person";
}
return character;
}
}
Now, when you call this method, you can retrieve the value returned from it:
class Main {
public static void main(String[] args) {
CharacterSurvey survey = new CharacterSurvey();
String character = survey.takeSurvey();
System.out.println(character);
}
}
There are several mistakes here.
First off, in your main class as you write you call the method survey() on the CharacterSurvey object but the survey itself the way it is implemented needs a String parameter to work
public void survey(String character)
Also this method returns void. If you want somehow to grab a string out of that method you need to declare the method as
public String survey() {}
this method returns a string now.
If i were to give a general idea, declare a String variable in the second class which will be manipulated inside the survey method and once the survey is declared as a String method return the value at the end inside the method.
By doing that you'll be able to receive the String value by calling the method on the characterSurvey object (and of course assign the value to a string variable or use it however).
Hope this helped

How to read a text file into an array with private fields using mutators in Java

I have Googled this for a couple of days without much luck. I am trying to read a text file and use that information to populate the private fields of an array for a class object. I am new to Java and pretty new to programming in general.
What I've come up with for reading into the array seems really clunky and I feel there must be a better way, but I cannot find a good example for this particular kind of case case.
Creating a bunch of string variables was the only way I could get this to work. Perhaps main is a bad place to do this; perhaps Scanner is a poor choice here?
What better ways are there to implement this situation?
My text file that contains Strings and integers separated by whitespace on lines is similar to this:
Joe 2541 555-1212 345 1542 Type
Bob 8543 555-4488 554 1982 Type
... etc.
Here's my majority of my code thus far which is within main:
Scanner in = new Scanner(new FileReader("accounts.txt")); //filename to import
Accounts [] account = new Accounts [10];
int i = 0;
while(in.hasNext())
{
account[i] = new Accounts();
String name = in.next();
String acct_num = in.next();
String ph_num = in.next();
String ss_num = in.next();
int open_bal = in.nextInt();
String type = in.next();
account[i].setName(name);
account[i].setAcctNum(acct_num);
account[i].setPhoneNum(ph_num);
account[i].setSSNum(ss_num);
account[i].setOpenBal(open_bal);
account[i].setType(type);
i++;
}
class Accounts
{
public Accounts()
{
}
public Accounts(String n, String a_num, String ph_num,
String s_num, int open_bal, String a_type, double close_bal)
{
name = n;
account_number = a_num;
phone_number = ph_num;
ssn = s_num;
open_balance = open_bal;
type = a_type;
close_balance = close_bal;
}
public String getName()
{
return name;
}
public void setName(String field)
{
name = field;
}
public String getAcctNum()
{
return account_number;
}
public void setAcctNum(String field)
{
account_number = field;
}
//And so forth for the rest of the mutators and accessors
//Private fields
private String name;
private String account_number;
private String phone_number;
private String ssn;
private int open_balance;
private String type;
private double close_balance;
}
I believe you need to split each line in order to get the data contained in each line. You can use the split() of the string class which will return a string[]. Then you can go through each index of the string array and pass them to the mutator methods of the account class.
Something like this maybe.
while(in.hasNext())
{
// will take each line in the file and split at the spaces.
String line = in.next();
String[] temp = line.split(" ");
account[i].setName(temp[0]);
account[i].setAcctNum(temp[1]);
account[i].setPhoneNum(temp[2] + "-" + temp[3]);
account[i].setSSNum(temp[4]);
account[i].setOpenBal((int)temp[5]);
account[i].setType(temp[6]);
// will account for blank line between accounts.
in.next();
i++;
}
The phone number gets split into two separate indices so you have to rejoin the phone number by accounting for the first 3 digits being in one index and the last 4 being in the next.
Replacing Accounts[] with Set<Accounts> would be more flexible solution as you can process either 10 lines or 10000 accounts without code changes. In general: Consider Collections vs arrays
Using Scanner seems to be reasonable in this particular case, however take a look at the others ways of processing text (performance vs convenience): Scanner vs. StringTokenizer vs. String.Split
Setting up account parameters with mutators or constructor might not be the best choice: Effective Java: Consider a builder when faced with many constructor parameters

Categories