Continuously Get User Input Until Empty String Entered

Jul 26, 2014

I have the code below that just keeps getting the user's name and displaying it until the user enter's an empty string. Well, to simulate that, I just hit the keyboard instead of entering any name but for some reasons I am not seeing in my code, the programme just keeps looping.
 
System.out.println("Enter your name :
");
Scanner st = new Scanner(System.in);
while(st.hasNext()){
System.out.println("Enter your name :
");
String name = st.nextLine();
System.out.println(name);
if(name==" ") break;
}
System.out.println("you are out of the while loop now!!");

View Replies


ADVERTISEMENT

Reading Input With Scanner And Checking If User Entered Empty String?

Apr 7, 2015

The project is a program that allows the user to enter students and enter grades for each student. One of the requirements is that if there is already a grade stored for the student that it will display the previous grade. IF the user then enters a new grade the new grade will be stored. IF the user simply presses enter (enters an empty string) nothing is done. I have everything working except for the requirement of doing nothing if the user enters an empty string. If I just press enter at this point I get a NumberFormatException.

The below code is a method "setTestGrades" from the student class. This method iterates through each student object stored in an array list and then checks if there is a previous grade (Requirement# unset grades have to default to -1) before allowing the user to set a new grade.

public void setTestGrades(int testNumber) { //Sets the grade for the specified test number for each student in the arraylist.
testNumber -= 1;
Scanner input = new Scanner(System.in);
for (int i = 0; i < studentList.size(); i++) {
System.out.println("Please enter the grade for Test #" + (testNumber + 1) + " For Student " + studentList.get(i).getStudentName());

[code]....

View Replies View Related

How To Compare Int To A Empty String To Input Error Message To User

Apr 16, 2015

I made a guess a number program but I am having issue figuring out a way that when a user enter's in nothing for the program to spit out a message saying "hey entering nothing doesn't work try again" then ask for input. I have done some research and from what I have found is to read the input in as a String rather than int, and use something like Integer.valueOf() to get the integer value but I am completely lost on how to apply that to my program here is my code

//import statements
import java.util.*; //for scanner class
// class beginning
public class Guess {
public static void main(String[] args ) {
//Declare variables area
int guess, secretNumber = (int) (Math.random() * 10 + 1), lowGuess,highGuess;

[Code] ....

View Replies View Related

Empty Strings Not Accepted On User Input

Apr 7, 2014

I've been trying to get my program to not accept empty strings when the user inputs, but I'm having some difficulties. I've tried for loops, as well as while loops.

import java.util.Scanner;
public class GasMileage
{
/**
* displayIntro
* This method displays the introduction to the user
*/
public static void displayIntro()

[Code] .....

View Replies View Related

How To Compare Int To Empty String To Input Error

Apr 16, 2015

I am having issues with the program below everything works but I can't figure out a way to add code that if a user just hits enter without inputting anything it says "entering in nothing is not a valid choice" I am stuck on how to compare a int to a string ...

//import statements
import java.util.*; //for scanner class
// class beginning
public class Guess {
public static void main(String[] args ) {
//Declare variables area

[Code] ....

View Replies View Related

Take Replacement String Entered By User And Print Out New String

May 22, 2014

I'm having trouble with the last few lines of the code. It's supposed to take a replacement string entered by the user and print out the new string. For some reason it's now allowing me to enter a replacement string

import java.util.Scanner;
public class Project02 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a long string: ");
String lString = keyboard.nextLine();

[Code] ....

Output:

Enter a long string: the quick brown fox jumped over the lazy dog
Enter a substring: jumped
Length of your string: 44
Length of your substring: 6
Starting position of your substring in string: 20
String before your substring: the quick brown fox
String after your substring: over the lazy dog
Enter a position between 0 and 43: 18
The character at position 18 is x

Enter a replacement string: Your new string is: the quick brown fox over the lazy dog <------ isn't taking user input

View Replies View Related

Take User Input And Display Sum Of Digits Of Entered Number

Nov 6, 2014

I have returned with yet another problem but I think this one might be a bit easier to fix.

So the whole MO of this program is to take user input, and display the sum of the digits of the number they entered. I am supposed to do this by utilizing methods. So far this is what I have and when I compile it tells me that it "cannot find symbol", which I don't understand as I define what "m" is in the for loop. The other error is that it says:

"Exercise6_2.java:22: error: incompatible types: possible lossy conversion from long to int
return result;
^

I don't understand why it's giving me this error nor do I understand why result seems to inherently be an int. (Also the public static int sumDigits(long n) method was given to me by the book so that is what I am supposed to use).

import java.util.Scanner;
public class Exercise6_2 {
public static void main(String[] args) { 
Scanner input = new Scanner(System.in);
System.out.println("Enter a integer");
long n = input.nextLong();

[Code]...

View Replies View Related

Program That Continuously Asks For Alphabet Letter And Stops When Non-Alphabet Letter Entered

Oct 8, 2014

Write a program that continuously asks for an alphabet letter, and stops when a non-alphabet letter is entered. Then output the number of upper case letters, lower case letters, and vowels entered ....

View Replies View Related

Get A String From User Input?

Apr 13, 2014

I trying to get this code to get user input instead of reading from a hardcoded array. I'm getting compile errors while trying to get user input. Here's some of the code:

Java Code: // BubbleSort Java
// compile with: javac BubbleSort.java
// run with: java BubbleSort

[Code]....

View Replies View Related

Prompt User For Integer To Make Sure Length Entered By User Is A Power Of 2

Oct 8, 2014

Basically I need to make a program prompts the user for an integer, check to make sure the length entered by the user is a power of 2 and at least 2. Then I need to convert from base e to base 2 then I need to print the tick marks of a ruler based of the value of the length.

I got the whole converting thing working and the check for a power of 2, that wasn't an issue because it didn't require any recursion. I just don't know how to print out the proper tick mark values.

The way it is supposed to work is that it needs to look like this. Say the user enters 8;

012131210
012345678

Or if the user enters 16;

01213121412131210
01234567890123456

The bottom row is pretty much just the index value, that I print fine.

The top row though is supposed to be the length of the ticks on a ruler, with the middle most value being the value of the conversion from base e to base 2 from above. I can get that printed and what I get just looks like this.

For 8;

000030000
012345678

For 16;

00000000400000000
01234567890123456

As you can see I can get the middle value and the index values below but I don't know how to use recursion to get the right numbers.

Here's my current code.

import java.util.*;
public class TickMarks {
public static void main (String args[]){
Scanner input = new Scanner(System.in);
boolean looping = true;
while(looping == true){
System.out.print("Please enter a length: ");

[Code]...

Now the methods isPowerOfTwo() and printLength() both work fine. However, I'm not sure how to get the left and right side working.

My thoughts were to split the length in half and get a left and right side. I gave both of them arrays so I can keep track of the values. Now as you've seen above I get all zeros and I know it's because that's the default value in an array, I just don't know how to get the proper values.

View Replies View Related

Evaluating User Input For String Or Int

Jan 14, 2015

I have to take a users input. The general gist of the problem is I want to convert a decimal number entered by the user inputs into it's binary equivalent....the conversion part I know how to do.

I'm stuck at the user input phase. If the user inputs a decimal number within the correct range (lets say between 0-5000 for this example) the conversion goes ahead as planned and the program outputs on the screen the binary equivalent.

If on the other hand the user inputs a number outside of this range ... OR a String OR and empty space, an error message is given and the user is asked to try again. I don't know how to handle it if the user enters the different types...int or String.

View Replies View Related

Scanning Known String And Not Input Typed By User?

Jul 29, 2014

I'm having an issue with my program that needs 2 lines of input when I only want one. First I call Scan.nextLine(); to fetch a word. Then I want Scan.findInLine(word).charAt(number); to scan the string word for a letter instead of having to put another line in the console. How do I make Scan.findInLine(word).charAt(number); scan a single String instead of scanning input typed by the user?

View Replies View Related

Getting User Input From TextArea And Storing It As String Value

Jan 20, 2015

I am having trouble with getting a user input once they enter it in to a JTextArea and then storing it in to a string value. See, I wanted the user to enter an answer in to the JTextArea, and then once I store it in to a string value, I would be able to use it later. I wanted to after storing the variable to print it on to a JLabel, but nothing is showing up... Heres my code.

static String usera[]= new String [10];
for (int i=0; i< usera.length; i++) {
//These are the JTextArea names
usera[0]= Question1.getText();
usera[1]= Question2.getText();

[Code].....

I already initialized the JLabels earlier in my code, and I did not feel the need to post all my code here. This is where I am trying to get the string variable and then printing it out.

View Replies View Related

Business Application - Get Input From User And Converts It Into A String

Apr 24, 2014

So this application gets input from the user and converts it into a string. It then uses various methods to set instance variables of this class and ends up printing those classes to display information to the user about that products.

package javaapplication5;
import java.text.NumberFormat;
import java.util.Scanner;
 public class Product
{
private String product;
private String description;
private double price;
 
[Code] ....

I am getting a logical error. My output is this:

Enter a product for information. Choose either Java or C++
java
Prduct: null Description: null Price 0.0

View Replies View Related

Storing Input From User As String Variable And Then Converting It To Double?

Jul 8, 2014

I am trying to make a program that calculates the change due in dollars and cents. The user inputs both the amount due and the amount tendered. My program only works with whole numbers?

View Replies View Related

Hangman Game - How To Scan The String For Input Supplied By User

Dec 9, 2014

My assignment is to create a hangman game. One of my first difficulties with it is how to scan the string for an input supplied by the user.

Here is my method:

//Guesses that character c is in the secret word.
//Updates all instance variables accordingly,
//and returns true if c is present in the secret word.
public boolean guessCharacter(char c){
}

View Replies View Related

Retrieving Result By User Input Different Combination Using String Tokenizer (MYSQL)

Mar 30, 2014

I am creating a simple Symptom Checker application. The problem I have is that I'm trying to retrieve user input (JTextField) by comma's using StringTokenizer which contacts the database for a result which matches the user's input (SELECT * FROM DIAGNOSIS WHERE ?, ?, ?) . It successfully finds the correct result however only in a particular format. Not different combinations....

for example, if I enter say within the JTextField: "tearful, nausea, lack of motivation" it will find the result successfully (as that is how it is formatted within the particular column (in the database table) i wish to display a result from) however, if i enter a different combination of these symptoms: "nausea, lack of motivation, tearful" - it will not find any result. I'm very unsure how to make it work regardless of what is inputted first, second or last.

Here is the code:

public void actionPerformed(ActionEvent e) {
try {
String abc = fieldsymp1.getText();
StringTokenizer str = new StringTokenizer(abc);
while (str.hasMoreTokens()) {
str.nextToken((", ")).trim();
 
[Code] ....

View Replies View Related

Retrieving User Input String From Keyboard - Program Errors (try / Catch)

Sep 23, 2014

I need to design, implement, and test a program to input and analyze a name. The program begins by retrieving a user input string from the keyboard. This string is intended to be the user's name. These are the errors we have to search analyze the user input for: No blanks between names firstName and lastName, Non-alphabetic characters in names, Less than two characters in first name, and Less than two characters in last name. Each of these errors must be thrown. All exceptions must be derived from a programmer-defined class called NameException. Each exception should use a detailed message to differentiate among the file types of errors.

This is the format of my NameException class, is the format itself correct? I will fill in the details of each exception I am just wondering if that is how I should set it up.

public class NameException extends Exception {
private String firstName, lastName;
public NoBlanksException(String firstName,String lastName) {
}
public NonAlphabeticalCharactersException(String firstName, String lastName) {

[Code] .....

I was told not to try and catch thrown errors in the main method, would I just create another method in the Driver class to take care of that then?

View Replies View Related

User Input Data As String And If Verified As Valid Number Then Convert Into Double

Nov 11, 2014

I am writing a code in which a user inputs data as a string and that data must be verified as a valid number. A valid number is anything from 0-100. Then all valid numbers are converted into double numbers.

I am having trouble in how to write the validation part of the code.

Is it suppose to be an if, else statement? And if so how is it suppose to be validated?

View Replies View Related

User Enter Empty Line

Oct 5, 2014

I am learning Java on my own, and I am creating little programs to do so.The program below asks the user to input text and hit enter. When user does that, it asks if that is correct. If the user enters "y," the program ends. That's good.If the users enters "n," the strGrategul is set to empty which triggers the while statement to start over again. That's good. However, when the program asks the user to "Tell me one thing you are grateful for..." it doesn't wait for user input. Instead it skips to "You said ''? Enter 'y' or 'n'" It thinks the user enter an empty line.

public static void main(String[] args) {
String strGrateful = "";
String strGoal = "";
String strContinue = "";
Scanner scn = new Scanner(System.in);

[code]....

View Replies View Related

How To Accept Enter As Empty Input

Nov 8, 2014

How can I get enter(return) as empty input from user?!

scanner.next will wait until I input a string ...

But I want it when I hit return sets the variable to empty string ...

View Replies View Related

Checking If Any Input Has Been Entered

Jan 12, 2015

I just can't find a way to check if user puts any input or not? The line is Employee Name and I need to validate that he puts something there.

import java.util.Scanner;
public class JavaMartInventorySystem {
public static void main(String[] args) {
String empName;
Scanner keyboard = new Scanner(System.in);

[Code] ....

View Replies View Related

String Testing For Null / Empty?

Oct 13, 2014

I've been beavering away with Java for a few months. But as with all languages the String implementation looks designed to trip up even experienced programmers.

My current development gets data from various sources outside my control. When I get a string I want to test if it is empty/null/or whatever. Simple enough one thinks.

But if you search the internet you see everone seems to have a slightly different approach. So what is the best way of determining that a string is not useful to you?

I've had success with this

if(string == null || string.length() == 0)

But I've seen people using methods - not necessarily of String (e.g equals, empty) and regular expressions.

What is the best approach to this considering coding efficiency and/or processing efficiency (accepting you'd have to be processing a lot of strings for the latter to be an issue).

View Replies View Related

Compile Error - Empty String?

Jul 1, 2014

I'm writing basically my first program for school. I've written small ones, following instructions, but this is the most vague. I'm having issues. I can't figure out what the error means. I'm not done with the code, but I think the ArrayList is throwing me off. I'm trying to gather user input and sum the total. Here's the code:

package graduationplanner;
import java.util.ArrayList;
import java.util.Scanner;
import java.lang.Double;
 public class GraduationPlanner {
public static void main(String[] args) {

[Code] ....

View Replies View Related

Validate Date When Entered By User

Oct 13, 2014

Below is my current program for my java class. The assignment is to validate a date when entered by user.

import java.util.*;
public class Date{
public static void main (String arg[]){
int month = 0;
int day = 0;
int year = 0;

[Code] ......

My issue with my program is the output for the day.

If I enter 30 for the date I get this: Date is invalid
Date is invalid
Date is invalid
Date is invalid
Date is invalid

I wanted to know how what is wrong and why it is doing this.

View Replies View Related

Identifying Hashes That User Has Entered

Jun 18, 2014

Before continuing a task, any more accurate way to identify hashes? Currently, I am using regex + length of hash to give the user possible hashes.

Identifier class:

package votek;
* Purpose: Class is used to run checks on possible hashes that the user has entered.
*/
public class Identifier {

//Hash entered by user is stored here
private String hash;
//String that will contain all possible hashes to share with user
private String results = "Possible Hashes: ";
//Method that runs the other hash methods checks and prints out the results.

[Code] ...

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved