Print to console in JAVA - java

I have a simple question. My program asks the user to type a name, range, and length to generate random numbers. The result will be printed into a file from the console. I want to know is it possible to print to the console that the file has been printed when it's done.
Currently this is my set up to print to a file:
Scanner s = new Scanner(System.in);
System.out.println("-----------------------------------------------");
System.out.println("Choose a name to your file: ");
String fn = s.nextLine();
System.out.println("-----------------------------------------------");
System.out.println("Choose your range: ");
String rn = s.nextLine();
System.out.println("-----------------------------------------------");
System.out.println("Choose your length of array: ");
String ln = s.nextLine();
System.out.println("-----------------------------------------------");
int rangeToInt = Integer.parseInt(rn);
int lengthToInt = Integer.parseInt(ln);
File file = new File(fn +".txt");
PrintStream stream = new PrintStream(file);
//System.out.println("File Has been Printed");
System.setOut(stream);
int[] result = getRandomNumbersWithNoDuplicates(rangeToInt, lengthToInt);
for(int i = 0; i < result.length; i++) {
Arrays.sort(result);
System.out.println(result[i] + " ");
}
System.out.println("Current Time in Millieseconds = " + System.currentTimeMillis());
System.out.println("\nNumber of element in the array are: " + result.length + "\n");
}// end of main
```

Don't call System.setOut. When you do that, you can no longer print to the console. Instead of System.out.println to write to the file, just... stream.println to write to the file. Then you can use System.out to print to the console.

Related

How to avoid having to declare a new scanner inside do while loop

I have created a program that allows a user to keep guessing numbers until they either guess the correct number or enter end. I have used a do-while loop to do this. When I create a new scanner inside the loop body it works as expected. However if I create it outside the loop body, it works fine if the input is integers or the first input is end However if the input end follows integer inputs it doesn't
pick up the nextLine() until the next loop. Is there a way to do this without having to creat a new scanner object each time.
private static void guessingGame() {
Scanner sc = new Scanner(System.in);
int answer = 7;
String input = "";
int number = 0;
do {
//Scanner sc = new Scanner(System.in);
System.out.print("Guess a number between 1 and 10 or end to finish ");
System.out.println("input at start is: " + input);
boolean b = sc.hasNextInt();
if(b) {
number = sc.nextInt();
System.out.println("number is: " + number); //for testing code
}else {
input = sc.nextLine();
System.out.println("input is: " + input); //for testing code
}
if (number == answer) {
System.out.println("Correct Guess");
break;
}else {
if(input.equals("end")) System.out.println("Hope you enjoyed the game");
else System.out.println("Incorrect Guess, try again ");
}
System.out.println("input before while is: " + input); //for testing code
}while(number != answer && !(input.equals("end")));
}
Example output for when end follow an integer input:enter code here
number is: 3
Incorrect Guess, try again
input before while is:
Guess a number between 1 and 10 or end to finish input at start is:
end
input is:
Incorrect Guess, try again
input before while is:
Guess a number between 1 and 10 or end to finish input at start is:
input is: end
Hope you enjoyed the game
input before while is: end
you can solve this by using a while loop .
See the following code.
private static void guessingGame() {
Scanner sc = new Scanner(System.in);
int answer = 7;
String input = "";
int number = 0;
while(!input.equals("end")) {
//Scanner sc = new Scanner(System.in);
System.out.print("Guess a number between 1 and 10 or end to finish ");
System.out.println("input at start is: " + input);
boolean b = sc.hasNextInt();
if(b) {
number = sc.nextInt();
System.out.println("number is: " + number); //for testing code
}else {
input = sc.next(); //Edited here . Changed nextLine() to next().
System.out.println("input is: " + input); //for testing code
}
if (number == answer) {
System.out.println("Correct Guess");
break;
}else {
if(input.equals("end")) System.out.println("Hope you enjoyed the game");
else System.out.println("Incorrect Guess, try again ");
}
System.out.println("input before while is: " + input); //for testing code
}
}
In here , at first , input will always be empty String . On while loop, it gets assigned to your String input i.e, end . Till it encounters end , your loop will be running.
Edited
Change input=sc.nextLine(); to input=sc.next(); . This is because , your scanner waits for next Line and doesn't consider "end" as input string .

How to store input line by line from an input file into variables

I am trying to store input of certain data types into variables and print them out into a output file but my code does not seem to work. If I enter the input through std in with System.in Scanner and print to stdout, my code will work. However, when I try what I have, I keep getting this:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Queue.main(Queue.java:17)
Here is my code:
import java.util.*;
import java.io.*;
public class Queue {
public static void main(String[] args) throws IOException {
// open files
// takes input from test-input.txt
Scanner input = new Scanner(new File("test-input.txt"));
// prints output to test-output.txt
PrintWriter output = new PrintWriter(new FileWriter("test-output.txt"));
//Scanner input = new Scanner(System.in);
while (input.hasNextLine()) {
int teller = input.nextInt();
String name = input.next();
int simTime = input.nextInt();
int transTime = input.nextInt();
output.println(teller + " " + name + " " + simTime + " " + transTime);
}
// close files
input.close();
output.close();
}
}
My input file contains lines such as:
1 Jesse 2 9
2 Wilson 1 4
3 King 4 8
4 Andy 6 7
You're never consuming the newline character after the transTime
int transTime = input.nextInt();
input.nextLine();
You could also consume the entire line at once, and then split it into types
Try to make sure you are parsing a non empty line, it can happen if your file has extra empty lines, so i suggest do a check inside your while statement
while (input.hasNextLine()) {
final String line = input.nextLine().trim();
if (line.isEmpty()) continue; // continue if line is empty
String [] items = line.split("\\s+");
int teller = Integer.parseInt(items[0]);
String name = items[1];
int simTime = Integer.parseInt(items[3]);
int transTime = Integer.parseInt(items[3]);
output.println(teller + " " + name + " " + simTime + " " + transTime);
}

Arrays and Output in Java

So I am trying to write a program that automates making an Operations Order (or OPORD). It is pretty straight forward, but I am having some issues with my arrays, more specifically how to get them to display properly in the output.
Here is my code:
import java.util.*;
import java.util.Scanner;
public class opord {
public static void main(String[] args){
//Variables
int opord_type, phase_a = 0, n = 1, tasks = 0, phase_b = 0, phase_c = 0;
//Strings for paragraph 1
String area_interest = " ", area_ops = " ", enemy_forces = " ", weather = " ", terrain = " ", friendly_forces = " ", civil_consid = " ", attach_detach = " ";
//Strings for paragraph 2
String who = " ", what = " ", where = " ", when = " ", why = " ";
//Strings for paragraph 3
String commander_intent = " ", phases;
Scanner keyboard = new Scanner(System.in);
//Array Lists
ArrayList alist = new ArrayList();
ArrayList blist = new ArrayList();
ArrayList clist = new ArrayList();
//Page One
System.out.println("Welcome to Automated OPORD");
System.out.println("Please choose which type of OPORD you want: (1:Garrison, 2:Tactical)");
opord_type = keyboard.nextInt();
if(opord_type == 1){
//Page Two
System.out.println("Paragraph One: ");
System.out.println("Situation: ");
//Indent One
System.out.println("Enter area of interest: ");
area_interest = keyboard.next();
System.out.println("Enter area of operations: ");
area_ops = keyboard.next();
//Indent Two
System.out.println("Enter weather: ");
weather = keyboard.next();
System.out.println("Enter terrain: ");
terrain = keyboard.next();
//End Indent Two
System.out.println("Enter enemy forces: ");
enemy_forces = keyboard.next();
System.out.println("Enter friendly forces: ");
friendly_forces = keyboard.next();
System.out.println("Enter civil considerations: ");
civil_consid = keyboard.next();
System.out.println("Enter attachments and detachments: ");
attach_detach = keyboard.next();
//End Indent One
//Page Three
System.out.println("Paragraph Two: ");
System.out.println("Mission");
//Indent One
System.out.println("Enter who: ");
who = keyboard.next();
System.out.println("Enter what: ");
what = keyboard.next();
System.out.println("Enter where: ");
where = keyboard.next();
System.out.println("Enter when: ");
when = keyboard.next();
System.out.println("Enter why: ");
why = keyboard.next();
//End Intent One
//Page Four
System.out.println("Paragraph Three: ");
System.out.println("Execution: ");
//Indent One
System.out.println("Enter commander's intent: ");
commander_intent = keyboard.next();
System.out.println("Concept of Operations");
//Indent Two
System.out.println("Enter number of phases: ");
phase_a = keyboard.nextInt();
for (int ph=0; ph<phase_a; ph++) {
System.out.println ("Enter phase " + (ph+1));
alist.add (keyboard.next());
}//End Indent Two
System.out.println("Scheme of Movement and Maneuver");
//Indent Three
System.out.println("Enter number of phases: ");
phase_b = keyboard.nextInt();
for (int p=0; p<phase_b; p++) {
System.out.println ("Enter phase " + (p+1));
blist.add (keyboard.next());
}//End Indent Three
System.out.println("Task to Subordinate Units");
//Indent Four
System.out.println("Enter number of tasks: ");
tasks = keyboard.nextInt();
for (int h=0; h<phase_b; h++) {
System.out.println ("Enter task " + (h+1));
clist.add (keyboard.next());
}
}else if(opord_type == 2){
}
//Output for Garrison
System.out.println("Output for Garrison");
for (int ph=0; ph<phase_a; ph++){
System.out.println("Phase " + n++ + ": " + alist.get(ph));
}
for (int p=0; p<phase_b; p++){
System.out.println("Phase " + n++ + ": " + blist.get(p));
}
for (int h=0; h<phase_c; h++){
System.out.println("Phase " + n++ + ": " + clist.get(h));
}
//Output for Tactical
}
}
I need the output of the phases and the tasks to look like this:
Concept of Operations:
Phase One: Here is some text that the user input
Phase Two: Here is some text that the user input
Phase Three: Here is some text that the user input
Phase (whatever the number the user input): Here is some text that the user input
Scheme of Movement and Maneuver:
Phase One: Here is some text that the user input
Phase Two: Here is some text that the user input
Phase Three: Here is some text that the user input
Phase (whatever the number the user input): Here is some text that the user input
Task to Subordinate Units:
Task One: Here is some text that the user input
Task Two: Here is some text that the user input
Task Three: Here is some text that the user input
Task (whatever the number the user input): Here is some text that the user input
Tactical is mostly mirrored with some changes so don't worry about that, I just need to fix this code so that. I just have to get this code finished, any help would be wonderful!
Thank you!
If I'm understanding you correctly, this is a question about how to create line breaks in the console output of a Java application.
The Character for this is "\n". Put that into print command when you want to do a line break.
//Page Three
System.out.println("\nParagraph Two: ");
System.out.println("Mission");
etc...
Further more, looking at your expected output (I don't know if this is important) but if you want to user input to be next to the text strings, rather than below, use System.out.print (without the ln at the end)
.println will do a line break after finishing the regular print operation

Suggestions with Strings from File

I am trying to read from a external file. I have successfully read from the file but now I have a little problem. The file contains around 88 verbs. The verbs are written in the file like this:
be was been
beat beat beaten
become became become
and so on...
What I need help with now is that I want a quiz like programe where only two random strings from the verb will come up and the user have to fill inn the one which is missing. Instead of the one missing, I want this("------"). My english is not so good so I hope you understand what I mean.
System.out.println("Welcome to the programe which will test you in english verbs!");
System.out.println("You can choose to be tested in up to 88.");
System.out.println("In the end of the programe you will get a percentage of total right answers.");
Scanner in = new Scanner(System.in);
System.out.println("Do you want to try??yes/no");
String a = in.nextLine();
if (a.equals("yes")) {
System.out.println("Please enter the name of the file you want to choose: ");
} else {
System.out.println("Programe is ended!");
}
String b = in.nextLine();
while(!b.equals("verb.txt")){
System.out.println("You entered wrong name, please try again!");
b = in.nextLine();
}
System.out.println("How many verbs do you want to be tested in?: ");
int totalVerb = in.nextInt();
in.nextLine();
String filename = "verb.txt";
File textFile = new File(filename);
Scanner input = new Scanner(textFile);
for (int i = 1; i <= totalVerb; i++){
String line = input.nextLine();
System.out.println(line);
System.out.println("Please fill inn the missing verb: ");
in.next();
}
System.out.println("Please enter your name: ");
in.next();
You can do something like this
import java.util.Scanner;
import java.io.*;
public class GuessVerb {
public static void main(String[] args) throws IOException{
Scanner in = new Scanner(System.in);
System.out.println("Enter a file name: ");
String fileName = in.nextLine();
File file = new File(fileName);
Scanner input = new Scanner(file);
String guess = null;
int correctCount = 0;
while(input.hasNextLine()) {
String line = input.nextLine(); // get the line
String[] tokens = line.split("\\s+"); // split it into 3 word
int randNum = (int)(Math.random() * 3); // get a random number 0, 1, 2
String newLine = null; // new line
int wordIndex = 0;
switch(randNum){ // case for random number
case 0: newLine = "------ " + tokens[1] + " " + tokens[2];
wordIndex = 0; break;
case 1: newLine = tokens[0] + " ------ " + tokens[2];
wordIndex = 1; break;
case 2: newLine = tokens[0] + " " + tokens[1] + " -------";
wordIndex = 2; break;
}
System.out.println(newLine);
System.out.println("Please fill inn the missing verb: ");
guess = in.nextLine();
if (guess.equals(tokens[wordIndex])){
correctCount++;
}
}
System.out.println("You got " + correctCount + " right");
}
}
Above is complete running program.

Exception in main thread java.util.NoSuchElementException

I'm working on this project to improve my skill in Java. My goal is to write a program that reads the line from a specified doc or text file (depending on which the user wants to open; int 2 or 1 respectively.) and then asks the user to input their document name (without the file extension), and then reads the first line in the document or text file. I want it to do this as many times as the user wants. But I keep getting NoSuchElementException while executing the code.
public class switches {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
System.out.println("How many files would you like to scan?");
System.out.println("Enter # of files to scan: ");
int countInput = input.nextInt();
input.close();
for (int count = 0; count < countInput;) {
System.out.println("Please enter a file name to scan. ");
System.out.println("1 for .txt, 2 for .doc");
Scanner keyboard = new Scanner(System.in);
int choice = keyboard.nextInt();
switch (choice) {
default: {
do {
System.out.println("Please pick "
+ "either 1: txt or 2: doc");
choice = keyboard.nextInt();
} while (choice != 1 && choice != 2);
}
case 1: {
System.out.println("Txt file name:");
keyboard.nextLine();
String txtName = keyboard.nextLine();
File openTxtFile = new File("C:/Users/Hp/Documents/" + txtName
+ ".txt");
Scanner firstTxtLine = new Scanner(openTxtFile);
String printedTxtLine = firstTxtLine.nextLine();
firstTxtLine.close();
System.out.println("The first line " + "of your text file is: "
+ printedTxtLine);
keyboard.close();
count++;
break;
}
case 2: {
System.out.println("Doc file name:");
keyboard.nextLine();
String docName = keyboard.nextLine();
File openDocFile = new File("C:/Users/Hp/Documents/" + docName
+ ".doc");
Scanner firstLine = new Scanner(openDocFile);
String printedDocLine = firstLine.nextLine();
firstLine.close();
System.out.println("The first line"
+ " of your word document is: " + printedDocLine);
keyboard.close();
count++;
break;
}
}
}
}
}
If you remove the line input.close(); on line 14. This should solve your problem. According to the documentation, it will throw a NoSuchElementException - "if input is exhausted".

Categories