I asked a question earlier and since then i've edited my code a bit but now my code won't stop when i reads in done it does not stop.
public class Done {
public static void main(String[] args){
Scanner kb = new Scanner(System.in);
ArrayList<String> sal = new ArrayList<String>();
int count = 0;
while (true){
sal.add(kb.next());
if (sal.equals("done"))
break;
count++;
}
display(sal);
displayb(sal);
}
public static void display(ArrayList<String> sal){
for (int i=0; i<sal.size(); i++)
System.out.print(sal.get(i)+ " ");
System.out.println();
}
public static void displayb(ArrayList<String> sal){
for (int z = sal.size(); z >= 1; z--)
System.out.print(sal.get(z-1) + " ");
System.out.println();
}
}
My code won't stop when I enter the phrase "done." Anyone know what I might be doing wrong?
You're checking if the ArrayList sal is equal to the string "done" -- this will never be true. Perhaps you want to check if the latest input is equal to that string:
while (true)
{
String input = kb.next();
if (input.equals("done"))
break;
sal.add(input);
count++;
}
kb.next() is the string you want to compare. You'll need to save that in a variable:
String inputString = kb.next();
if (inputString.equals("done"))
break;
sal.add(inputString);
That will also solve the problem of not adding "done" to the array.
Related
So I am completely new to java, and I want to create a code to accept string inputs from a user, and store it into an array. After this in the next statement, I will type a value into the terminal, and I want the code to compare my string input to one of the strings in the array and print available on the terminal when the string is available and vice versa. The first part of my code was right (hopefully) but I had a problem in comparing the strings. I feel it doesn't check the strings with my input in the code. Here is my code, Could anyone please help me with this? Thank you so much.
import java.util.Scanner;
class Course {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a[] = new String[20] //assuming max 20 strings
System.out.println("Enter no. of courses");
int no_of_courses = sc.nextInt(); // number of strings
if (no_of_courses <= 0)
System.out.println("Invalid Range");
else {
System.out.println("Enter course names:");
for (int i = 0; i < no_of_courses; i++) {
a[i] = sc.next(); //accepting string inputs
}
System.out.println("Enter the course to be searched:");
String search = sc.next() //entering a string to search
for (int i = 0; i < no_of_courses; i++) {
if (a[i].equals(search)) //I feel the problem is here
System.out.println(search + "course is available");
break;
else
System.out.println(search + "course is not available");
}
}
}
}
I expect the output to be
<string> course is available
when my string matches a string in the array and
<string> course is not available
when my entered string doesn't match a string in the array
But there is no output :(
I have modified your code and commented on line where it need to be explained. check it carefully.
import java.util.Scanner;
class Course {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter no. of courses");
int no_of_courses = sc.nextInt(); // number of strings
String a[] = new String[no_of_courses]; // do not assume when you have proper data.
if (no_of_courses <= 0)
System.out.println("Invalid Range");
else {
System.out.println("Enter course names:");
for (int i = 0; i < no_of_courses; i++) {
a[i] = sc.next(); // accepting string inputs
}
System.out.println("Enter the course to be searched:");
String search = sc.next(); // entering a string to search
boolean flag = false;
for (int i = 0; i < no_of_courses; i++) {
if (a[i].equals(search)) // I feel the problem is here
{
flag = true;//do not print here. just decide whether course is available or not
break;
}
}
//at the end of for loop check your flag and print accordingly.
if(flag) {
System.out.println(search + "course is available");
}else {
System.out.println(search + "course is not available");
}
}
}
}
class Course {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String a[] = new String[20] ; //assuming max 20 strings
System.out.println("Enter no. of courses");
int no_of_courses = sc.nextInt(); // number of strings
if(no_of_courses <= 0)
System.out.println("Invalid Range");
else
{
System.out.println("Enter course names:");
for(int i=0 ; i < no_of_courses ; i++)
{
a[i] = sc.next(); //accepting string inputs
}
System.out.println("Enter the course to be searched:");
String search = sc.next() ; //entering a string to search
boolean found = false;
for(int i = 0 ; i < no_of_courses ; i++)
{
if(a[i].equalsIgnoreCase(search)) //I feel the problem is here
{
**found = true;**
break;
}
}
if(found) {
System.out.println(search+ "course is available");
}else {
System.out.println(search+ "course is not available");
}
}
}
}
This is really a good effort and you almost got it. So just a couple of things
Since you are inputting the number of courses, just use that value to initialise your array (it's just a good practice to get into to try not initialise things before you actually need them).
If you are doing String comparisons and case sensitivity does not matter, rather use .equalsIgnoreCase(String)
To solve your problem, you just needed a boolean variable to indicate whether or not you had found a match. Initially this would be FALSE (no match found) and you would run through your array until a match is found. Once found this would be flagged TRUE and you'd breakout your loop (which you correctly did).
Only once out your loop, you'd print out whether you found a match.
Have a look:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter no. of courses");
int no_of_courses = sc.nextInt(); // number of strings
if (no_of_courses <= 0) {
System.out.println("Invalid Range");
} else {
String a[] = new String[no_of_courses];
System.out.println("Enter course names:");
for (int i = 0; i < a.length; i++) {
a[i] = sc.next(); //accepting string inputs
}
System.out.println("Enter the course to be searched:");
String search = sc.next(); //entering a string to search
boolean courseFound = Boolean.FALSE;
for(int i = 0; i < a.length; i++) {
if (a[i].equalsIgnoreCase(search)) {
courseFound = Boolean.TRUE;
break;
}
}
if(courseFound) {
System.out.println(search + "course is available");
} else {
System.out.println(search + " course is not available");
}
}
}
Oh, just for interest (and when you start working with some more advanced constructs), you could always just use stream, which was introduced in Java 8. It'll trim down 12 lines to 5...
if(Arrays.stream(a).anyMatch(i -> i.equalsIgnoreCase(search))) {
System.out.println(search + " course is available");
} else {
System.out.println(search + " course is not available");
}
I noticed a few things - Does your program run to the end? When i copy/pasted into my ide i noticed a few missing semi-colons, and like Yhlas said, your last if/else statement syntax is incorrect.
And this doesn't have anything to do with whether or not your program will give you the right answer, but your last loop will print over and over again because it will check each element in a, and each time it loops and finds a mismatch it will print something out
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.
I am taking a course and I have the programs run in a loop so you can easily exit by entering "Quit". I am running into trouble working with arrays. This has the user type in sentences and then at the end shows the user what they typed. I want to have the program check each input the user types in and if it is "Quit", I want to exit the program. I am new to Java so looking for something that is within my understanding without using a break if possible.
I have attempted to use a boolean in my while loop to quit when it is set to false.
public static void main(String[] args)
{
String [] Responses = new String [10];
boolean ExitLoop = true;
do
{
Scanner Input = new Scanner(System.in);
int n = 0;
for (int i = 0; i < 10; i++)
{
System.out.println("Please enter sentence " + (i+1) + ": ");
Responses[n] = Input.nextLine();
if (Responses[n] == "Quit")
{
ExitLoop = false;
}
n++;
}
System.out.println();
for (int j = 0; j < 10; j++)
{
System.out.println("Sentence " + (j+1) + " " + Responses[j]);
}
}
while (ExitLoop);
}
To exit the application you can call the following line from anywhere.
System.exit(0);
Integrated into you code it would look like this.
for (int i = 0; i < 10; i++)
{
System.out.println("Please enter sentence " + (i+1) + ": ");
Responses[n] = Input.nextLine();
if (Responses[n].equals("Quit"))
{
System.exit(0); //add this to exit the application
}
n++;
}
If you wanted to keep separation of concerns you could make a method that exits the application.
public void ExitApplication()
{
//you can add pre-exit checks and other items here
System.exit(0);
}
Then you could simply call the method from inside you loop.
if (Responses[n].equals("Quit"))
{
ExitApplication();
}
The '==' operator only checks if the strings refer to the same memory location, which they do not. Try using the string.equals() method for comparing the actual string values.
if (Responses[n].equals("Quit")) {
ExitLoop = false;
}
You can use one variable for iteration, and you need to use equals for comparing string.
Try that:
public static void main(String[] args) {
final int countSentences = 10;
final String[] sentences = new String[countSentences];
final Scanner scanner = new Scanner(System.in);
for (int i = 0; i < countSentences; i++) {
System.out.println("Please enter sentence "+(i+1)+": ");
sentences[i] = scanner.nextLine();
if (sentences[i].equals("Quit")) System.exit(0);
}
System.out.println();
for (int j = 0; j < countSentences; j++)
System.out.println("Sentence "+(j+1)+" "+sentences[j]);
}
Disclaimer, I've been at java for about a month. I'm completely lost on this. I'm trying to have a user input a phrase and if any strings in that phrase is found on the array, it returns the corresponding string in one line. if the string isn't found, it would just skip it.
so if someone typed in "dog eat my fish"
and the array holds:
dog perro
eat munched
fish yellow trout
it would return:
perro munched yellow trout
I haven't written the code to print out what I've got yet, but I know this code isn't working.
any help would be greatly appreciated.
import java.io.*;
import java.util.*;
public class ArrayTest2 {
public static void main(String[] args)
throws java.io.IOException {
Scanner input = new Scanner(System.in);
String userString = " ";
userString = englishString();
String[][] wordList = new String[10][2];
loadEnglishString(wordList);
}
public static String englishString() {
Scanner input = new Scanner(System.in);
String s1 = " ";
System.out.println("Please enter a phrase to translate: ");
s1 = input.nextLine().trim().toUpperCase();
return s1;
}
public static void loadEnglishString(String[][] wordList)
throws java.io.IOException {
String filName = " ";
filName = ("/home/chrism/ArrayTest2.txt");
Scanner input = new Scanner(new File(filName));
while(input.hasNextLine()) {
String line = input.nextLine();
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens()) {
boolean stop = false;
for(int i = 0; i < wordList.length; i++) {
if(stop)
break;
for(int j = 0; j < wordList[i].length; j++)
if(input.hasNextLine())
wordList[i][j] = input.nextLine();
else {
stop = true;
}
break;
}
}
}
input.close();
}
}
You'll definitely want to change your for loop. Brackets are your friend.
for(int i = 0; i < wordList.length; i++) {
if(stop)
break;
for(int j = 0; j < wordList[i].length; j++) {
if(input.hasNextLine())
wordList[i][j] = input.nextLine();
else {
stop = true;
}
}
}
The way you had it, both increments were registering as dead code because your second break would always called the first time through the loop, and your else was registering as coupled with the first if(stop).
Edit: don't know for sure about how the else would couple, but the break is definitely called after the first run through.
//package com.myjava.stokenizerr;
import java.util.StringTokenizer;
public class MyStringTokenizer {
public static void main(String a[]){
/* your code for user input string */
/* assume input as dog eat my fish */
String input = "dog eat my fish";
String msg = "dog perro eat munched fish yellow trout";
StringTokenizer st1 = new StringTokenizer(msg," ");
StringTokenizer st2 = new StringTokenizer(input," ");
while(st1.hasMoreTokens()){
System.out.println(st1.nextToken()); // Store this one(first) string array
}
while(st2.hasMoreTokens()) {
System.out.println(st2.nextToken()); // Store in another(second) array
}
/* Now Compare both the arrays */
/* If the strings are equal then remove string from second array */\
/* If equal just skip it */
}
}
See the above code st1.nextToken() and st2.Tokens() will give you the values
For comparing take two loops
for(i==0;i<array1length();i++) {
for(j==0;j<array2length();j++) {
// Your code for comparsion
}
}
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("");
}
}
}
}