How can I reloop this code? - java

My program requires the user to input a file name that they have in the working directory (which contains text) and then enter the output file name that is also already in the same directory. After that the user then must choose whether they want to Capitalize or lowercase all the text in the file.
Once they have chosen that they should be given the option to process another file. That's where I'm having trouble. After printing "Would you like to process another file? Y for Yes or N for No?" how do I Get it to loop back to the beginning?
Right now my code keeps looping back to the "Capitalize or lowercase all words" I need it to stop doing that and ask the user if they want to process another file, if so it needs to go back and ask the input and output file names again.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the input data file name:");
String fileInput = sc.next();
System.out.println("Please enter the output data file name:");
String fileOutput = sc.next();
while(true){
System.out.println("A: Capitalize all words.\nB: Lowercase all words.");
System.out.println("enter choice:");
char choice = sc.next().charAt(0);
if(choice == 'A'){
capitalize(fileInput, fileOutput);
}else{
lowercase(fileInput, fileOutput);
}
}
System.out.println("Process another file? Y for Yes or N for No");
}

You simply need to wrap all your code in the while loop, as follows; the while loop only repeats the code in it:
public static void main(String[] args) {
while (true) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the input data file name:");
String fileInput = sc.next();
System.out.println("Please enter the output data file name:");
String fileOutput = sc.next();
System.out.println("A: Capitalize all words.\nB: Lowercase all words.");
System.out.println("enter choice:");
char choice = sc.next().charAt(0);
if (choice == 'A') {
capitalize(fileInput, fileOutput);
} else {
lowercase(fileInput, fileOutput);
}
System.out.println("Process another file? Y for Yes or N for No");
String processAnother = sc.next();
if (processAnother.equals("N") || processAnother.equals("n")) break;
}
}

Related

Same code but different output

First i want user to input somethings(name,contact,idnumber),and i will show 2 different file but code are same.The first code problem is "name" input place disappear,and the second but doesn't disappear.Can anyone tell me the problem?Im new in java.
public class Admin {
static Scanner scan= new Scanner(System.in);
static Client client = new Client();
public void admin(){
newClient []nc = new newClient[10];
\\login();
while(true){
System.out.println("Select 1:add Client\n 2:add Account\n 3:login as Client");
try{
int selection = scan.nextInt();
switch(selection)
{
case 1: addClient(nc);
break;
case 2: \\addAccount(nc);
break;
case 3: ;
break;
default: System.out.println("INvalid selection");
}
}
catch(InputMismatchException ex){
System.out.println("Invalid input");
scan.nextLine();
}
}
}
public void addClient(newClient []nc){
for(int i=0;i<nc.length;i++){
System.out.println("Enter name");
String name = scan.nextLine();
System.out.println("Enter contact");
String contact = scan.nextLine();
System.out.println("Enter id number");
String idNumber = scan.nextLine();
nc[i]=new newClient(name,contact,idNumber);
System.out.println(nc[i]);
}
}
Output of the first code is
Enter name
Enter contact
Why the name input place is missing?
There are the second code
public static void main(String[]args){
Scanner scan =new Scanner(System.in);
for(int i=0;i<nc.length;i++){
System.out.println("Enter name");
String name = scan.nextLine();
System.out.println("Enter contact");
String contact = scan.nextLine();
System.out.println("Enter id number");
String idNumber = scan.nextLine();
nc[i]=new newClient(name,contact,idNumber);
System.out.println(nc[i]);
}
}
The second code is working correctly.
Enter name
Enter contact
Enter idNumber
The two pieces of code are in fact different.
In the second code, the scan object is a brand new one. And the only method you call is nextLine(). In the first code, the scan object is created an class level, and has been used before addClient is called.
"Has been used" here is very important. By that I mean you called nextInt on scan and then nextLine:
int selection = scan.nextInt(); <-- You called nextInt here!
switch(selection)
{
case 1: addClient(nc);
break;
case 2: \\addAccount(nc);
break;
case 3: ;
break;
default: System.out.println("INvalid selection");
}
}
catch(InputMismatchException ex){
System.out.println("Invalid input");
scan.nextLine();
}
}
}
public void addClient(newClient []nc){
for(int i=0;i<nc.length;i++){
System.out.println("Enter name");
String name = scan.nextLine(); <-- then you called nextLine here!
System.out.println("Enter contact");
String contact = scan.nextLine();
System.out.println("Enter id number");
String idNumber = scan.nextLine();
nc[i]=new newClient(name,contact,idNumber);
System.out.println(nc[i]);
}
}
This makes the nextLine method return an empty string.
Why?
Let's look at the documentation for both nextInt and nextLine:
nextInt()
Scans the next token of the input as an int.
nextLine()
Advances this scanner past the current line and returns the input that was skipped.
I have created a simpler code that reproduces this situation to explain why calling nextLine immediately after nextInt can cause problems:
Scanner s = new Scanner(System.in);
s.nextInt();
System.out.println(s.nextLine());
I will use a | character to denote where the scanner's current position is.
When the program starts,
|
Then I enter the number 20:
|20
Now the scanner reads the 20, according the documetation, the scanner should be at this position:
20|
Here comes the interesting part, nextLine "Advances this scanner past the current line and returns the input that was skipped."
20
|
So what input has the scanner skipped? Nothing! As a result, an empty string is returned.
as ΦXocę 웃 Пepeúpa ツ says scan.nextInt wouldnt read the enter.
so an alternative solution is before read name contact id information, employ scan.nextLine() to read the enter like this:
public void addClient(newClient []nc){
scan.nextLine();
for(int i=0;i<nc.length;i++){
....// your origin code
}

Need to close out java with the letter q

I'm pretty new to programming. I need it to say "Enter the letter q to quit or any other key to continue: " at the end. If you enter q, it terminates. If you enter any other character, it prompts you to enter another positive integer.
import java.util.Scanner;
public class TimesTable {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a postive integer: ");
int tableSize = input.nextInt();
printMultiplicationTable(tableSize);
}
public static void printMultiplicationTable(int tableSize) {
System.out.format(" ");
for(int i = 1; i<=tableSize;i++ ) {
System.out.format("%4d",i);
}
System.out.println();
System.out.println("------------------------------------------------");
for(int i = 1 ;i<=tableSize;i++) {
System.out.format("%4d |",i);
for(int j=1;j<=tableSize;j++) {
System.out.format("%4d",i*j);
}
System.out.println();
}
}
}
Do this to have the user input a letter
Info:
System.exit(0) exits the program with no error code.
nextLine() waits for user to enter string and press enter.
nextInt() waits for user to enter int and press enter.
Hope this helps!
Scanner input = new Scanner(System.in);
String i = input.nextLine();
if(i.equalsIgnoreCase("q")) {
System.exit(0);
}else {
System.out.println("Enter a postive integer: ");
int i = input.nextInt();
//continue with your code here
}
This looks like homework ;-)
One way to solve this problem is to put your code that prints your messages and accepts your input inside a while loop, maybe something like:
Scanner input = new Scanner(System.in);
byte nextByte = 0x00;
while(nextByte != 'q')
{
System.out.println("Enter a postive integer: ");
int tableSize = input.nextInt();
printMultiplicationTable(tableSize);
System.out.println("Enter q to quit, or any other key to continue... ");
nextByte = input.nextByte();
}
use a do-while loop in your main method as below
do {
System.out.println("Enter a postive integer: ");
String tableSize = input.next();
if (!"q".equals(tableSize) )
printMultiplicationTable(Integer.parseInt(tableSize));
}while (!"q".equals(input.next()));
input.close();
you would also want to have a try-catch block to handle numberFormatException

Not sure what loop to use in this case

I'm trying to make a simple program that asks for the user's age and displays an error when the user inputs a non-integer value.
Here's what I did so far:
import java.util.Scanner;
public class apples {
public static void main(String args[]) {
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name to begin.");
System.out.println("Hello " + nameinput.nextLine() + "!");
Scanner ageinput = new Scanner(System.in);
System.out.println("Please enter your age");
if(!ageinput.hasNextInt()){
System.out.println("Please enter an integer");
}
System.out.println("You've entered a valid age");
nameinput.close();
ageinput.close();
}
}
Here's what I want:
Every time the user inputs a non integer, I want the Please enter an integer error to appear. The user should then be able to input their age again, which will again be checked if it's an integer and so on. This will continue until the user inputs an integer and only then will the message You've entered a valid age be shown. I'm sure about neither which loop to use in this case (for, while, do while) nor how to implement it in the code.
String stringAge;
do {
System.out.println("Please Enter an int");
stringAge = ageinput.next();
} while (!stringAge.matches("^-?\\d+$")); //regex matches for - sign, and then a number
System.out.println("You entered an int");
int age = Integer.parseInt(stringAge);
As you know in Java they're 3 types of loops:
The while and do-while Statements
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once
while is simply a pre-test loop, that is the condition first will be checked before moving on to the body of the loop:
while(condition) # First check, if true or false
{
# Body
}
do-while loop however, checks the condition after executing of the body of the loop at least once, it's a post-test loop:
do{
# Body executed at least once
}while(condition);
The for Statement
The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied
Notice that in your code, asking the user for the age, the proper choice would be do-while, because you need to execute your program at least once to prompt the message and then you have to check the condition, if that's what you intended to do then this will suffice for your purpose. Though, you still can use while.
This is your code edited:
import java.util.Scanner;
public class apples {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name to begin.");
System.out.println("Hello " + input.nextLine() + "!");
System.out.println("Please enter your age");
do{
if(input.hasNextInt()){
System.out.println("You've entered a valid age");
break;
}
else{
System.out.println("Please enter an integer");
input.next();
}
}while(true);
}
}
Since the condition for the loop is the Boolean true it really doesn't matter here if you use while instead of do-while unless if you want to change the condition, that's up to you. For now, this code is very much close to the original code you posted and from my perspective it works, but it may not be the best code out there, there could be other approaches simpler or more complex to the same problem domain.
First of all, there's no need to have multiple Scanner objects wrapping the System.in input stream. (How to use multiple Scanner objects on System.in?)
As for the actual code, here's what came to mind:
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter your name to begin:");
String name = scanner.nextLine();
System.out.println("Hello " + name + "!");
System.out.println("Please enter your age:");
int age;
while (true) {
try { // Try to read in the age.
age = scanner.nextInt();
} catch (InputMismatchException ex) { // The input wasn't a valid integer; parsing the value failed.
System.out.println("Please enter an integer:");
continue; // Attempt reading the age again.
}
break; // The input was a valid integer. Break out of the loop.
}
scanner.close();
System.out.println("You've entered a valid age");
}
}
Hope this is what you wanted. i would suggest that using while is the way to go (my preference)
Using while::
public static void main(String args[]) {
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name to begin.");
System.out.println("Hello " + nameinput.nextLine() + "!");
Scanner ageinput = new Scanner(System.in);
System.out.println("Please enter your age");
while (!ageinput.hasNextInt()) {
System.out.println("Please enter an integer");
ageinput.next();
}
System.out.println("You've entered a valid age");
nameinput.close();
ageinput.close();
}
Using for::
public static void main(String args[]) {
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name to begin.");
System.out.println("Hello " + nameinput.nextLine() + "!");
Scanner ageinput = new Scanner(System.in);
System.out.println("Please enter your age");
for (; !ageinput.hasNextInt();) {
System.out.println("Please enter an integer");
ageinput.next();
}
System.out.println("You've entered a valid age");
nameinput.close();
ageinput.close();
}
Using do while
public static void main(String args[]) {
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name to begin.");
System.out.println("Hello " + nameinput.nextLine() + "!");
Scanner ageinput = new Scanner(System.in);
int i = 0;
do {
if (i == 0) {
System.out.println("Please enter your age");
i++;
} else {
System.out.println("Please enter an integer");
ageinput.next();
}
} while (!ageinput.hasNextInt());
System.out.println("You've entered a valid age");
nameinput.close();
ageinput.close();
}

Java won't respond to my input

I'm budding into java and I've been trying to write this basic program where it asks you a yes or no question, you give it an answer and then it does something based off that answer. currently my code is this.
import java.util.Scanner;
public class Main {
public static void main(String args[])
{
Scanner inputvar = new Scanner (System.in);
String yes, no;
System.out.println("Enter yes or no");
yes = inputvar.nextLine();
no = inputvar.nextLine();
if (inputvar.equals(yes))
{
System.out.println("You said yes!");
}
else if (inputvar.equals(no)){
System.out.println("You said no");
}
}
}
I don't get any errors when compiling but when I run the program It doesn't reply when I put anything in. It allows me to enter two lines of text then it terminates.
Your code yes, no variables are not correct, you invoke nextLine() twice in your code, that's why you are asked to enter inputs twice.
yes = inputvar.nextLine();
no = inputvar.nextLine();
inputvar is a Scanner instance, not a String object, you cannot try
inputvar.equals(yes)
You should only define:
String myInput = inputvar.nextLine();
and checks
if (myInput.equals("yes")){
//do some stuff
}else if(myInput.equals("no")){
//do other stuff
}
Scanner inputvar = new Scanner (System.in);
String yes, no;
System.out.println("Enter yes or no");
yes = inputvar.nextLine(); // You enter the first line
no = inputvar.nextLine(); // You enter the second line
if (inputvar.equals(yes)) // You try to compare an instance of
// Scanner with the firstline (not equal)
{
System.out.println("You said yes!");
}
else if (inputvar.equals(no)){ // You try to compare an instance of
// Scanner with the firstline (not equal)
System.out.println("You said no");
}
// You terminate the program
You should do something like:
String yes = "yes";
String no = "no";
String input = inputvar.nextLine();
if(yes.equals(input)) { [...]
You should change your code to this
Scanner inputvar = new Scanner (System.in);
String input;
System.out.println("Enter yes or no");
input = inputvar.nextLine();
if (input.equals(yes))
{
System.out.println("You said yes!");
}
else if (input.equals(no)){
System.out.println("You said no");
}
Hope this helps and best of luck.

How to Use the Scanner class and its next() method in Java?

hi I have this Java code,
import java.io.*;
import java.util.*;
public class SongWriter
{
public static void main(String[] args)
{
PrintWriter outputStream = null; // Scope must be outside the try/catch structure
try
{
outputStream = new PrintWriter("Song.txt"); // new
FileOutputStream("Song.txt")
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file Song.txt.");
System.exit(0);
}
System.out.println("\n classical songs has many lines");
System.out.println("\nNow enter the three lines of your Song.");
String line = null;
Scanner keyboard = new Scanner(System.in);
int count;
for (count = 1; count <= 3; count++)
{
System.out.println("\nEnter line " + count + ": ");
line = keyboard.nextLine();
outputStream.println(count + "\t" + line);
}
outputStream.close();
System.out.println("\nYour Song has been written to the file Song.txt.\n");
} // end of main
} // end of class
how do I Adjust the program so it first asks for a name of the file to write to. Use the Scanner class and its next() method. Read in the file name as a string variable after informing the reader the file name should end in the suffix .txt
Eg:- Song with the file names Haiku1.txt, Haiku2.txt and Haiku3.txt.
You almost had it.
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter first file name:");
String first = keyboard.nextLine();
System.out.println("Enter second file name:");
String second = keyboard.nextLine();
System.out.println("Enter third file name:");
String third = keyboard.nextLine();
//and so on and continue whatever you want to do..
EDIT: After your comment.
First store the 3 lines in a StringBuilder and then ask for the file name to write. Now you have the lyrics and file name.
Using the Scanner class to get input from the user:
String fileName1;
Scanner keyboard = new Scanner(System.in); //creates Scanner object
System.out.print ("Enter the name of the file. The file should end in the suffix .txt") //prompt the user to enter the file name
fileName1 = keyboard.next(); //store the name of the file
You should do this before the try/catch block so that you can use the filename that the user entered instead hardcoding it (like you did here with song.txt).
You can prompt the user this way for as many file names as you need.

Categories