I need to incorporate an IF statement to break the script when the user enters the letter Q.
I also need to display their input backwards to them - I am unsure on how I would do this, here is my code.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayListOfNames {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<String> list = new ArrayList<String>();
Scanner Scan = new Scanner (System.in);
String name;
System.out.println("Please enter some words (You may press Q to finish): ");
while (Scan.hasNext())
{
name = Scan.nextLine();
list.add(name);
}
Scan.close();
}
}
To check against Q:
while(Scan.hasNext())
{
name = Scan.nextLine();
if(name.equals("Q") || name.equals("q"))
{
break;
}
list.add(name);
}
To show list in the reverse order:
for(int i = list.size() - 1; i >= 0; i--)
{
System.out.println(list[i]);
}
How about this.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayListOfNames {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<String> list = new ArrayList<String>();
Scanner Scan = new Scanner (System.in);
String name;
System.out.println("Please enter some words (You may press Q to finish): ");
while (Scan.hasNext())
{
name = Scan.nextLine();
if( name.equals("Q") ) {
break;
}
list.add(name);
}
Scan.close();
}
}
To display input backward put this code after loop that scans input.
for(int i = list.size()-1; i>=0; i--)
System.out.println(list.get(i));
while (Scan.hasNext())
{
name = Scan.nextLine();
//Input is stored to name, so you need to compare input with Q
if("Q".equals(name)
{
//You need to exit the loop
break;
}
list.add(name);
}
//You have what ever user entered in list. So use iterator (or) for-each to print them out again.
As I suspect this is homework, there are probably extra marks for using the Stack class.
Get the data in the loop and push it onto the Stack. Then when you need to print it pop results from the Stack.
From a Software Engineering standpoint, we try to stay away from using break; statements in loops. Instead, it's recommended to use a terminator
final String TERMINATOR = "Q";
boolean terminated = false;
while (scanner.hasNext() && !terminated)
{
String line = scanner.next();
if (!line.equals(TERMINATOR))
{
list.add(line);
}
else
{
terminated = true;
}
}
Also note how we do !line.equals(TERMINATOR) instead of line.equals(TERMINATOR) and do the normal list appending. This is because list appending is the nominal case and as such we want to do the least amount of checks and jumping to get to it.
As for printing out your list in reverse, you can do a simple backwards iterative for-loop
for (int i = list.size()-1; i >= 0; i--)
{
System.out.print(list.get(i) + " ");
}
Related
Write a simple program that uses a break statement to end the while loop where the condition in while loop is always true. Test the user input and if it is zero then use a break to exit or come out of the loop.
Do I need to add any value to execute the code?
import java.util.Scanner;
class WhileLoopWithBreak {
public static void main(String[] args) {
int n;
Scanner input = new Scanner(System.in);
while () {
continue;
} else {
break;
}
}
}
Check this:
int n;
Scanner input = new Scanner(System.in);
while (true) {
# Using string as user can enter anything.
String text = input.nextLine();
# Trimming the input to remove white-space characters.
if (text.trim().equals("0")){
break;
}
}
I'm a beginner in Java and I have to write a program that allows the user to enter in words, then the program returns the word backwards until the user writes "stop". Every time the user enters a word, java outputs it backwards plus the previous word which is outputted and I don't want that.
For example, if I put input pots
it outputs, stop
if I print cat
it outputs potstac
How can I just get java to just output the words backwards without adding it on to the prior words
For example, i want to input in pots
it should output, stop
i want to print cat
it should output, tac
import java.util.*;
public class javapdf2413 {
public static void main (String [] args) {
Scanner in = new Scanner (System.in);
String wordEntered = "";
String backWords = "";
do {
System.out.println("Enter in a word");
wordEntered = in.next();
for (int i = wordEntered.length()-1; i>=0; i--) {
backWords = backWords + wordEntered.charAt(i);
}
System.out.println(backWords);
}while(!wordEntered.equals("stop"));
}
}
You'll need to set backWords back to an empty string at the beginning of the do loop. If you don't it will just concatenate onto the end of the previous string - which is what you said is happening. Setting it back to "" at the beginning of the loop body will essentially "reset" it for the next word.
Like this:
do {
backWords = "";
System.out.println("Enter in a word");
wordEntered = in.next();
for (int i = wordEntered.length()-1; i>=0; i--) {
backWords = backWords + wordEntered.charAt(i);
}
System.out.println(backWords);
}while(!wordEntered.equals("stop"));
Try to do this with while loop
import java.util.Scanner;
public class TestRun {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String wordEntered = "";
String backWords = "";
while (true) {
System.out.println("Enter in a word");
wordEntered = in.next();
if (wordEntered.equals("stop")) {
break;
} else {
for (int i = wordEntered.length() - 1; i >= 0; i--) {
backWords = backWords + wordEntered.charAt(i);
}
System.out.println(backWords);
backWords = "" ;
}
}
}
}
Just initialize your variables inside your do loop
String wordEntered;
String backWords;
do {
wordEntered = "";
backWords = "";
System.out.println("Enter in a word");
wordEntered = in.next();
for (int i = wordEntered.length()-1; i>=0; i--) {
backWords = backWords + wordEntered.charAt(i);
}
System.out.println(backWords);
}while(!wordEntered.equals("stop"));
Just beware - Strings are immutable objects. Use it with right use case and approach. Try to use StringBuilder for non concurrent code as much as possible where ever you can.
So I am a beginner to java (not to programming), and I encoutered a problem where it wont let me create an arrayList:
import java.io.*;
import java.util.ArrayList;
import java.util.*;
public class OrderingNumbers{
public static void main (String[] args)throws IOException{
boolean keepRunning = true;
List<String> numbers = new ArrayList<String>(); //<--this one does not work
ArrayList sortedNumbers = new ArrayList();//<-- This one works
while(keepRunning){
DataInputStream input = new DataInputStream(System.in);
System.out.print("Do you want to sort the numbers or add a number?");
String answer = input.readLine();
if(answer.equals("sort")){
for(int i = 0; i < numbers.size(); i++){
System.out.println(numbers.get(i));
}
System.out.println("Bye Bye.");
keepRunning = false;
}else if(answer.equals("add")){
System.out.print("What number to you want to add?");
numbers.add(input.readLine());
System.out.println("Added number.");
}else{
System.out.print("That is not an option.");
}
}
}
}
I have tried doing this as well, ArrayList<String> strArrayList = new ArrayList<String>(); but still does not work. I am trying to allow the user to add another number to the array if they want.
import java.io.*;
import java.util.*;
public class OrderingNumbers{
public static void main (String[] args)throws IOException{
boolean keepRunning = true;
// here is the corrected line
List numbers = new ArrayList();
ArrayList sortedNumbers = new ArrayList();//<-- This one works
// add data to sort
numbers.add(0, 1); // adds 1 at 0 index
numbers.add(1, 2); // adds 2 at 1 index
System.out.println(numbers);
while(keepRunning){
Scanner input = new Scanner(System.in);
System.out.print("Do you want to sort the numbers or add a number?");
String answer = input.nextLine();
if(answer.equalsIgnoreCase("sort")){
for(int i = 0; i < numbers.size(); i++){
System.out.println(numbers.get(i));
// note does not actually do any sorting
}
System.out.println("Bye Bye.");
keepRunning = false;
}else if(answer.equalsIgnoreCase("add")){
System.out.print("What number to you want to add?");
numbers.add(input.nextLine());
System.out.println("Added number.");
}else{
System.out.print("That is not an option.");
}
}
}
}
The normal usage is as follows:
import java.util.List;
List<String> numbers = new ArrayList<>();
List<String> sortedNumbers = new ArrayList<>();
So typically:
Most general type (List) for variables so implementation may be changed later, and all kind of Lists will fit.
Always typed List<...>.
Using the diamond <> operator.
The error might have been an import java.awt.List; which is an other class with the same name. Probably not here.
To sort (integer) numbers a List<Integer> would seem more logic, as 9 < 10, but "9" greater than "10" alphabetically.
For reading text better use Scanner as mentioned in an other answer. It has:
if (scanner.hasNextInt()) {
int number = scanner.nextInt();
numbers.add(number); // adds an Integer with number's value.
...
The real error is unclear however.
In the program given I have to make sure that if two consequtive characters are the same. I shouldn't increase the value of the variable (Count)... I have tried "break;", but that skips me out of the "for loop" which is very counter-productive. How can I skip the given part and still continue the "for loop"?
Currently my output for "Hello//world" is 3. It should be 2 (the '/' indicates a ' '(Space)).
Code
import java.util.Scanner;
class CountWordsWithEmergency
{
public static void main()
{
Scanner input = new Scanner(System.in);
System.out.println("Please input the String");
String inp = input.nextLine();
System.out.println("thank you");
int i = inp.length();
int count = 1;
for(int j=0;j<=i-1;j++) //This is the for loop I would like to stay in.
{
char check = inp.charAt(j);
if(check==' ')
{
if((inp.charAt(j+1))==check) //This is the condition to prevent increase for
//count variable.
{
count = count; //This does not work and neither does break;
}
count++;
}
}
System.out.println("The number of words are : "+count);
}
}
You can use the keyword continue in order to accomplish what you are trying to do.
However you can also inverse your conditional test and use count++ only if it is different (!= instead of == in your if) and do nothing otherwise
if ((inp.charAt(j+1)) != check) {
count++;
}
The word you are looking for is "continue".
Try this:
if ((inp.charAt(j+1)) != check) {
count++;
}
Increment the value of count by checking with !=.
Try using continue where you want to skip an block.
Use "continue;" when you want to break the current iteration.
continue is a keyword in java programming used to skip the loop or block of code and reexecutes the loop with new condition.
continue statement is used only in while,do while and for loop.
You may want to use the continue keyword, or modify the logic a little bit:
import java.util.Scanner;
class CountWordsWithEmergency
{
public static void main()
{
Scanner input = new Scanner(System.in);
System.out.println("Please input the String");
String inp = input.nextLine();
System.out.println("thank you");
int i = inp.length();
int count = 1;
for(int j=0;j<=i-1;j++) //This is the for loop I would like to stay in.
{
char check = inp.charAt(j);
if(check==' ')
{
if((inp.charAt(j+1))!=check)
{
count++;
}
}
}
System.out.println("The number of words are : "+count);
}
}
Edit:
You may want to use the split method of the String class.
int wordsCount = str.split(' ').length;
Hope it helps :)
The following should work.
import java.util.Scanner;
class CountWordsWithEmergency
{
public static void main()
{
Scanner input = new Scanner(System.in);
System.out.println("Please input the String");
String inp = input.nextLine();
System.out.println("thank you");
int i = inp.length();
int count = 1;
for(int j=0;j<=i-1;j++) //This is the for loop I would like to stay in.
{
char check = inp.charAt(j);
if(check==' ')
{
if((inp.charAt(j+1))==check) //This is the condition to prevent increase for
//count variable.
{
continue;
}
count++;
}
}
System.out.println("The number of words are : "+count);
}
}
thanks for all the help guys but now the nature of the question has changed using Patrick's suggestion below loop is running but it dise not seem to be storing the input to respective arrays data keeps hetting replaced into the ArrayLists rather than going to the next position into the ArrayList any suggestions?
import java.util.ArrayList;
import java.util.Scanner;
public class Arrray {
public static void main(String [] args){
ArrayList<String> names;
ArrayList<String> addr;
do {
names = new ArrayList<String>();
addr = new ArrayList<String>();
Scanner userInput = new Scanner(System.in);
System.out.println("Name and Adreess are: " + names.size() + "**"
+ addr.size());
System.out.println("please Enter Your Name :");
names.add(userInput.next());
System.out.println("please enter your Address :");
addr.add(userInput.next());
System.out.println("Do you want to add another entry? :(y/n)" );
String ans =userInput.next(); // get the value from the user using scanner class
if(ans.equals("n") || ans.equals("N"))
break;
} while (true);
int n = names.size();
int a = addr.size();
for(int i =0; i<n && i<a; i++ )
System.out.println("Name and address are as below: "+ names.get(i)+"**"+ addr.get(i));
}
}
Use a while(true) in conjunction with a break statement:
do {
if(input.next() == 'n'){
break;
}
} while(true);
get value from the user and if user enter n then break otherwise nothing
System.out.println("Do you want to add another entry? :(y/n)" );
String ans = .... // get the value from the user using scanner class
if(ans.equalsIgnoreCase("n"))
break;
Try to capture this user's input
System.out.println("Do you want to add another entry? :(y/n)");
and use that info in the while.
You have to do something like this:
String choice = "";
do {
.
.
.
.
System.out.println("Do you want to add another entry? :(y/n)" );
choice = userInput.next();
} while (!(choice.equals("n") || choice.equals("N")));
The line
choice = userInput.next();
will read user input, and the String classes equals method for comparing the input. The loop will continue until the choice is either N or n.
import java.util.ArrayList;
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
ArrayList<String> name = new ArrayList<String>();
ArrayList<Integer> phone = new ArrayList<Integer>();
Scanner scanner = new Scanner(System.in);
String answer = "";
do {
System.out.println("Please enter your name: ");
name.add(scanner.next());
System.out.println("Please enter your number: ");
phone.add(scanner.nextInt());
System.out.println("Do you want to add a directory y/n?");
answer = scanner.next();
} while (answer.equals("y") || answer.equals("Y"));
if (answer.equals("y") || answer.equals("Y")); //want it to go back to start another direcotry here
else {
System.out.println("Thanks for adding to the directory");
for (int i = 0; i < name.size(); i++) {
System.out.print(name.get(i) + "\t");
System.out.print(phone.get(i));
System.out.println("");
}
}
}
}