creating a loop in java? [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have been struggling to figure out how to make my code loop when asking for user input.
Basically, I want the program to re-ask the question if the user enters no text at all.
This is what I done so far.
import javax.swing.JOptionPane;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Assessment {
public static void main(String[] args) throws IOException {
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
String me = JOptionPane.showInputDialog("Please enter your name");
System.out.println("Your name is: " + me);
String user1 = JOptionPane.showInputDialog("Please choose a number");
System.out.println("Your number is: " + user1);
String user2 = JOptionPane.showInputDialog("Please enter your choice of security, choice1(low) or choice2(high)");
String response = (String)System.in.toString();
if(user2.equals("choice1"))
JOptionPane.showMessageDialog(null,"your username is: "+me+user1,"Your username",JOptionPane.WARNING_MESSAGE);
}
}

while (!me.equals("")) {
}
to compare Strings in Java you have to use equals() and since you don't want it to be equal to empty text you should use the negation in Java.
Hope it helps.

This is all you need to do -
String me = "";
do
{
me = JOptionPane.showInputDialog("Please enter your name");
}while(me.equals(""));
Do it for your other windows too.
Or, just copy paste this code :(
import javax.swing.JOptionPane;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Assessment {
public static void main(String[] args) throws IOException {
BufferedReader userInput = new BufferedReader(new InputStreamReader(
System.in));
String me = "";
String user1 = "";
String user2 = "";
do {
me = JOptionPane.showInputDialog("Please enter your name");
} while (me.equals(""));
System.out.println("Your name is: " + me);
do {
user1 = JOptionPane.showInputDialog("Please choose a number");
} while (user1.equals(""));
System.out.println("Your number is: " + user1);
do {
user2 = JOptionPane
.showInputDialog("Please enter your choice of security, choice1(low) or choice2(high)");
} while (user2.equals(""));
String response = (String) System.in.toString();
if (user2.equals("choice1"))
JOptionPane.showMessageDialog(null, "your username is: " + me
+ user1, "Your username", JOptionPane.WARNING_MESSAGE);
}
}

You could use a while loop that refers to what they entered:
like while input = ""{question} or even a do while loop.
See this question:
Goto statements in Java
This may also help:
http://www.tutorialspoint.com/java/java_loop_control.htm

use java.util.Scanner.
Scanner input = new Scanner(System.in);
After prompting for the name, use the following:
String name = input_next();
if (name != null && !("").equals(name)) { //then move next - else go back to the prompt

You can find a great tutorial on this here, specifically the "while" and "do-while" statements.
In short :
while (condition) {
// statements
}
and
do {
// statements
} while (condition);
As long as the condition evaluates to true, the statements will keep getting executed. The difference between while and do-while is the time at which the conditions are evaluated, refer to the tutorial for more information.

Related

Could I get some help understating what is causing my "NoSuchElementException"?

I am currently going through the Helsinki MOOC for Java OOP and I have hit a snag on one of the questions. I am working on Week 7 Exercise 8 and when I run my code manually I am getting everything to work out okay. However when I run their automated tests I am getting the "NoSuchElementException" error.
It is my understanding from the JavaDoc on this particular error that it is most likely caused by .nextLine() not finding a line to read. What confuses me though is based on the error message, and the location of the exceptions, my use of .nextLine() is working in some places and not others while I am using it in the same manner. I included my class that I am using below. Thanks for the help everyone, and if I overlooked a previous post similar to this I apologize.
import java.util.Scanner;
import java.util.ArrayList;
public class AirportPanel {
private Scanner reader;
private ArrayList<Airplane> airplanes;
private ArrayList<Flight> flights;
public AirportPanel(Scanner reader){
this.reader = reader;
this.airplanes = new ArrayList<Airplane>();
this.flights = new ArrayList<Flight>();
}
public void start(){
System.out.println("Airport panel");
System.out.println("--------------------\n");
while(true){
printMenu();
String input = readString();
if(input.toLowerCase().equals("x")){
break;
}else{
chooseOperation(input);
}
}
}
private void printMenu(){
System.out.println("Choose operation:");
System.out.println("[1] Add airplane" + "\n[2] Add flight" + "\n[x] Exit");
System.out.print("> ");
}
private void chooseOperation(String input){
if(input.equals("1")){
addPlane();
}else{
addFlight();
}
}
private void addPlane(){
System.out.print("Give plane ID: ");
String planeID = readString();
System.out.print("Give plane capacity: ");
String planeCap = readString();
this.airplanes.add(new Airplane(planeID, planeCap));
}
private void addFlight(){
System.out.print("Give plane ID: ");
String planeID = readString();
System.out.print("Give departure airport code: ");
String airport1 = readString();
System.out.print("Give destination airport code: ");
String airport2 = readString();
String airports = airport1 + "-" + airport2;
for(Airplane ap : this.airplanes){
if(ap.getID().equals(planeID)){
this.flights.add(new Flight(ap, airports));
}
}
}
private String readString(){
return this.reader.nextLine();
}
EDIT: Here is a screenshot of the stack trace. I also made a github repo with all of my files in the event that would help more. I am pretty new to coding so excuse the mess I surely made of these files.
EDIT 2: I went to my readString() method and changed my call of .nextLine() to .next() and it fixed my issue. I'm not entirely sure how or why but it is now submitting correctly.

Is there a way to implement some gui (message box that asks for multiple inputs ie. registration document) into a code ive written

I just want a simple popup message box that asks for multiple inputs and such.
System.out.println("Please enter Name");
Name = name.nextLine();
System.out.println("Please enter Age");
age=ages.nextInt();
System.out.println("Please enter Gender");
Gender =gender.nextLine();
System.out.println("Please enter Contact Number");
ConNum =number.nextLine();-->
Is there a way to make a gui for this? (its a foundation level project)
Use JOptionPane to take your input:
String name = JOptionPane.showInputDialog(null, "Please enter Name");
Edit:
You could ask the user all the questions on the one box (for this example, ensure they separate the answers by a space).
String input = JOptionPane.showInputDialog(null, "Please enter name.\nPlease enter age.\nPlease enter gender.");
String[] allInput = input.split("\\s+");
System.out.println("Name: " + allInput[0] + " Age: " + allInput[1] + " Gender: " + allInput[2]);
Note: obviously there will be issues, such as not using a space, or using a full name (Jack Sparrow) etc; but it gives you a general idea.
As #notyou mentioned you can use JOptionPane it's very simple to implement it into you code check this example :
import java.io.*;
import javax.swing.*;
public class SystemOutDialog {
public static void main(String[] args) {
// set up a custom print stream
CustomPrintStream printStream = new CustomPrintStream();
System.setOut(printStream);
// from now on, the System.out.println() will shows a dialog message
System.out.println("hello!");
System.out.println("how are you?");
}
}
class CustomPrintStream extends PrintStream {
public CustomPrintStream() {
super(new ByteArrayOutputStream());
}
public void println(String msg) {
JOptionPane.showMessageDialog(null, msg);
}
}
Source link

How do I return the number of items found after I do a search?

Please help me to figure out how I can get a count of the result when I do a search against a specific folder?
Also how can I ask the user if they want to perform another search?
// Importing utilities
import java.io.File;
import java.util.*;
public class FileListing
{
public static void main (String[] args)
{
// Creating a Scanner
Scanner keyboard = new Scanner(System.in);
// Specifying search location
File file = new File("D:/Music");
String[] content = file.list();
// Searching for a match
System.out.println("Enter the first few characters of the folder/file to do a lookup");
String userInput = keyboard.nextLine();
// Adding text to say what the user searched for
System.out.println("Below you will find the list of folders/files with a partial match to (" + userInput + ").");
System.out.println();
// Posting the contents
for(String folders : content)
{
if(folders.toUpperCase().startsWith(userInput.toUpperCase()))
{
System.out.println("Name: " + folders);
}
}
}
}
If you want to count your matches you can do the following
int i=0;
// Posting the contents
for(String folders : content)
{
if(folders.toUpperCase().startsWith(userInput.toUpperCase()))
{
System.out.println("Name: " + folders);
i++;
}
}
System.out.println("Total number of results: " + i);`
As for asking the user, consider using a do-while loop in the following format
do{
// your code
// ask user and read his answer on a string called userChoice
}while (userChoice.equals('y'))
Experiment with our suggestions and you will find the answer easily enough!
I would add a variable
int count = 0;
right before the for loop, and just increment it if it's a match.
This should get you started. I am incrementing the variable count each time a match is found. I am also looping forever so it keeps asking the user for more input.
// Importing utilities
import java.io.File;
import java.util.*;
public class FileListing
{
public static void main (String[] args)
{
// Creating a Scanner
Scanner keyboard = new Scanner(System.in);
// Specifying search location
File file = new File("D:/Music");
String[] content = file.list();
while(true){
// Searching for a match
System.out.println("Enter the first few characters of the folder/file to do a lookup");
String userInput = keyboard.nextLine();
// Adding text to say what the user searched for
System.out.println("Below you will find the list of folders/files with a partial match to (" + userInput + ").");
System.out.println();
// Posting the contents
int count=0;
for(String folders : content)
{
if(folders.toUpperCase().startsWith(userInput.toUpperCase()))
{
System.out.println("Name: " + folders);
count++;
}
}
}
}
}
Use a while loop and prompt the user to enter a phrase (such as 'exit') if they want to stop. After reading the user input, check the phrase and call a break if it matches the exit phrase.
Use a variable as Robert suggested to count the total number of files found.

Java How to search a word from text file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
edit: Write a program to read in 100 words from a file. Then, have the user search for a word until they enter 'quit'.
The program will read in up to 100 words from a file. The file may or may not contain 100 words but the array should hold up to 100 (if the list does not contain enough words, fill the rest of the array with empty strings).
After the file is read in, the program will prompt the user for a search string. The program will then search for the string and tell the user if the word was found or not. The program will continue to get search strings from the user until the user enters 'quit'
Hello I need help write a program to find a word from text file
the result should look like:
Enter a word to search for: taco
Word 'taco' was found.
Enter a word to search for: asd
Word 'asd' was NOT found.
and when user enter the word "quit" the program will quit
below is what I have so far and need help to complete
import java.io.*;
import java.util.Scanner;
public class project2 {
public static void main( String[] args ) throws IOException {
String[] list;
String search;
list = load_list( "words.txt" );
search = prompt_user( "\nEnter a word to search for: " );
while ( ! search.equals( "quit" ) ) {
System.out.println( "Word '" + search + "' was" +
( ( find_word( search, list ) ) ? "" : " NOT" ) +
" found." );
search = prompt_user( "\nEnter a word to search for: " );
}
System.out.println();
}
for(String s: list){
if(s.equals(search)){
//do whatever
}
}
Use this:
Scanner txtscan = new Scanner(new File("filename.txt"));
while(txtscan.hasNextLine()){
String str = txtscan.nextLine();
if(str.indexOf("word") != -1){
System.out.println("EXISTS");
}
}
The below code answers this question perfectly:
String word = ""; int val = 0;
while(!word.matches("quit"))
{
System.out.println("Enter the word to be searched for");
Scanner input = new Scanner(System.in);
word = input.next();
Scanner file = new Scanner(new File("newFile.txt"));
while(file.hasNextLine())
{
String line = file.nextLine();
if(line.indexOf(word) != -1)
{
System.out.println("Word EXISTS in the file");
val = 1;
break;
}
else
{
val = 0;
continue;
}
}
if(val == 0)
{
System.out.println("Word does not exist");
}
System.out.println("-------continue or quit--- enter continue or quit");
word = input.next();
}

How I can correctly use command "if" in Message Dialog? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I`m new in Java. I would like to ask how I can use if in Message Dialog?
If "age" under 15, add message to new line of Message Dialog-
"You`re so baby"
I wrote this codes but it was error.Please help.
import javax.swing.JOptionPane;
public class Isim {
public static void main(String[] args) {
// TODO Auto-generated method stub
String name, age, baby;
name = JOptionPane.showInputDialog(null, "Enter Your name");
age = JOptionPane.showInputDialog(null, "Enter Your Age");
int i = new Integer(age).intValue();
baby = "You`re so baby";
JOptionPane.showMessageDialog(null, "Your Name is: "+name+"\n"+"Your Age is: "+age+"\n"+if (i < 15){baby});
}
}
Use Conditional operator:
JOptionPane.showMessageDialog(null, "Your Name is: "+name+"\n"+"Your Age is: "+age+"\n" +
(i < 15 ? baby : ""));
You can also use String.format method to avoid those concatenation:
JOptionPane.showMessageDialog(null, String.format("Your Name is: %s\n. Your Age is: %d\n. %s", name, age, (i < 15? baby: ""));
For yours and other edification this is the way the problem should be solved:
public static final String babyMessage = " You`re so baby";
public static final int notABabyAge = 15;
public static String generateMessage(String name, int age) {
StringBuilder sb = new StringBuilder("Your name is: ");
sb.append(name);
sb.append(". Your age is: ");
sb.append(age);
sb.append(".");
if(age < notABabyAge) sb.append(babyMessage);
return sb.toString();
}
public static void main(String args[]) {
String name, age, message;
name = JOptionPane.showInputDialog(null, "Enter Your name");
age = JOptionPane.showInputDialog(null, "Enter Your Age");
//Possible NumberFormatException here, enter aaa in the dialog, and boom.
int i = new Integer(age).intValue();
message = generateMessage(name,age);
JOptionPane.showMessageDialog(message);
}
This kind of problems crops its head often. Typically when interacting with a database in an application. Often times we end up constructing an SQL statement using a combination of variables and hard coded strings.
For the hard coded strings, they are typically best to be static and final. For variables such as notABabyAge, those kinds are thing should be coded so they can change with a configuration that occurs outside of the application.
Catching the NumberFormatException is important as people will always try to break your code.
You can also do something like this, for more readable code:
String age = JOptionPane.showInputDialog(null, "Enter your age");
int ageInt = new Integer(age).getValue();
String babe = "";
if(ageInt < 14){
babe = "You're so baby";
}
JOptionPane.showMessageDialog(null,"Your Name is: "+name+"\n"+"Your Age is: "+age+"\n"+baby);
Use "Your Name is: "+ name + "\n" + "Your Age is: " + age + "\n" + (i < 15 ? "baby" : "")
See this link for details.
Try this:
JOptionPane.showMessageDialog(null, "Your Name is: "+name+"\n"+"Your Age is: "+age+"\n"+ (i < 15) ? baby : String.Empty);
It evaluates the condition, in this case i < 15, if it evaluates to true then it returns what comes after the ?, in this case baby, otherwise what comes after the :, an empty string (String.Empty).

Categories