Output line numbers parallel to output - java

thank you all for looking.
I am a beginner to Java and have been for a few years.
I am not looking for the answer but would like some to tips to finish my query.
I want to output line numbers with my out put of code in netbeans.
I am guessing a while loop would be sufficient.
I would like my output to look like the below example:
I am looking to add line numbers to my output like they are in bold below.
1: Enter a line
Some input
2: Enter another line
More input
3: Enter the last line
The end
The end,More input,Some input
HERE IS my code i would like to add to:
Scanner in = new Scanner(System.in);
String msg1, msg2, msg3;
System.out.println("Enter a line");
msg1 = in.nextLine();
System.out.println("Enter another line");
msg2 = in.nextLine();
System.out.println("Enter the last line");
msg3 = in.nextLine();
System.out.println(msg3 + "," + msg2 + "," + msg1);
This is what I am guessing i should add, however I may be totally wrong
int count = 0;
while (count ??????) {
count++;
System.out.println(count + "" + ?????????????());
}
Thank you in advance for any advice,
regards

Seems like your homework, but I would answer it anyway
Scanner in = new Scanner(System.in);
String msg1, msg2, msg3;
int count = 0;
System.out.println(++count + ": Enter a line");
msg1 = in.nextLine();
System.out.println(++count + ": Enter another line");
msg2 = in.nextLine();
System.out.println(++count + ": Enter the last line");
msg3 = in.nextLine();
System.out.println(msg3 + "," + msg2 + "," + msg1);

Related

Print to console in 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.

Making a MadLib in Java - User Input Erroring

I am VERY new to Java and I'm trying to make a madlib that takes user input and inserts it into a sentence. So far, I'm not having much luck. When I run the program, it prompts me for the first input, but after that it errors out. Do you know why? I think it has something to do with data types (int, string, etc).
Bonus question: How would I make the inputs appear bold once inserted into the paragraph? Assuming I can get this code to work in the first place.
Here is my code:
import java.util.Scanner;
public class Madlib
{
public static void main(String[] args)
{
int firstName, childAge, colorToy, typeToy;
Scanner input = new Scanner(System.in);
System.out.println("Enter someone's first name:");
firstName = input.nextInt();
System.out.println("Enter a child's age:");
childAge = input.nextInt();
System.out.println("Enter a color:");
colorToy = input.nextInt();
System.out.println("Enter a toy:");
typeToy = input.nextInt();
System.out.println("\"I am" + childAge + "years old, so that means I get to have the" + colorToy + typeToy + "!\" exclaimed the little girl.");
System.out.println("\"Share with your sister,\"" + firstName + "grovelled, barely peering over their large, Sunday newspaper.");
}
}
You have this error because
firstName, childAge, colorToy, typeToy
should all not supposed to be an integer. They are supposed to be String You should be doing
firstName = input.nextLine();
childAge = input.nextLine();
colorToy = input.nextLine();
typeToy = input.nextLine();
Also, this is not part of your question; however, when you do
System.out.println("\"I am " + childAge + " years old, so that means I get to have the " + colorToy + " " + typeToy + "!\" exclaimed the little girl.");
System.out.println("\"Share with your sister,\"" + " " + firstName + " grovelled, barely peering over their large, Sunday newspaper.");
It should look like that with spaces included in places that you didn't have them in. I hope this answered your question!

How to keep a string input within a loop

I'm making a program that takes a string from the user and separates it word by word with a delimiter, and it's almost complete. However, after the first full loop, the next input from the user doesn't pass through the last while loop.
Here's the segment of code I'm talking about:
do
{
System.out.println ("\nEntered String: " + s1 + "\n");
while (input.hasNext())
{
word++;
System.out.println ("Word #" + word + ": \t" + input.next());
}
System.out.print ("\nEnter 'q' to quit, enter string to continue: \t");
s1 = scan.nextLine();
} while (!s1.equals("q"));
I'm thinking that I need another while loop around the word increment and print line and have the continue sequence within the input.hasNext() loop, because that's how I got a similar program using int to work, but I'm not sure how that would work with strings.
Any advice?
EDIT: to clarify, right now the output of my code looks like this:
Enter a sentence: this is a sentence
Entered String: this is a sentence
Word #1: this
Word #2: is
Word #3: a
Word #4: sentence
Enter 'q' to quit, enter string to continue: another sentence
Entered String: another sentence
Enter 'q' to quit, enter string to continue:
I need 'another sentence' to print out like 'this is a sentence'
I do not understand exactly what's the problem since your code does not compile. But there is no need for another loop. Here is a bit of code that works:
Scanner scan = new Scanner(System.in);
System.out.print("\nEnter a sentence:");
String s1 = scan.nextLine();
do
{
System.out.println("\nEntered String: " + s1 + "\n");
Scanner input = new Scanner(s1);
int word = 0;
while (input.hasNext())
{
word++;
System.out.println("Word #" + word + ": \t" + input.next());
}
System.out.print("\nEnter 'q' to quit, enter string to continue: \t");
s1 = scan.nextLine();
} while(!s1.equals("q"));
scan.close();
You can try this if it works. It has the same results with the one you need.
Scanner scan = new Scanner(System.in);
String s1 = scan.nextLine();
do {
String input[] = s1.split(" ");
System.out.println ("\nEntered String: " + s1 + "\n");
for(int i = 0; i < input.length; i++) {
System.out.println ("Word #" + i+1 + ": \t" + input[i]);
}
System.out.print ("\nEnter 'q' to quit, enter string to continue: \t");
s1 = scan.nextLine();
} while (!s1.equals("q"));
You are using
while (input.hasNext())
I suppose input is a Scanner object, so you should do something like this before using it (but before entering the loop):
Scanner input = new Scanner(System.in);
Instead of using scanner.next() in while loop, I would recommend doing the following API:
String.split
Scanner.nextLine
Something like this:
while(input.hasNextLine()) {
String line = input.nextLine();
String[] words = line.split("delimeter");
if(words.length < 1 || words[words.length - 1].equals("q")) {
break;
}
}

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.

Categories