Usage of String in method - java

I need a lit help here. So I want my first method to read the file "./data/textfiles/zahlen01.txt" (there are some numbers i want to add together, this works). And I want my second method to do the same but with a string in the method. So how do i name the method in the main method?
public static double countSumOf(Scanner in) {
PrintWriter out = new PrintWriter(System.out);
double sum = 0;
while (in.hasNext()) {
double b = in.nextDouble();
sum = sum + b;
}
out.println(sum);
out.flush();
return sum;
}
public static double countSumOf(String filename) {
DirtyFileReader dfr = new DirtyFileReader(filename);
Scanner in = new Scanner(dfr);
return countSumOf(in);
}
public static void main(String[] args) {
Locale.setDefault(Locale.US);
PrintWriter out= new PrintWriter (System.out);
DirtyFileReader dfr = new DirtyFileReader("./data/textfiles/zahlen01.txt");
Scanner in = new Scanner(dfr);
countSumOf(in);
countSumOf();
out.flush();
}

Not sure I correctly understand so I rephrase:
You want to sum up some numbers, once using a file as source that contains the numbers and once using a java string that contains the numbers?
I found this interesting piece of code:
https://github.com/alquesh/PR1PRAXIS/blob/master/PR1PRAXIS/src/pr1/a04/FirstInput.java
To sum it up: Scanner can take a String as an argument to the constructor to scan that string instead so where you have Scanner in = new Scanner(dfr); you can instead use Scanner in = new Scanner(meineZeichenkette);

Related

Issue with scanner in main method vs in constructor java?

SOLVED
I'm having an issue using Scanners nextInt() method in a class constructor.
it works fine if used in a main method like the code below however when doing the same thing in a constructor I get an inputmismatchexception,
what could be the possible issues?
public class QuickTest{
public static void main(String[] args) throws Exception{
java.io.File myFile = new java.io.File("tograph.txt");
java.util.Scanner input = new java.util.Scanner(myFile);
int numberOfPoints = input.nextInt();
String[] myArray = new String[numberOfPoints];
//need to use nextLine once after reading in number of points to get to next line
input.nextLine();
int count = 0;
while(input.hasNext() == true){
myArray[count] = input.nextLine();
count++;
}
input.close();
for(int i = 0; i < myArray.length; i++){
System.out.println(myArray[i]);
}
the class version
public class MyGraph{
//filled with strings from file
String[] points;
java.io.File file;
java.util.Scanner input;
//length of points array
int numPoints;
public MyGraph(String file){
this.file = new java.io.File(file);
this.input = new java.util.Scanner(file);
this.numPoints = this.input.nextInt();
this.points = new String[this.numPoints];
fillGraphArray();
}
//after getting the number of vertices we populate the array with every
//line after those points untill the end
private void fillGraphArray(){
//used once after reading nextInt()
this.input.nextLine();
int count = 0;
while(this.input.hasNext() == true){
points[count] = input.nextLine();
count++;
}
input.close();
}
//test method to be delted later
public String[] getPoints(){
return this.points;
}
//may need a method to close the file
}
When I use the debugger the main method version will get the number of points from the file and then fill the array with a string from each following line in the file however the class version throws the exception

read lines from external file and store elements in array

I am new here so please show some patience. I am trying to read the data from an external file and store the info in 2 arrays.
The file looks like this:
0069 723.50
0085 1500.00
0091 8237.31
I am using 2 scanners to read the input and I think they work ok because when I try to print, the result looks ok.
My first problem is that I am able to read the first numbers on the list using nextInt(), but cannot use nextDouble() for the double ones as I get the "java.util.InputMismatchException" message. For that reason I read it as a String. The part with the other two scanners is supposed to do what the first parts should do, for a different input file, but the problem is the same.
My next and biggest problem, until now, is that am not able to store the values from the two columns in two distinct arrays. I have tried several ways (all commented) but all fail. Please help and thanks.
Here is my code:
import ui.UserInterfaceFactory;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Scanner;
import ui.UIAuxiliaryMethods;
public class Bank {
static final int MAX_NUMBER_OF_ACCOUNTS = 50;
PrintStream out;
Bank(){
UserInterfaceFactory.enableLowResolution(true);
out = new PrintStream(System.out);
}
void readFiles(){
Scanner balanceFile = UIAuxiliaryMethods.askUserForInput().getScanner();
while(balanceFile.hasNextLine()){
String balance_Line = balanceFile.nextLine();
Scanner accountsFile = new Scanner(balance_Line);
int account = accountsFile.nextInt(); //works
out.printf("%04d ",account);
/*int [] accounts_array = new int [MAX_NUMBER_OF_ACCOUNTS]; //does not store the values properly
int account = accountsFile.nextInt();
for(int j=0; j < accounts_array.length; j++){
accounts_array[j] = account;
}*/
/*int [] accounts_array = new int [MAX_NUMBER_OF_ACCOUNTS]; //java.util.InputMismatchException
for(int j=0; j < accounts_array.length; j++){
accounts_array[j] = accountsFile.nextInt();
//out.printf("%04d \n",accounts_array[j]);
}*/
String balance = accountsFile.nextLine(); //problem declaring balance as a double
out.printf("%s\n",balance);
/*String [] balance_array = new String [MAX_NUMBER_OF_ACCOUNTS]; //java.util.NoSuchElementException
for(int j=0; j < balance_array.length; j++){
accountsFile.useDelimiter(" ");
balance_array[j] = accountsFile.next();
//out.printf("%04d \n",accounts_array[j]);
}*/
}
Scanner mutationsFile = UIAuxiliaryMethods.askUserForInput().getScanner();
while(mutationsFile.hasNext()){
String mutation_Line = mutationsFile.nextLine();
Scanner mutatedAccountsFile = new Scanner(mutation_Line);
int mutated_account = mutatedAccountsFile.nextInt();
out.printf("%04d ",mutated_account);
int action = mutatedAccountsFile.nextInt(); //deposit or withdrawal
/*if (action == 1){
}else{
}*/
out.printf(" %d ",action);
/*Double amount = mutatedAccountsFile.nextDouble();
out.printf(" %5.2f ",amount);*/
String amount = mutatedAccountsFile.nextLine();
out.printf("%s\n",amount);
}
}
void start(){
new Bank();readFiles();
}
public static void main(String[] args) {
new Bank().start();
}
}
The InputMismatchException occurs because you try to read a double using the nextInt() function. To solve this issue, you can first read the tokens as Strings using the next() function and convert them appropriately.
while(mutationsFile.hasNext()){
mutation_Line = mutationsFile.next();
if(mutation_Line.indexOf(".") == -1)
//token is int
else
//token is double
}
Since you already know what the contents of the two columns are, you can store the integers and doubles in two lists and then, if you want, get them into an array.
List<Integer> intList = new ArrayList<Integer>();
List<Double> doubleList = new ArrayList<Double>();
Now replace the if statements in the first snippet with this:
if(mutation_Line.indexOf(".") == -1)
intList.add(new Integer(Integer.parseInt(mutation_Line)));
else
doubleList.add(new Double(Double.parseDouble(mutation_Line)));
In the end, you can get them into arrays:
Object[] intArr = intList.toArray(),
doubleArr = doubleList.toArray();
//display the contents:
for(int i=0; i<intArr.length; i++)
out.printf("%04d\t%.2f\n", Integer.parseInt(intArr[i].toString()),
Double.parseDouble(doubleArr[i].toString()));
OUTPUT:
0069 723.50
0085 1500.00
0091 8237.31
First off, you don't need to use 2 scanners. The Scanner object is simply reading your file, one scanner is plenty to accomplish the task of reading a file.
If you're trying to read the integers/doubles from file and are having trouble with nextInt() and nextDouble(), consider a different approach to parsing (e.g. parse the line into a string, split the line into 2 parts based on a space character, then trim both resulting strings and convert to respective integers/doubles).
Now back to the Scanner parsing the two values, remember first that when you use a next() or nextInt(), etc. those methods consume the next respective token. So parsing a line as a string from the file into another Scanner object is redundant and unnecessary in this case.
If you know your max number of accounts, and it's simply 50, then go ahead an allocate that prior to the while loop.
Here's an alternative approach with the code you posted.
public class App {
static int MAX_NUMBER_OF_ACCOUNTS = 50;
static PrintStream out;
static void readFiles() {
Scanner balanceFile = null;
try {
balanceFile = new Scanner(new File("C:\\Users\\Nick\\Desktop\\test.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (balanceFile == null)
return;
int [] accounts_array = new int [MAX_NUMBER_OF_ACCOUNTS];
double [] balance_array = new double [MAX_NUMBER_OF_ACCOUNTS];
int currentIndex = 0;
while (balanceFile.hasNextLine()) {
int account = balanceFile.nextInt();
double balance = balanceFile.nextDouble();
System.out.print("acc = " + account + " ");
System.out.println("bal = " + balance);
//out.printf("%04d ", account);
accounts_array[currentIndex] = account;
//out.printf("%s\n", balance);
balance_array[currentIndex] = balance;
currentIndex++;
}
balanceFile.close();
}
static void start() {
readFiles();
}
public static void main(String[] args) {
start();
}
}
Please note the excessive use of static could also be avoided in the future, but for the sake of the example it spread like the plague.
As you can see in the logic leading up to the while loop, the scanner object is made from a file I copied your example data into a file on my desktop. The arrays are allocated prior to the while loop (note: see #progy_rock and their use of ArrayList's - may help improve your code in the long run). And finally, note the index count to move the position along in the array to which you are inserting your lines to.

Method in another Class not returning anything

I'm working on a project that creates a Hangman game. The GameManager Class should call the getRandomAnswer method from the AnswerBank Class, which should return a random answer of two nouns from a file called noun_noun.txt (I've placed this file in the first level of the project folder). However, whenever I try to test the code, the console produces nothing after typing "yes" when prompted. Can anyone help?
public class GameManager {
private ArrayList<String> puzzleHistory;
private int numPuzzlesSolved;
private AnswerBank bank;
public GameManager(String fn) throws IOException{
numPuzzlesSolved = 0;
puzzleHistory = new ArrayList<String>();
this.bank = new AnswerBank(fn);
}
public static void main(String[] args) throws IOException {
GameManager obj = new GameManager("noun_noun.txt");
obj.run();
}
public void run() throws FileNotFoundException{
Scanner scan = new Scanner(System.in);
System.out.println("Would you like to play Hangman? Please type 'yes' or 'no'.");
String inputAns = scan.next();
if(inputAns.equalsIgnoreCase("no")){
System.exit(0);
}
else if(inputAns.equalsIgnoreCase("yes")){
System.out.println(bank.getRandomAnswer());
}
else{
System.out.println("Invalid response!");
}
scan.close();
}
}
public class AnswerBank {
private ArrayList<String> listStrings;
private File gameFile;
public AnswerBank(String fileName) throws IOException{
File gameFile = new File(fileName);
this.gameFile = gameFile;
this.listStrings = new ArrayList<String>();
}
public String getRandomAnswer() throws FileNotFoundException{
Scanner fileScan = new Scanner(gameFile);
int totalLines = 0;
while(fileScan.hasNextLine()){
totalLines++;
}
for(int i = 0; i < totalLines; i++){
this.listStrings.add(fileScan.nextLine());
}
int randInt = (int)(Math.floor ( Math.random() * totalLines));
String randAns = listStrings.get(randInt);
fileScan.close();
return randAns;
}
}
puzzleHistory and numPuzzlesSolved will be used later, so please ignore those. Thanks in advance for any help.
The problem is at here:
while (fileScan.hasNextLine()) {
totalLines++;
}
You file scanner never move position in the file, so it will keep scan the first line, and since first line is not empty, this is an infinite loop here.
A simple fix here is to count while reading words at the same time:
public String getRandomAnswer() throws FileNotFoundException {
Scanner fileScan = new Scanner(gameFile);
int totalLines = 0;
while (fileScan.hasNext()) {
totalLines++;
this.listStrings.add(fileScan.nextLine());
}
int randInt = (int) (Math.floor(Math.random() * totalLines));
String randAns = listStrings.get(randInt);
fileScan.close();
return randAns;
}
Hope it helps.

Changing a String into an int

I have an array of string objects that was read from a file. Some of these strings I need to use as ints. I wrote a method to read the file but now I just don't know how to get the numbers from the file, here is the file
29,,
Chute,1,0
Chute,2,0
Chute,3,0
Chute,4,0
Chute,5,0
Chute,6,0
Chute,7,0
Chute,8,0
Chute,9,0
Chute,0,1
Chute,0,2
Chute,0,3
Chute,9,1
Chute,9,2
Chute,9,3
Ladder,0,5
Ladder,1,5
Ladder,2,5
Ladder,3,5
Ladder,4,5
Ladder,5,5
Ladder,6,5
Ladder,7,5
Ladder,8,5
Ladder,9,5
Ladder,9,6
here is my method
public void readBoard(String file)throws FileNotFoundException
{
File clboard = new File ("myBoard.csv");
Scanner x = new Scanner(clboard);
while(x.hasNext())
{
String c = x.nextLine();
String [] myboard =c.split(",");
}
}
Try
int numOne = Integer.parseInt(myboard[1]);
int numTwo = Integer.parseInt(myboard[2]);
immediately after your split line.
String [] myboard = c.split(",");
if (myboard.length < 3) {
// error message
} else {
int i1 = Integer.parseInt(myboard[1]);
int i2 = Integer.parseInt(myboard[2]);
}
You might also want to add a try/catch to handle NumberFormatException (which occurs when you try to convert something that isn't a number).
public void readBoard(String file)throws FileNotFoundException
{
File clboard = new File ("myBoard.csv");
Scanner x = new Scanner(clboard);
while(x.hasNext()) {
List<Integer> number = new ArrayList<Integer>();
String c = x.nextLine();
String [] myboard =c.split(",");
for (String candid8 : myboard) {
try {
number.add(Integer.parseInt(candid8));
} catch (NumberFormatException e) {
}
}
}
}
Your numbers will now be in the number object, which is a List. If it's a more complex grammar, look into jflex, as that seems to be the recommendation of Google.

NetBeans won't print to console JAVA

I have written a simple program in the NetBeans IDE using Java. After making a few changes to the main method this morning, the console does not print anything when I run the program. I simply want it to reach startMenus(sc). EDIT: I have now put in a few System.out.println() and it does not reach "Blah2" which is right after my first loop...
public class Calculator {
public static int[] NUMBERS; //global value for the array
public static void main(String[] args) throws FileNotFoundException {
File file = new File("data.txt");
Scanner sc = new Scanner(file);
System.out.println("Blah1");
int counter = 0;
while (sc.hasNextInt()) {
counter = counter++;
}
System.out.println("Blah2");
int lenth = counter;
NUMBERS = new int[lenth];
System.out.println("Blah3");
sc.close();
File file2 = new File("data.txt");
Scanner sc2 = new Scanner(file2);
System.out.println("Blah4");
int i = 0;
while (sc2.hasNextInt()) {
NUMBERS[i] = sc2.nextInt();
++i;
}
System.out.println("Blah5");
sc2.close();
System.out.println("Welcome to Calculation Program!\n");
startMenus(sc);
}
}
Are you sure you aren't throwing any other exceptions that are killing your app before it reaches System.out.println? Judging by your description you may want to either debug or put some other println statements further up the chain as it could be dying due to something.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class Calculator {
public static int[] NUMBERS; //global value for the array
public static void main(String[] args) throws FileNotFoundException, IOException {
File file = new File("data.txt");
file.createNewFile();
Scanner sc = new Scanner(file);
int counter = 0;
while (sc.hasNextInt()) {
counter = counter++;
}
int lenth = counter;
NUMBERS = new int[lenth];
sc.close();
File file2 = new File("data.txt");
file2.createNewFile();
Scanner sc2 = new Scanner(file2);
int i = 0;
while (sc2.hasNextInt()) {
NUMBERS[i] = sc2.nextInt();
++i;
}
sc2.close();
System.out.println("Welcome to Calculation Program!\n");
startMenus(sc);
}
private static void startMenus(Scanner sc) {
System.out.println("Run your code here!!!");
}
}
Couple of things:
You need to import additional classes that are not part of your core project. Exceptions, File, and Scanner all fall into this category.
You need to run the createNewFile() method to actually create your file. Your original code was throwing a FileNotFound exception because the file was never being created.
You need to have the startMenus method defined before calling it.
I've included some corrected code. Hope this helps!
The System.out calls probably wheren't reached yet, because one of your loops took too long to execute, longer then you were willing to wait. Log something from inside a loop to get some more feedback, the program is probably fine.

Categories