Output to file with multiple methods - java

Is there a way to output to a file with multiple methods? I used this technique in C++:
// create Scanner for input
static Scanner in = new Scanner(System.in);
// Output survey results to a file
public static void main(String[] args) throws Exception
{
// create Formatter for output
Formatter out = new Formatter("numbers.txt");
// store answer
int ans;
// ask 40 students to rate the food at the cafeteria
// 1 is bad, 10 is good
for(int i = 0; i < 40; i++) {
// ensure answer is between 1 and 10
do {
System.out.print("Rate the food at the cafeteria between 1 (horrid) and 10 (excellent): ");
ans = in.nextInt();
} while(ans > 10 || ans < 0);
// end do-while
} // end for
// close file
out.close();
} // end method main
// Output data
public static void output(Formatter out, int num)
{
// enter data in a file
out.format("%d\n", num);
} // end method output
It compiles, runs, creates the file, et cetera; but when I open the file, if is empty. Any suggestions will be appreciated.

The problem with this is that output() writes the file, but you're never calling output(). Thus, the file is never written. You need to insert:
output(out, ans);
after the end of the do-while, but before the end of the for loop.

Related

When I run my methods it keeps repeating itself and doesn't move on java

Like the caption said the method "scanInput1" runs two times in a row when it should only run once. Then the method "arrayskapare" runs as intended but after that. instead of running the method "medelvarde" is jumps back and runs "scanInput1" again and again and again
import java.util.*;
class Heltalshanterare{
private static String scanInput1(){
System.out.print("Skriv in antal heltal: ");
Scanner scr = new Scanner(System.in);
String antalHeltal = scr.next();
try {
Integer.parseInt(antalHeltal);
}
catch (NumberFormatException e) {
System.out.println("Ogilitigt värde");
scanInput1();
}
return antalHeltal;
}
private static List<Integer> arrayskapare() {
int antalangivnatal = Integer.parseInt(scanInput1());
int noll = 1;
int heltal = 0;
String tal1 = "";
Scanner tal = new Scanner(System.in);
List<Integer> list = new ArrayList<>();
while (noll <= antalangivnatal) {
noll++;
heltal++;
System.out.print("ange heltal " + heltal + ": ");
tal1 = tal.next();
try {
int num = Integer.parseInt(tal1);
list.add(num);
} catch (NumberFormatException e) {
System.out.println("Ogiltigt värde");
noll--;
heltal--;
}
}
return list;
}
public static int medelvarde(){
int antalsiffror = arrayskapare().size();
int sum = 0;
for (int i : arrayskapare()){sum += i;}
int medelvärde = sum / antalsiffror;
System.out.println("medelvärdet av dina tal är " + medelvärde);
return medelvarde();
}
public static void main(String [] args){
scanInput1();
arrayskapare();
medelvarde();
}
}
Im sorry that the code is so long but I have been struggling with this for too long and I really need some help.
Your main method is calling each method just once, which is what you need. But it's not actually holding onto any of the values being returned. So the number of heltal (integers in English) is captured from the user but then never actually stored anywhere. And later an array of numbers is captured but not stored anywhere.
Your second, bigger problem is that your methods are then calling the earlier methods all over again. So instead of asking the user to type in the data just once, you're forcing them to answer the exact same questions multiple times.
A much tidier approach is to alter your methods so that they take the required data as a parameter. Which means your arrayskapare (array producer) method should take the antalHeltal (number of integers) value as a parameter, and then it won't need to call the scanInput1 method again. Same thing can be done for your medelvarde (mean value) method: have it take the array as a method parameter, so that it won't need to call arrayskapare.
With those changes your main method can simply look like this:
public static void main(String [] args){
int antalHeltal = scanInput1();
List<Integer> heltalArray = arrayskapare(antalHeltal);
int medelvardet = medelvarde(heltalArray);
System.out.println("Medelvärdet är " + medelvardet);
}
Now each method just gets called once and the data captured from the user gets stored into variables and passed along the river of methods until the final result is reached.

Java Why does my for loop set i to 0 after i is 4?

Ok, I'm trying to get the output to look a certain way. Print 10 numbers the new line. For some reason after running through loop 4 it sets i to 0. I'll put the file I'm reading from first. I eventually want to write it to a new file. This is for a class, just one assignment and I'm not asking you guys to do the assignment. (Basically I have to read the file and write to a new file with the name designated in the first file. And only use the number of numbers at the top of the first file.
The txt file contents:
MyOutput.txt 23
20 1 4 5 7
45
1 2 3 4 5 6 7 8 9 77 88 99 23 34
56 66 77 88 99 100 110 120
and the code
...
package reading_with_exceptions;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Scanner;
public class inputFilename {
static Scanner kbInput = new Scanner(System.in);
public static void main(String[] args) {
String lines = null;
Scanner inFile = null;
int count = 0;
boolean metCount = false;
// TODO Auto-generated method stub
try {
inFile = new Scanner(new FileReader("src/MyInput.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lines = inFile.nextLine();
lines.trim();
//Now check to see if line is empty
//If not empty get the ouput file name and number of lines from file
if(lines.length()>0) {
String outPutFile = lines.substring(0, lines.indexOf(' '));
String numNumbers = lines.substring((lines.indexOf(' ')+1), (lines.length()-1));
numNumbers.trim();
count = Integer.parseInt(numNumbers);
System.out.print(outPutFile+" ");
System.out.println(count);
}
//
//check if there is another line in the file
int i=0;
while(inFile.hasNextLine() && !metCount) {
lines = inFile.nextLine();
String[] separated = lines.split(" ");
for( i = 0; i<separated.length; i++) {
System.out.print(separated[i]+" ");
if((i+1) % 10 ==0) {
System.out.println("...");
}
//System.out.print(" spot:"+i+" ");
//System.out.println("i:" +i +"count:"+count);
if(i>=count)
metCount = true;
}
}
}
}
...
I've tried stepping though it in Eclipse and still can't resolve the problem. It only happens every other time. First count goes to 4 Second count goes to 10 Third goes to 4 etc.
You're first line of output outputs the count as 23.
The processing stops because you're using the line count as a comparator with your string token count...
Hence the metCount gets set to true in the while loop and the program ends
I've edited the code with some improvements so you can understand this more clearly...
I've extracted some parts to methods so you can have a named method rather than needing comments.
package reading_with_exceptions;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class inputFilename {
static Scanner kbInput = new Scanner(System.in);
public static void main(String[] args) {
Scanner inFile = open("src/MyInput.txt");
/**
* First check you have a first line.
*/
if (!inFile.hasNext()) {
throw new IllegalStateException("File is empty");
}
String header = inFile.nextLine().trim();
/**
* Check first line is not blank
*/
if(isBlank(header)) {
throw new IllegalStateException("First line has no content");
}
/**
* Get filename and total line count from file
*/
String filename = getFilename(header);
int totalLines = getNumberOfLines(header);
/**
* output results to console on one line
*/
System.out.println(filename + " " + totalLines);
/**
* iterate over/process the lines one by one (but not the last line)
* This whole process could be put in a method named processLines(...) with relevant arguments passed.
* The more you nest your code, the harder it becomes to read/debug... and the easier it is for bugs to hide.
* The more your variables have meaningless names (i, j, k) the harder it is to follow.
* Tip: try to use methods and work on small bits of code at a time... much easier to read and understand a
* single, well named function with less steps to it than one large function.
*/
boolean isLastLine = false;
while(inFile.hasNextLine() && !isLastLine) {
String[] separated = inFile.nextLine().split(" ");
for(int tokenCount = 0; tokenCount < separated.length; tokenCount++) {
/**
* print out the token
*/
System.out.print(separated[tokenCount]+" ");
/**
* continue on a new line after every 10th token is printed to the console
*/
newLineAfterTenthTokenInASingleLine(tokenCount);
/**
* here when `tokenCount` passes over the 23rd item (`separated[tokenCount]`),
* `metCount` is set to `true` and the program ends.
* This is probably not what's wanted as you want to compare a `lineCount` to the `totalLines`, not the `tokenCount`
*/
if(tokenCount>=totalLines) { // <<<<<<<<<<<<<<<<< HERE'S THE PROBLEM
isLastLine = true;
}
}
}
}
private static void newLineAfterTenthTokenInASingleLine(int tokenId) {
if((tokenId+1) % 10 == 0) {
continueOnNewLine();
}
}
private static boolean isBlank(String firstLine) {
return firstLine.length()==0;
}
private static Scanner open(String inFile) {
try {
return new Scanner(new FileReader(inFile));
} catch (FileNotFoundException e) {
throw new
}
}
private static void continueOnNewLine() {
System.out.println("...");
}
private static int getNumberOfLines(String header) {
int beginIndex = header.indexOf(' ') + 1;
int endIndex = header.length() - 1;
return Integer.parseInt(header.substring(beginIndex, endIndex).trim());
}
private static String getFilename(String header) {
int beginIndex = 0;
int endIndex = header.indexOf(' ');
return header.substring(beginIndex, endIndex);
}
}

How to keep asking for a console input running even after program execution

I am trying to execute a program after taking user input from the console. [code block below]. However, I do not want to terminate after the program execution finishes. I want the console to always ask me the INITIAL_MESSAGE after the execution finishes. Effectively, after the execution of the program, I want the console to again ask me the INTIAL_MESSAGE so that I can again enter the inputs as I want and execute the program again.
I am actually calling the interactor() in this method, from the main method as the starting point.
Please tell me how do I achieve this
public class ConsoleInteraction {
/**
* #param args
*/
public static int numberOfJavaTrainees ;
public static int numberOfPHPTrainees ;
Barracks trainingBarrack = new Barracks();
public void interactor() throws IOException {
//reading capability from the consolemessages properties file
ResourceBundle bundle = ResourceBundle.getBundle("resources/consolemessages");
// Create a scanner so we can read the command-line input
Scanner scanner = new Scanner(System.in);
// Prompt for training or viewing camp
System.out.print(bundle.getString("INITIAL_MESSAGE"));
//Get the preference as an integer
int preference = scanner.nextInt();
//Show options based on preference
if(preference == 1)
{
//System.out.println("Whom do you want to train?\n 1.Java Guy \n 2.PHP Guy \n 3.Mix \n Enter You preference:");
System.out.print(bundle.getString("WHO_TO_TRAIN"));
int traineepreference = scanner.nextInt();
if (traineepreference == 1)
{
//System.out.println("How many Java guys you want to train ? : ");
System.out.print(bundle.getString("HOW_MANY_JAVA"));
numberOfJavaTrainees = scanner.nextInt();
trainingBarrack.trainTrainees(numberOfJavaTrainees, 0);
}
else if (traineepreference == 2)
{
//System.out.println("How many PHP guys you want to train ? : ");
System.out.print(bundle.getString("HOW_MANY_PHP"));
numberOfPHPTrainees = scanner.nextInt();
trainingBarrack.trainTrainees(0, numberOfPHPTrainees);
}
else if (traineepreference == 3)
{
System.out.print(bundle.getString("HOW_MANY_JAVA"));
numberOfJavaTrainees = scanner.nextInt();
System.out.print(bundle.getString("HOW_MANY_PHP"));
numberOfPHPTrainees = scanner.nextInt();
trainingBarrack.trainTrainees(numberOfJavaTrainees, numberOfPHPTrainees);
}
else
{
System.out.print(bundle.getString("ERROR_MESSAGE1"));
}
}
else if (preference == 2)
{
System.out.println("Showing Camp to You");
System.out.println("Java trained in Trainee Camp : "+ TraineeCamp.trainedJavaGuys);
System.out.println("PHP trained in Trainee Camp : "+ TraineeCamp.trainedPHPGuys);
}
else
{
System.out.print(bundle.getString("ERROR_MESSAGE2"));
}
scanner.close();
}
}
Consider these changes quickly drafted to your class. Might not compile. Might not work as you planned.
Some highlights of what I think you should change:
Use constants for the choice values. Makes your code way more better to read.
Initialize Bundle and Scanner outside of the method. Might be reused.
instead of coding lengthy parts of code inside of the if-else-if cascade, call methods there - angain increasing your readability a long way
public class ConsoleInteraction {
public static int numberOfJavaTrainees ;
public static int numberOfPHPTrainees ;
//Don't read that every time...
ResourceBundle bundle = ResourceBundle.getBundle("resources/consolemessages");
public static void main(String[] args) {
//Moving Scanner out of loop
try {
Scanner scanner = new Scanner(System.in);
ConsoleInteraction ci = new ConsoleInteraction();
//Loop until this returns false
while(ci.interactor(scanner)) {
System.out.println("=== Next iteration ===");
}
} catch (IOException e) {
e.printStackTrace();
}
}
//Constant values to make code readable
public final static int PREF_TRAINING = 1;
public final static int PREF_SHOW_CAMP = 2;
public final static int PREF_QUIT = 99;
public boolean interactor(Scanner scanner) throws IOException {
// Prompt for training or viewing camp
System.out.print(bundle.getString("INITIAL_MESSAGE"));
//Get the preference as an integer
int preference = scanner.nextInt();
//Show options based on preference.
if(preference == PREF_TRAINING) {
//LIKE YOU DID BEFORE OR calling method:
readTraining(scanner);
} else if (preference == PREF_SHOW_CAMP) {
//LIKE YOU DID BEFORE OR calling mathod:
showCamp();
} else if (preference == PREF_QUIT) {
//Last loop
return false;
} else {
System.out.print(bundle.getString("ERROR_MESSAGE2"));
}
//Next loop
return true;
}
}

Beginner at Java through APCS first post. Is my Java program actually executable after compiling correctly? I think I may be somehow stuck in a loop

This chapter of the course is teaching us about methods in Java, more specifically returning values. While the rubric called for it to just be able to apply values from a .txt list the 9 planets provided below the program. I wanted to go beyond and make it so that there would be no limit on the amount of celestial bodies this could apply to (as I did with the program that created the .txt as an output). I have a finished program by another student available to me. However, I'd rather try approaching it in another way(Though I must thank Omar because I had no idea you could return arrays from methods).
Currently, as is, the program compiles without any errors in BlueJ. However, It does not run, or even put out any test print statements I put in. It's been running for over an hour on core 2 of my overclocked i5, but nothing. Since the core is being stressed, I assume it's stuck in a loop somehow?
How may I solve this issue?
I really appreciate any advice, and hope to spend more time here in the future.
/**
* 7.04 This program will take gravity and textual data from a .txt
* and will perform calculations with it once I figure out how that may be done.
*
*
* #author ********
* #version (The Date)
*/
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class Weight2
{
// write static methods here
// Note: formula for finding weight on a planet: Earth weight divided by Gravity constant times surface gravity
public static String[] getData(int arraylength,int i, int value) {
String [] Gravityscan = new String[arraylength]; //Initiates String Arrays to be used
String [] pregravity = new String[arraylength];
String [] names = new String[arraylength];
String [] prevalues = new String[arraylength];
String [] error = {"error"};
String delims = "[ |\\ ]+"; // Sets Delimiters
File data2 = new File("Gravityoutput.txt"); //Opens data source
Scanner inFile = new Scanner("Gravityoutput.txt");
for(int m = 0; m < arraylength ; m++)
{
Gravityscan[m] = inFile.nextLine(); //String for each line being run
prevalues = Gravityscan[m].split(delims); //Split into two (gravity name)
pregravity[m] = prevalues[0]; //Sorts gravity string to array
names[m]= prevalues[1]; //Sorts name string to array
}
inFile.close();
//if (value == 0){return Integer.toString(arraylength);}
if (value == 1){return pregravity;} //Returns pregravity string for first part of loop below
else if (value == 2){return names;} //Returns names to end of for string below
else {System.out.print("AN ERROR HAS OCCURED IN METHOD GETDATA"); return error;}
}
//public static double calcWeight() {
//}
public static void main(String[] args)throws IOException
{
Scanner in = new Scanner(System.in);//Scanner activated
File data = new File("Gravityoutput.txt"); //Select file to get data from
Scanner inFile = new Scanner("Gravityoutput.txt");
int arraylength = 0; //Works with loop to determine length of data
while (inFile.hasNext())
{
arraylength++;
}
inFile.close(); //Closes file
System.out.print("arraylength is " + arraylength);//Beta testing check
double [] gravities = new double[arraylength]; //Declaring double array for after string conversion
//String[] names = new String[arraylength]; //Declaring array to be used for names
System.out.print("Please enter your mass on Earth in lbs: "); //User input for math
double earthWeight = in.nextDouble();
for(int i=0; i < arraylength; i++)
{
int value = 1;
String[] stringgravity = getData(arraylength, i, value);
gravities[i] = Double.parseDouble(stringgravity[i]);
System.out.print(gravities[i] + " gravity ");
value++;
String[] names = getData(arraylength, i, value);
System.out.println(names[i] + "gravity");
// static method you write Double.parseDouble
}
//double[] weight = calcWeight(earthWeight, gravity); // static method you write
//printResults(names, gravity, weight); // static method you write
} //end main
}//end class
//Below is the data contained by Gravityoutput.txt
3.70 Mercury
8.87 Venus
9.82 Earth
3.70 Mars
24.78 Jupiter
10.44 Saturn
8.86 Uranus
11.13 Neptune
0.61 Pluto
Creating an instance of Scanner with Scanner inFile = new Scanner("Gravityoutput.txt"); does not read input from the file, it reads input from the String "Gravityoutput.txt".
Try Scanner inFile = new Scanner(data); instead.
Oh, and your code is stuck in a loop :
inFile.hasNext() always returns true, since you never read anything from the Scanner.
You can replace it with
while (inFile.hasNext())
{
String str = inFile.next();
arraylength++;
}

Reading every other line from a txt file and saving into an array

assignment:
A school that your little cousin attends is selling cookies. If your cousin's class sells more cookies than any other class, the teacher has promised to take the whole class on a picnic. Of course, your cousin volunteered you to keep track of all the sales and determine the winner.
Each class is identified by the teacher's name. Each sales slip has the teacher's name and the number of boxes sold. You decide to create two parallel arrays: one to hold the teacher's names and one to record the number of boxes sold. Here is a sample of the data:
The first number gives the number of classes, and then a teacher's Name is followed by the number of boxes sold
15
Smith
3
Courtney
... so on so forth
My main issue (because i can just duplicate it for the "to-be" parrallel array)
is getting every other line to save into an array for the boxes sold
so array "boxSold"
would look like
[1] 15
[2] 3
package assignment5Package;
import java.util.Scanner;
import java.io.*;
public class assignment5Demo
{
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException
{
// TODO Auto-generated method stub
//create arrays, variables
Scanner keyboard = new Scanner(System.in);
BufferedReader input = new BufferedReader
(new FileReader ("/Users/lee/Desktop/class/cs 113/Assignment5/cookies.txt"));
System.out.println("How many sale slips are there");
int numSaleSlips = keyboard.nextInt();
int[] soldBox = new int[numSaleSlips];
//______String[] teacherName = new String[numSaleSlips];
int soldBoxIndex;
int teacherNameIndex;
//String soldBoxString; (line 50)
//initializing both strings to 0 and "_"
for (soldBoxIndex = 0; soldBoxIndex < numSaleSlips; soldBoxIndex++)
{
soldBox[soldBoxIndex] = 0;
}
//**for (teacherNameIndex = 0; teacherNameIndex < numSaleSlips; teacherNameIndex++)
//**{
//** teacherName[teacherNameIndex] = "_";
//**}
//reading from the cookies.txt file
for (soldBoxIndex = 0; soldBoxIndex < numSaleSlips; soldBoxIndex++)
{
if (soldBoxIndex % 2 != 0
{
String soldBoxString;
soldBoxString = input.readLine(); //reads in value and assigns/re-assigns
soldBox[numSaleSlips] = (int) Double.parseDouble(soldBoxString); //type-casted to fit variable type, converts to double, stores in array
System.out.println(soldBox[soldBoxIndex]);
}
else
{
System.out.println("Error at " + soldBoxIndex +".");
}
}
}
The following may be a quick-and-dirty solution, but will get the job done:
for (soldBoxIndex = 0; soldBoxIndex < numSaleSlips; soldBoxIndex++)
{
if (soldBoxIndex % 2 != 0
{
String soldBoxString;
soldBoxString = input.readLine(); //reads in value and assigns/re-assigns
soldBox[numSaleSlips] = (int) Double.parseDouble(soldBoxString); //type-casted to fit variable type, converts to double, stores in array
System.out.println(soldBox[soldBoxIndex]);
}
else
{
input.readLine(); //read the following line, but ignore its content, effectivly skipping the line
}
}
You might also need to work the numbers of the for-loop a bit, to accomodate the skipped line.

Categories

Resources