SOLVED IT
I've written a program that loads Strings after an equal sign, and has it count how many times its done this. After counting, I tell it to tell me how large the int is. The value I'm looking for is 3, and it tells me, 3. I then change it to an String, the value stays three. Then, I put it into an 4d array, and It tells me the value is 2. What happened?
The Code:
int times=0;
else if (list.equals("Weapon")) {//If the word weapon is before the =
weapon = value; //take the string after the = and put it into String weapon
troopStats[times][1][weaponTimes][0] = weapon;
weaponTimes++;
System.out.println(weaponTimes+"weapontimes"+times);
}
weaponTimesStr = Integer.toString(weaponTimes);
System.out.println(weaponTimesStr+"string");
troopStats[times][1][0][1] = weaponTimesStr;
System.out.println(troopStats[times][1][0][1]+"InArray");
times++
//loops
The Output:
3weapontimes //Counted the equals sign 3 times, Note that this is from the part of the
omitted code
3string // Changed the integer to a string and got 3
2InArray // Put it into an array, and got 2 back
What Is going on?
(I know that I could just add 1 to the value, but I want to use this code for a unknown number of things later on)
To help, I've posted the entire code:
public class TroopLoader {
static String[][][][] troopStats;
static int times = 0;
static int weaponTimes = 0;
static int armorTimes = 0;
static int animalTimes = 0;
static String weaponTimesStr;
static String armorTimesStr;
static String animalTimesStr;
static String troop;
static String weapon;
static String armor;
static String animal;
static String speed;
static int total = 0;
/*
* [][][]
*
* [total number of troops (total)]
*
* [stats] 0= name 1= weapon 2= armor 3= animal 4= speed
*
* [different things within stat]
*/
public void readTroop() {
File file = new File("resources/objects/troops.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
// repeat until all lines is read
while ((text = reader.readLine()) != null) {
StringTokenizer troops = new StringTokenizer(text, "=");
if (troops.countTokens() == 2) {
String list = troops.nextToken();
if (list.equals("Troop")) {
total++;
}
else {
}
} else {
}
}
troopStats = new String[total][5][10][2];
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
File file2 = new File("resources/objects/troops.txt");
BufferedReader reader2 = null;
try {
reader2 = new BufferedReader(new FileReader(file2));
String text = null;
// repeat until all lines is read
while ((text = reader2.readLine()) != null) {
StringTokenizer troops = new StringTokenizer(text, "=");
if (troops.countTokens() == 2) {
String list = troops.nextToken();
String value = troops.nextToken();
if (list.equals("Troop")) {
troop = value;
troopStats[times][0][0][0] = troop;
}
else if (list.equals("Weapon")) {
weapon = value;
troopStats[times][1][weaponTimes][0] = weapon;
weaponTimes++;
System.out.println(weaponTimes+"weapontimes"+times);
}
else if (list.equals("Armor")) {
armor = value;
troopStats[times][2][armorTimes][0] = armor;
armorTimes++;
}
else if (list.equals("Animal")) {
animal = value;
troopStats[times][3][animalTimes][0] = animal;
animalTimes++;
}
else if (list.equals("Speed")) {
speed = value;
troopStats[times][4][0][0] = speed;
}
else if (list.equals("Done")) {
weaponTimesStr = Integer.toString(weaponTimes);
System.out.println(weaponTimesStr+"string");
armorTimesStr = Integer.toString(armorTimes);
animalTimesStr = Integer.toString(animalTimes);
troopStats[times][1][0][1] = weaponTimesStr;
troopStats[times][1][0][1] = armorTimesStr;
troopStats[times][1][0][1] = animalTimesStr;
System.out.println(troopStats[times][1][0][1]+"InArray"+times);
times++;
troop = "";
weapon = "";
armor = "";
animal = "";
speed = "";
weaponTimes = 0;
armorTimes = 0;
animalTimes = 0;
}
else {
}
} else {
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
if (reader2 != null) {
reader2.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
In the earlier part of the code, I had the program store a value in the location on the array with the weaponTimes variable, not storing the weaponTimes variable. My mistake, sorry for wasting your time.
I wrote a SSCCE with what you posted and it prints what you would expect:
public static void main(String[] args) {
String[][][][] troopStats = new String[4][4][4][4];
int times = 2;
int weaponTimes = 3;
String weaponTimesStr = Integer.toString(weaponTimes);
System.out.println(weaponTimesStr + "string"); //prints 3string
troopStats[times][1][0][1] = weaponTimesStr;
System.out.println(troopStats[times][1][0][1] + "InArray"); //prints 3InArray
}
So the problem is most likely something/somewhere else.
The following:
public class Foo {
public static void main(String[] args) {
String[][][][] troopStats = new String[2][2][2][2];
String weaponTimesStr = Integer.toString(3);
System.out.println(weaponTimesStr+"string");
troopStats[0][1][0][1] = weaponTimesStr;
// You said in a comment that 'times' is equal to 0 in this case so have subbed that in
System.out.println(troopStats[0][1][0][1]+"InArray");
}
}
Gives me the expected output:
3string
3InArray
Sorry I've wasted your time, my mistake was because I stored values in the array using the values of weaponTimes, and not storing weaponTimes in the array.
troopStats[times][1][weaponTimes][0] = weapon;
That was the mistake.
Related
private static List<A> compute(Path textFile, String word) {
List<A> results = new ArrayList<A>();
try {
Files.lines(textFile).forEach(line -> {
BreakIterator it = BreakIterator.getWordInstance();
it.setText(line.toString());
int start = it.first();
int end = it.next();
while (end != BreakIterator.DONE) {
String currentWord = line.toString().substring(start, end);
if (Character.isLetterOrDigit(currentWord.charAt(0))) {
if (currentWord.equals(word)) {
results.add(new WordLocation(textFile, line));
break;
}
}
start = end;
end = it.next();
}
});
} catch (IOException e) {
e.printStackTrace();
}
return results;
}
How can I get the line number which the word has been found?
I want to use a stream to calculate in Lamdba.
Do you have any idea?
public class Try {
public static void main(String[] args) {
Path path = Paths.get("etc/demo.txt");
List<String> result = compute(path, "Test");
result.stream().forEach(s -> System.out.println(s));
}
private static List<String> compute(Path textFilePath, String wordToFind) {
List<String> results = new ArrayList<String>();
// Added position and initialized with 0
int[] position = new int[]{0};
try {
Files.lines(textFilePath).forEach(line -> {
BreakIterator it = BreakIterator.getWordInstance();
it.setText(line.toString());
int start = it.first();
int end = it.next();
// Increment position by 1 for each line
position[0] += 1;
while (end != BreakIterator.DONE) {
String currentWord = line.toString().substring(start, end);
if (Character.isLetterOrDigit(currentWord.charAt(0))) {
if (currentWord.equals(wordToFind)) {
results.add("File Path: " + textFilePath + ", Found Word: " + wordToFind + ", Line: " + position[0]);
break;
}
}
start = end;
end = it.next();
}
});
} catch (IOException e) {
e.printStackTrace();
}
return results;
}
}
demo.txt:
Stream1
Review
Stream
2020-10-10 10:00
Test
0.0
admin HOST Test
Stream2
Review
Output:
Note:
This is an example for your reference as it uses List<String>.
Added int[] position = new int[]{0}; and position[0] += 1; for line numbers to be displayed.
In above example Test exists in line number 5 and 7.
You can use a LineNumberReader to get the linenumber. That would look something like this:
private static List<A> compute(Path textFile, String word) {
List<A> results = new ArrayList<A>();
try (final LineNumberReader reader = new LineNumberReader(new FileReader(textFile.toFile()))) {
String line;
while ((line = reader.readLine()) != null) {
BreakIterator it = BreakIterator.getWordInstance();
it.setText(line);
int start = it.first();
int end = it.next();
final int lineNumber = reader.getLineNumber(); // here is your linenumber
while (end != BreakIterator.DONE) {
String currentWord = line.substring(start, end);
if (Character.isLetterOrDigit(currentWord.charAt(0))) {
if (currentWord.equals(word)) {
results.add(new WordLocation(textFile, line));
break;
}
}
start = end;
end = it.next();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return results;
}
I am facing a issue when fatch the value from xl after that print under the for loop scope then printed. when declare the in return statement and call the method only first cell value print. I want 8 cell value.
public String Sheet_Infor() {
ReadConfig readconfig = new ReadConfig();
String excelPath = readconfig.getExcelPath();
int Row =0;
String s = "";
try {
Row = XLUtils.getRowCount(excelPath,"Course 7");
} catch (IOException e) {
e.printStackTrace();
}
for (Row = 20; Row<28; Row++) {
try {
s = XLUtils.getCellData(excelPath,"Course 7", Row,1);
return s;
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println("sss="+s);
}
return s;
}
You can use if(condition) to break/return the required value. For ex, I have a for loop interating upto 10. At value 6 I want to stop and return the value. It can be done as:
private test() {
for (int i = 10; i > 10; i++) {
if(i==5) {
return i;
}
}
}
If you want all the 8 cell values then you will have to hold those values in a list/array. You can do it as:
public List<String> Sheet_Infor() {
ReadConfig readconfig = new ReadConfig();
String excelPath = readconfig.getExcelPath();
int Row = 0;
String s = "";
try {
Row = XLUtils.getRowCount(excelPath, "Course 7");
} catch (IOException e) {
e.printStackTrace();
}
List<String> items = new ArrayList<String>();
for (Row = 20; Row < 28; Row++) {
try {
s = XLUtils.getCellData(excelPath, "Course 7", Row, 1);
items.add(s);
return s;
} catch (IOException e) {
e.printStackTrace();
}
// System.out.println("sss="+s);
}
return items;
}
I have a Java project that I am working for the school, and I am a beginner. For school, I have to create an authentication program, and for the most part, I figured it out on my own. However, I am having an issue implementing a three failed attempts, and you're locked out kind of thing. All while loops and if statements just mess up the program. I also need help re-initializing the program once it brings up the prompt of a correct user input. The main method is in another class but essentially all it does is it only asks the user for the username, and then it sends it to this class while this class does all the work. It needs to be polished as well, so there is a lot of unnecessary code that I will remove once I get the program running how I like.
package authenticationsystem;
import java.security.MessageDigest;
import java.io.*;
import java.util.*;
public class UserInfo {
private Scanner x;
private Scanner z;
private String user;
private String pass;
private String role;
private String hash;
private boolean trip = false;
public void userName(String name) throws Exception {
Scanner scnr = new Scanner(System.in);
String userLine, hashCode, password="", userPass, roleFile;
int quotes, quotes2, lineLength, usernameLength, hashLength;
int lineNumber = 0, i = 0;
user = name;
try{
x = new Scanner(new File("src\\authenticationsystem\\credentials.txt"));
}
catch(Exception e) {
System.out.println("could not find file");
}
while(x.hasNextLine()) {
userLine = x.nextLine();
if (userLine.contains(user)) {
usernameLength = user.length();
lineLength = userLine.length();
quotes = userLine.indexOf('\"');
quotes2 = userLine.lastIndexOf('\"');
//password = userLine.substring((quotes + 1), quotes2);
//System.out.println(password);
System.out.println(usernameLength + " " + lineLength);
System.out.println("Please enter your password");
userPass = scnr.nextLine();
//userPass = password;
hashCode = userLine.substring((usernameLength + 1), (usernameLength + 32));
roleFile = userLine.substring((quotes2 + 1), lineLength);
setPassword(userPass);
setHashCode(hashCode, roleFile);
user = userLine.substring(0, usernameLength);
}
else if (user.equals("Exit") || user.equals("exit")) {
System.exit(i);
}
lineNumber++;
}
}
String getName() {
return user;
}
public void setPassword(String passW) throws Exception {
pass = passW;
String original = passW; //Replace "password" with the actual password inputted by the user
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(original.getBytes());
byte[] digest = md.digest();
StringBuffer sb = new StringBuffer();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
hash = sb.toString();
}
public String getPassword() {
return pass;
}
public void setHashCode(String hashC, String roleF) {
AuthenticationSystem mane = new AuthenticationSystem();
Scanner scnr = new Scanner(System.in);
if (hash.contains(hashC)) {
if (roleF.contains("admin") || roleF.contains("Admin")) {
try{
z = new Scanner(new File("src\\authenticationsystem\\admin.txt"));
}
catch(Exception e) {
System.out.println("could not find file");
}
while(z.hasNext()) {
String a = z.nextLine();
String b = z.nextLine();
String c = z.nextLine();
System.out.printf("\n%s\n%s\n%s\n", a, b, c);
}
role = roleF;
}
else if (roleF.contains("veterinarian") || roleF.contains("Veterinarian")) {
try{
z = new Scanner(new File("src\\authenticationsystem\\veterinarian.txt"));
}
catch(Exception e) {
System.out.println("could not find file");
}
while(z.hasNext()) {
String a = z.nextLine();
String b = z.nextLine();
String c = z.nextLine();
System.out.printf("\n%s\n%s\n%s\n", a, b, c);
}
role = roleF;
}
else if (roleF.contains("zookeeper") || roleF.contains("Zookeeper")) {
try{
z = new Scanner(new File("src\\authenticationsystem\\zookeeper.txt"));
}
catch(Exception e) {
System.out.println("could not find file");
}
while(z.hasNext()) {
String a = z.nextLine();
String b = z.nextLine();
String c = z.nextLine();
System.out.printf("\n%s\n%s\n%s\n", a, b, c);
}
role = roleF;
}
}
else {
System.out.println("Invalid hash codes.");
}
}
public String getHashCode() {
return hash;
}
public void closeFile () {
x.close();
}
}
first of all, when you do a throw exception you don't need to try catch it. practically the throws exception works as a "i'll let another method to handle my exception".
Regarding on how you want to loop to prompt for the password you might want to use a switch case and use a counter variable to do the tries for it, so lets say it would be something like this:
int counter = 0;
do{
switch(counter){
case 1:
askForPass();
counter++;
break;
.
.
.
case 3:
askForPass();
counter++;
myBool = true;
}while(myBool == false);
Let me know if it worked!
I'm trying to handle multiple exceptions in my code, while using the Scanner to let the user enter a new path if the current one is incorrect, however I keep getting the same error, "No Line Found". Any help would be appreciated. The problem is occurring in the catch blocks at "path = sc.nextLine()".
public class Deck {
private static ArrayList<Card> monsters = new ArrayList<Card>();
private static ArrayList<Card> spells = new ArrayList<Card>();
private ArrayList<Card> deck = new ArrayList<Card>();
private static String monstersPath = "Database-Monster.csv";
private static String spellsPath = "Database-Spells.csv";
// private static Board board;
public Deck() throws IOException, UnknownCardTypeException,
UnknownSpellCardException, MissingFieldException,
EmptyFieldException {
if (monsters== null) {
monsters = loadCardsFromFile(monstersPath);
}
if (spells == null) {
spells = loadCardsFromFile(spellsPath);
}
// shuffleDeck();
buildDeck(monsters, spells);
shuffleDeck();
}
/*
* public static Board getBoard() { return board; }
*
* public static void setBoard(Board board) { Deck.board = board; }
*/
public ArrayList<Card> loadCardsFromFile(String path) throws IOException,
UnknownCardTypeException, UnknownSpellCardException,
MissingFieldException, EmptyFieldException {
Scanner sc = new Scanner(System.in);
int trials = 3;
String currentLine = null;
//String newPath = "";
for (int i = 0; i <=trials ; i++) {
try {
FileReader fileReader = new FileReader(path);
BufferedReader br = new BufferedReader(fileReader);
ArrayList<Card> temp = new ArrayList<Card>();
int sourceLineNumber = 1; // Source line
while ((currentLine = br.readLine()) != null) {
String[] mOrS = new String[6]; // Monsters or Spells
mOrS = currentLine.split(",");
int sourceFieldNumber = 0;
while (sourceFieldNumber < mOrS.length) {
if (mOrS[sourceFieldNumber].equals("")
|| mOrS[sourceFieldNumber].equals(" ")) {
throw new EmptyFieldException(path,
sourceLineNumber, sourceFieldNumber + 1); // Depends
// on
// the
// Splitted
// String
// array,
// loop
// on
// every
// field
// and
// check
}
sourceFieldNumber++;
}
if (mOrS[0].equals("Monster")) {
if (mOrS.length == 6) {
int attack = (int) (Integer.parseInt(mOrS[3]));
int defense = (int) (Integer.parseInt(mOrS[4]));
int level = (int) (Integer.parseInt(mOrS[5]));
MonsterCard monster = new MonsterCard(mOrS[1],
mOrS[2], level, attack, defense);
temp.add(monster);
} else {
throw new MissingFieldException(path,
sourceLineNumber); // Depends on the amount
// of fields in the
// String array, Monster
// should have 6, Type
// and 5 attributes.
}
} else if (mOrS[0].equals("Spell")) {
if (mOrS.length != 3) {
throw new MissingFieldException(path,
sourceLineNumber); // Depends on the amount
// of fields in the
// String Array, Spells
// should have 3, Type
// and 2 attributes
}
if (mOrS[1].equals("Card Destruction")) {
CardDestruction cardDestruction = new CardDestruction(
mOrS[1], mOrS[2]);
temp.add(cardDestruction);
} else if (mOrS[1].equals("Change Of Heart")) {
ChangeOfHeart changeOfHeart = new ChangeOfHeart(
mOrS[1], mOrS[2]);
temp.add(changeOfHeart);
} else if (mOrS[1].equals("Dark Hole")) {
DarkHole darkHole = new DarkHole(mOrS[1], mOrS[2]);
temp.add(darkHole);
} else if (mOrS[1].equals("Graceful Dice")) {
GracefulDice gracefulDice = new GracefulDice(
mOrS[1], mOrS[2]);
temp.add(gracefulDice);
} else if (mOrS[1].equals("Harpie's Feather Duster")) {
HarpieFeatherDuster harpieFeatherDuster = new HarpieFeatherDuster(
mOrS[1], mOrS[2]);
temp.add(harpieFeatherDuster);
} else if (mOrS[1].equals("Heavy Storm")) {
HeavyStorm heavyStorm = new HeavyStorm(mOrS[1],
mOrS[2]);
temp.add(heavyStorm);
} else if (mOrS[1].equals("Mage Power")) {
MagePower magePower = new MagePower(mOrS[1],
mOrS[2]);
temp.add(magePower);
} else if (mOrS[1].equals("Monster Reborn")) {
MonsterReborn monsterReborn = new MonsterReborn(
mOrS[1], mOrS[2]);
temp.add(monsterReborn);
} else if (mOrS[1].equals("Pot of Greed")) {
PotOfGreed potOfGreed = new PotOfGreed(mOrS[1],
mOrS[2]);
temp.add(potOfGreed);
} else if (mOrS[1].equals("Raigeki")) {
Raigeki raigeki = new Raigeki(mOrS[1], mOrS[2]);
temp.add(raigeki);
} else {
throw new UnknownSpellCardException(path,
sourceLineNumber, mOrS[1]); // We have 10
// spells, if
// there is an
// unknown one
// we throw the
// exception
}
} // else of Spell code
else {
throw new UnknownCardTypeException(path,
sourceLineNumber, mOrS[0]); // We have two
// types, Monster
// and Spell.
}
sourceLineNumber++;
}// While loop close
br.close();
return temp;
}// try Close
catch (FileNotFoundException exception) {
if (i == 3) {
throw exception;
}
System.out
.println("The file was not found, Please enter a correct path:");
path = sc.nextLine();
//path = newPath;
} catch (MissingFieldException exception) {
if (i == 3) {
throw exception;
}
System.out.print("The file path: " + exception.getSourceFile()
+ "At Line" + exception.getSourceLine()
+ "Contians a missing Field");
System.out.print("Enter New Path");
path = sc.nextLine();
//path = newPath;
} catch (EmptyFieldException exception) {
if (i == 3) {
throw exception;
}
System.out.println("The file path" + exception.getSourceFile()
+ "At Line" + exception.getSourceLine() + "At field"
+ exception.getSourceField()
+ "Contains an Empty Field");
System.out.println("Enter New Path");
path = sc.nextLine();
//path = newPath;
} catch (UnknownCardTypeException exception) {
if (i == 3) {
throw exception;
}
System.out.println("The file path:" + exception.getSourceFile()
+ "At Line" + exception.getSourceLine()
+ "Contains an Unknown Type"
+ exception.getUnknownType());
System.out.println("Enter New Path");
path = sc.nextLine();
//path = newPath;
} catch (UnknownSpellCardException exception) {
if (i == 3) {
throw exception;
}
System.out.println("The file Path" + exception.getSourceFile()
+ "At Line" + exception.getSourceLine()
+ "Contains an Unknown Spell"
+ exception.getUnknownSpell());
System.out.println("Enter New Path");
path = sc.nextLine();
//path = newPath;
}
} // For loop close
ArrayList<Card> noHope = null;
return noHope;
}// Method Close
You should use hasNext() before assigning path = sc.nextLine();
Something like :-
if (sc.hasNext()){
path = sc.nextLine();
}
else{
//print something else.
}
next
public String next() Finds and returns the next complete token from
this scanner. A complete token is preceded and followed by input that
matches the delimiter pattern. This method may block while waiting for
input to scan, even if a previous invocation of hasNext() returned
true. Specified by: next in interface Iterator Returns: the
next token Throws: NoSuchElementException - if no more tokens are
available IllegalStateException - if this scanner is closed See Also:
Iterator
I'm trying to scan a text file that has a format like this:
reviewers: 0
open: Sunday 08:00 16:00,Monday 06:00 20:00,Tuesday 06:00 20:00,Wednesday 06:00 20:00,Thursday 06:00 20:00,Friday 06:00 20:00,Saturday 06:00 01:00
name: The Lyre of Orpheus
city: San Francisco
cost: $$
category: Greek,Breakfast & Brunch,Seafood,Salad,Soup
rank: 0
and saving each line as a string or double, but i keep getting null with the sys.out.println inside of my forloop, anything I can change? My thought is that I'm resetting my variables inside my try too early or something.
public class Yulp {
//instance vars
ArrayList<Restaurant> resList = new ArrayList<Restaurant>();
public static void main(String args[]) {
Yulp yelp = new Yulp();
yelp.scan();
for(int i = 0; i < yelp.resList.size(); i++){
System.out.println(yelp.resList.get(i).getCity());
}
}
public void scan() {
try {
Restaurant tempRes = new Restaurant();
String name, city, category, cost;
double rank, reviewers;
Scanner scan = new Scanner(new File("randomizedList.txt"));
while (scan.hasNext()) {
//name = null; city = null; category = null; cost = null; rank = 0.0; reviewers = 0;
String line = scan.nextLine();
String rest = omitPrefix(line, "reviewers:");
if (rest != null) {
reviewers = Double.parseDouble(rest);
tempRes.setReviewers(reviewers);
}
rest = omitPrefix(line, "rank:");
if (rest != null) {
rank = Double.parseDouble(rest);
}
rest = omitPrefix(line, "name:");
if (rest != null) {
name = rest;
}
rest = omitPrefix(line, "city:");
if (rest != null) {
city = rest;
}
rest = omitPrefix(line, "category:");
if (rest != null) {
category = rest;
}
rest = omitPrefix(line, "cost:");
if (rest != null) {
cost = rest;
}
resList.add(tempRes);
}
scan.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
}
private String omitPrefix(String line, String prefix) {
if (line.startsWith(prefix))
return line.substring(prefix.length());
return null;
}
}
Here's what I have
import java.io.InputStream;
import java.util.Scanner;
public class Snippet {
public void scan() throws Exception {
Scanner scan = new Scanner(new File("randomizedList.txt"));
while (scan.hasNext()) {
String line = scan.nextLine();
String rest = omitPrefix(line, "reviewers:");
if (rest != null) {
System.out.println(rest);
}
rest = omitPrefix(line, "name:");
if (rest != null) {
System.out.println(rest);
}
rest = omitPrefix(line, "city:");
if (rest != null) {
System.out.println(rest);
}
rest = omitPrefix(line, "category:");
if (rest != null) {
System.out.println(rest);
}
}
scan.close();
}
private String omitPrefix(String line, String prefix) {
if (line.startsWith(prefix))
return line.substring(prefix.length());
return null;
}
public static void main(String[] args) throws Exception {
new Snippet().scan();
}
}
Main points:
Instead of line = new Scanner(scan.nextLine()); temp = line.nextLine(); you can just do scan.nextLine.
For getting the remainder of a line (for instance the part that follows the "name:" part) I introduced a helper method called omitPrefix(line, prefix) which returns line sans prefix if line starts with prefix, or null otherwise.
Here's another way of doing it.
public class FileParser {
public void scan() {
try {
File list = new File("randomizedList.txt");
Scanner scan = new Scanner(list);
String temp;
Scanner line;
while (scan.hasNext()) {
line = new Scanner(scan.nextLine());
temp = line.nextLine();
if (temp.startsWith("reviewers:")) {
System.out.println(temp.split(":",2)[1]);
}
if (temp.startsWith("name:",1)) {
System.out.println(temp.split(":",2)[1]);
}
if (temp.startsWith("open:")) {
System.out.println(temp.split(":",2)[1]);
}
if (temp.startsWith("city:")) {
System.out.println(temp.split(":",2)[1]);
}
if (temp.startsWith("category:")) {
System.out.println(temp.split(":",2)[1]);
}
}
scan.close();
}
catch(FileNotFoundException e){
System.out.println("File's MISSIN!");
}
catch(NoSuchElementException e){
System.out.println("NoSuchElementException dangus.");
}
}
public static void main(String[] args) {
new FileParser().scan();
}
}
Check the line with startsWith to find the introductory key word.
Then use split the string around the : which returns an array of two strings.
The second string in the returned array is reached by [1] and this produces the above output
There are further improvements that can be made to this code though.
The if statements should be refactored and extracted as a separate method.
The strings constants should extracted and each line should only be checked once.
Once a match is made you should move on to the next line.