I am new at Java so thank you for helping!
public static int convert (String value) {
int temp_convert = 0;
// Setting up new Scanner to read the User-input string
Scanner token = new Scanner(value);
// Take out the word "CONVERT"
String fnc = token.next();
// Get the temperature that needs to be converted
int temp = token.nextInt();
// Current unit of temperature
String type = token.next().toLowerCase();
if (type.equals("f")) {
temp_convert = (int) Math.round((temp - 32)/1.8);
System.out.println(temp_convert + "C");
} else if (type.equals("c")) {
temp_convert = (int) Math.round(1.8 * temp + 32);
System.out.println(temp_convert + "F");
}
return temp_convert;
}
I am trying to get the print result from this method into an output file using PrintStream. I need whatever is lines printed in this method to be print out into the output file. How can I do this? This is the code I have so far but it doesn't produce anything in the .txt file yet.
public static void readFile (Scanner console, String file_input) throws FileNotFoundException {
// Setting up new Scanner to scan the file
Scanner input = new Scanner (file_input);
// Prompt user for output file's name
System.out.print("Output file name: ");
String name_output = console.next();
PrintStream file_output = new PrintStream(new File(name_output));
System.out.println("YazLang program interpreted and output to .txt file!");
System.out.println();
while (input.hasNext()) {
String value = input.nextLine().toLowerCase();
if (value.startsWith("convert")) {
int concert_temp = convert(value);
file_output.println(concert_temp);
} else if (value.startsWith("range")) {
range(value);
} else if (value.startsWith("repeat")) {
repeat(value);
}
}
}
Why don't you change signature of convert method to return int?
public static int convert (String value) {
Scanner token = new Scanner(value);
// ...
return value;
}
And then write result to file in readFile method like this:
public static void readFile (Scanner console, String file_input) throws FileNotFoundException {
// omitted..
while (input.hasNext()) {
String value = input.nextLine().toLowerCase();
if (value.startsWith("convert")) {
int concert_temp = convert(value);
file_output.println(concert_temp);
} else if (value.startsWith("range")) {
// here
int concert_temp = range(value);
file_output.println(concert_temp);
} else if (value.startsWith("repeat")) {
repeat(value);
}
}
}
you can use System.setOut() (https://www.tutorialspoint.com/java/lang/system_setout.htm)
Insert this line after line 7 in your readFile method:
System.setOut(file_output);
There are two options:
Define the PrintStream in the outer most function, then pass it to whichever function you need. Proceed to write to file using PrintStream::print... method.
Define a wrapper class that will write to both stream:
public class DuplexPrinter {
private final PrintStream printStream;
public DuplexPrinter(PrintStream printStream) {
this.printStream = printStream;
}
public void println(String line) {
System.out.println(line);
printStream.println(line);
}
public void close() {
printStream.close();;
}
}
Init printer:
DuplexPrinter printer = new DuplexPrinter(file_output);
Now replace every call to System.out.println with:
printer.println()
Using third party library. For example TeeOutputStream
Related
I'm new to Java and would appreciate any assistance to solve the following problem.
I would like the java program to read and print a two column (integer or double) text file and search for a value in the first column that matches with another parameter within the java code. If the match is found, to print out the corresponding value on the second column. I wrote the following code which can read and print the data in console but I'm unable to use this data in the next code to search for a value in the first column that matches with another parameter. please help,here is my code:
import java.io.File;
import java.util.Scanner;
public class readfile {
private Scanner s;
public static void main(String[] args) {
readfile r = new readfile();
r.openFile();
r.readFile();
r.closeFile();
}
public void openFile() {
try {
s = new Scanner (new File("filename.txt"));
}catch(Exception e) {
System.out.println("file not found ");
}
}
public void readFile() {
while(s.hasNext()) {
String a = s.next();
String b = s.next();
System.out.printf("%s %s\n",a, b);
}
}
public void closeFile() {
s.close();
}
}
// here is the problem!
double a = 0;
double b = 0;
if (para == a[i]) {
System.out.println("param =" + a[j]);
}else {
System.out.println("It is out of range ");
}
I've just started with Java, and so far been only playing around solving problems online, where you're not supposed to write the whole functional of a program, but only adjust a few lines of code to the already organized code.
However, I'm still struggling to organize my code in a compiling program in IntelliJ Idea, getting confused at,e.g. how methods invocations must be properly written.
Here's what I'm getting stuck with: an example from codingbat.com:
- Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo".
I've come up with a solution online, but now I wanna run it in Idea, with main method, with Scanner/BufferedReader input from console etc. Looks like I'm missing something...
import java.util.Scanner;
public class Bat
{
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
printString();
}
public String stringBits(String str) {
String result = "";
for (int i = 0; i<str.length();i += 2) {
result += str.substring(i, i+1);
}
return result;
}
public static void printString () {
System.out.println(result);
}
}
I ask your help to solve it out. What to do to make it:
Read a word from a console;
create a new string;
print it out.
Two alternatives:
make stringBits static
create an instance of the class Bat and invoke the member method
First solution - easy, not much to change
import java.util.Scanner;
public class Bat {
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
printString(stringBits(str));
}
public static String stringBits(String str) {
String result = "";
for (int i = 0; i < str.length();i += 2) {
result += str.substring(i, i + 1);
}
return result;
}
public static void printString (String string) {
System.out.println(string);
}
}
Second solution - a bit more advances
import java.util.Scanner;
public class Bat {
private String string;
public Bat(String string) {
this.string = string;
}
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
Bat bat = new Bat(str);
bat.printStringBits();
}
private String stringBits() {
String result = "";
for (int i = 0; i < string.length(); i += 2) {
result += string.substring(i, i + 1);
}
return result;
}
public void printStringBits() {
System.out.println(stringBits());
}
}
Your result variable is only accessible from within the "stringBits" method. Since the method returns a string you can do the following to print it:
System.out.println(stringBits(string)); //Call in main method in place of printString();
Edited: My code wasn't a working example. Note that stringBits has to be a static method in order to work.
I have this code i'm working on to compute the ARI of a given text read from the a .txt file. This code works perfectly but I want to put in fewer things in my main method. How is it able to put my try and catch block in a new method and then call it to my main method instead of having everything mashed together? I have tried some few ways but i'm not getting the usual output.
Here is my main class:
public class MyClass {
public static void main(String[] args){
String EachSentence;
int wordCount;
List<Sentence> sentences = new ArrayList<>();
List<Integer> EachWordCount = new ArrayList<>();
List<Integer> EachLetterCounted= new ArrayList<>();
try{
File file = new File("a2b.txt");
Scanner scanner = new Scanner(file);
scanner.useDelimiter("[.?!]");
int SentenceCount =0;
while(scanner.hasNext()){
SentenceCount++;
EachSentence = scanner.next();
EachSentence = EachSentence.replaceAll("\\r?\\n", " ");
EachSentence = EachSentence.trim();
if (sentences.add(new Sentence(EachSentence)) && sentences.size() > 1){
System.out.println("(" + SentenceCount + ") " + EachSentence);
}
StringTokenizer tokenizer = new StringTokenizer(EachSentence, " ");
wordCount = tokenizer.countTokens();
if(EachWordCount.add(wordCount)&& EachWordCount.size() > 1){
//I removed the element at position 0 so as to correlate with EachSentence then added the counts to the arrayList
//to prepare them for addition
EachWordCount.remove(0);
EachWordCount.add(wordCount);
}
int LetterCount=1;
for(int i=1; i<EachSentence.length(); i++){
char currentChar = EachSentence.charAt(i);
if(currentChar != ' '&& currentChar!='('&¤tChar!=')'&¤tChar!=','&& currentChar!='.'){
EachLetterCounted.add(LetterCount);
LetterCount++;
}
}
}
scanner.close();
}catch (IOException ex){
System.out.println(ex.getMessage());
}
//Computes the ARI of the total sentences
double lettersCounted = (double) lettersCounted(EachLetterCounted);
double wordsCounted = (double) sum(EachWordCount);
double sentencesCounted = (double) SentencesCounted(EachWordCount);
double AutomatedReadabilityIndex= 4.71*(lettersCounted/wordsCounted) + 0.5 * (wordsCounted/sentencesCounted) -21.43;
System.out.println("\nSummary statistics: ");
System.out.println("Letters: "+lettersCounted(EachLetterCounted));
System.out.println("Words: "+ sum(EachWordCount));
System.out.println("Sentences: " + SentencesCounted(EachWordCount));
DecimalFormat df = new DecimalFormat("#.##");
System.out.println("readability: "+ df.format(AutomatedReadabilityIndex));
}
contributions would be great!
Second time answering my question.(For anyone having the same problem) I achieved this by simply putting everything I had in the main method in a ...static void ReadFile() method and calling only `ReadFile in the main method. It may not be the best way but it was what I was looking for :)
public static void main(String[] args) {
ReadFile();
}
public static void ReadFile() {
//insert all what is in main method, the exceptions were handled
//here also. So there was no need for the throws IOException that
//should've followed.
}
OR
public static void main(String[] args) {
ReadFile(//insert name of file to be read here);
}
public static void ReadFile(String filename) {
//insert all what is in main method, the exceptions were handled
//here also. So there was no need for the throws IOException that
//should've followed.
}
I've been coding a while for an assignment but can't figure out how
to receive a string input from the user to have the sentences filtered by unicode.
When I try to run the code, the input prompt won't happen. What am I doing wrong?
Any advice is appreciated.
package deel1;
import java.util.*;
public class Deel1 {
public static void main(String[] args) {
}
static String getInput() {
Scanner scan = new Scanner(System.in);
String zin = "";
System.out.println("Voer een zin in: ");
if (scan.hasNextLine()) {
zin = scan.nextLine().trim();
}
if (zin.equals("")) {
System.out.println("Geen invoer!");
System.exit(0);
}
return zin;
}
static String filterZin(String zin) {
for (int groteLetters = 65; groteLetters <= 90; groteLetters++) {
groteLetters = groteLetters + 32;
char kleineLetterAlfabet = (char) groteLetters;
}
int specialeTekens1 = 33;
int specialeTekens2 = 58;
int specialeTekens3 = 91;
if (specialeTekens1 <= 47 && specialeTekens2 <= 64 && specialeTekens3 <= 96) {
System.out.println("");
}
System.out.println("Gefilterd: " + zin);
}
}
Nah, come on, nobody posted an answer?
As Rohit pointed out, you never invoked the function!
//this method is the entry point
public static void main(String[] args) {
// invoke getting input, store it in local variable
String input = getInput();
//invoke filtering method, store result in lcal variable
String output = filterZin(input);
}
The filterZin method doesn't really do anything...
Bigger problem, that it is not even valid! The filterZin method is specified to have a String return type - and nothing gets returned. Add a return statement to the end, to get at least a syntactically correct method...
You wrote a method getXYZ() which returns a String when called.
This is your method definition:
static String getInput() {
//your code
return someString;
}
This says, when you'll call this method at any point in the program, this method will return a String object.
Inside your main method:
String returnString = getInput();
This is called method calling or invocation. You will not receive something until you call for it.
Now, about your program asking for input from user.
Here's a simple code for that:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//This will create a chain for input from console
System.out.println("Enter a line:");
String userInput;
try{
userInput = br.readline();
}catch(IOException e){
e.printStackTrace();
}
I am writing some simple code to parse a file and return the number of lines but the little red box in eclipse won't go off so I assume I am triggering an infinite loop. Th Text file i am reading has only 10 lines...here's the code: What am I doing wrong?
import java.io.*;
import java.util.Scanner;
public class TestParse {
private int noLines = 0;
public static void main (String[]args) throws IOException {
Scanner defaultFR = new Scanner (new FileReader ("C:\\workspace\\Recommender\\src\\IMDBTop10.txt"));
TestParse demo = new TestParse();
demo.nLines (defaultFR);
int x = demo.getNoLines ();
System.out.println (x);
}
public TestParse() throws IOException
{
noLines = 0;
}
public void nLines (Scanner s) {
try {
while (s.hasNextLine ())
noLines++;
}
finally {
if (s!=null) s.close ();
}
}
public int getNoLines () {
return noLines;
}
}
You're not calling s.nextLine() in the while-loop:
should be:
while(s.hasNextLine()){
s.nextLine(); // <<<
noLines++;
}
You only check hasNextLine within your loop. This checks if another line is present but does not read it. Let it follow by nextLine and your code will work.
while(s.hasNextLine()){
s.nextLine();
noLines++;
}