Two methods executing at the same time? Why? - java

package contractmanager;
import java.util.*;
/**
*
* #author Tom McCloud
*/
public class ContractManager {
static Scanner keyb = new Scanner(System.in);
// global scanner
public static void main(String[] args) {
int option;
//variable declaration
String clientName;
String packageSize;
String dataBundle;
String reference;
int period;
boolean intlCalls;
//display menu to user
System.out.println("Welcome: \n");
System.out.println("1. Enter new contract ");
System.out.println("2. Display contract summary");
System.out.println("3. Display summary of contract for selected month");
System.out.println("4. Find and display contract");
System.out.println("0. Exit");
//take option off user
option = keyb.nextInt();
//WIP - only working on option 1 at the minute
switch(option) {
case 1:
clientName = clientName();
packageSize = packageSize();
dataBundle = dataBundle();
reference = reference();
break;
}
exit();
}
public static void exit()
{
System.out.println("Thank you for using the contract manager. Goodbye!");
}
public static String clientName()
{
String name = " ";
System.out.println("Please input your full name: ");
name = keyb.nextLine();
return name;
}
public static String packageSize()
{
String size;
System.out.println("Please input your package size: ");
System.out.println(" 1. Small \n 2. Medium \n 3. Large");
size = keyb.next();
return size;
}
public static String dataBundle()
{
String data;
System.out.println("Please input data bundle size: ");
System.out.println("1. Low \n 2. Medium \n 3. High \n 4. Unlimited");
data = keyb.next();
return data;
}
public static String reference()
{
String ref;
boolean isRefValid = false;
do {
System.out.println("Please input your reference code: ");
ref = keyb.next();
if(ref.length() > 6)
{
System.out.println("Reference number too long, re-enter!");
}
for(int i = 0; i < 2; i++)
{
if(Character.isDigit(ref.charAt(i)))
{
System.out.println("First two characters must be letters!");
}
}
} while(isRefValid = false);
return ref;
}
}
So, this is some code I have. If I press enter code hereone, it executes these, now technically shouldn't this be in order of one another once each method reaches completion and returns?
For example, on execution after pressing "1" I get the following output:
Please input your full name:
Please input your package size:
1. Small
2. Medium
3. Large
Whereas this should come one by one, after the full name has been inputted it should move onto the package size step. If I input it goes to the third step rather than repeating for the second step's input.

I think it's because in your clientName function you have just printed "Please input your full name: " without waiting for input. For example you have to do something like below here scan.nextLine() will wait until user have press enter:
Scanner scan = new Scanner();
System.out.println("Please input your full name:");
String name= scan.next();
System.out.println(name);
scan.nextLine();
Updated: Try by updating clientName function as below
public static String clientName() {
String name = " ";
System.out.println("Please input your full name: ");
name = keyb.next();
keyb.nextLine();
return name;
}

Related

How to validating user input with hasNext(); while?

I'm building a phone book program where it asks the user for a set of questions, Q1: Enter your name, Q2: Enter your username, Q3: Enter your number. I'm struggling to include exceptions in my program.
public void Q1(){
Scanner scan = new Scanner(System.in);
do {
System.out.println("Enter the name of the person: ");
while (!scan.hasNext()) {
System.out.println("Invalid Input!");
scan.next();
}
firstName = scan.next();
}while(firstName != null);
Q2();
}
Q2(); has practically the same code as Q1();. My problem here is validating user input and moving onto the next question.
Build a method that verifies the string input if empty string entered by the user then print invalid input until getting valid one, and verify the string of the digits using the REGEX \\d+ which means one digit or more, like this:
String name, username;
int number;
public void Q1(Scanner scan) {
System.out.println("Enter the name of the person: ");
name = readAndCheckString(scan);
}
public void Q2(Scanner scan) {
System.out.println("Enter the username of the person: ");
username = readAndCheckString(scan);
}
public void Q3(Scanner scan) {
System.out.println("Enter number of the person: ");
String numberString = readAndCheckDigit(scan);
number = Integer.parseInt(numberString);
}
String readAndCheckString(Scanner scan) {
String input = scan.nextLine();
while ("".equals(input)) {
System.out.println("Invalid Input!");
input = scan.nextLine();
}
return input;
}
String readAndCheckDigit(Scanner scan) {
String numberString = scan.nextLine();
// if numberString is empty or not digit then print invalid
while ("".equals(numberString) || !numberString.matches("\\d+")) {
System.out.println("Invalid Input!");
numberString = scan.nextLine();
}
return numberString;
}

How to repeatedly store data in linked lists?

I have a program where I want to continue adding in an integer and string in a linked list. However when I print out the linked list it only prints out the last entered values and not the previous ones. So If I entered 3 Sally and then entered 6 Bob the linked list only prints out 6 bob. I want to be able to print out everything in the linkedlist no just the last entered.
public class Texteditor {
/**
* #param args the command line arguments
*/
static int myInt;
static String myString;
public Texteditor(int a, String s){
myInt = a;
myString = s;
}
public String toString(){
return myInt + " " + myString;
}
public static void main(String[] args) {
LinkedList<Texteditor> myLL = new LinkedList<Texteditor>();
int isExit = 0;
System.out.println("Hello Welcome to Your Personal Texteditor! ");
System.out.println("There are many options you can do with this text editor");
System.out.println("1. If you enter a line number with no text, the line number will be deleted.");
System.out.println("2. If you enter LIST alone the editor will print everything in the list with line number.");
System.out.println("3. If you enter RESEQUENCE the line numbers will be resequenced to start at 10.");
while(isExit ==0) {
// myLL = new LinkedList<Texteditor>();
System.out.println("");
System.out.println("Please enter the line number: ");
Scanner kb = new Scanner(System.in);
myInt = kb.nextInt();
System.out.println("Plese enter text as a string: ");
Scanner kb1 = new Scanner(System.in);
myString = kb1.nextLine();
Texteditor a1 = new Texteditor(myInt, myString);
myLL.add(a1);
System.out.println("Would you like to keep going? Enter yes or no: " );
Scanner kb2 = new Scanner(System.in);
if (kb2.next().equals("no")){
isExit = 1;
}
}
for (Texteditor element : myLL){
System.out.println(element + "\n");
}
}
}
Your myInt and myString are static, which means they're shared by instances. Make them non-static and the code should work correctly.
Also, don't recreate the Scanner every time in the loop. Once is enough.
The problem is that you are making the myInt and myString variables static. Remove the static modifier and then in your while loop, instead of referencing the class's myInt and myString variables, create local int and String variables instead.
public class Texteditor {
/**
* #param args the command line arguments
*/
int myInt;
String myString;
public Texteditor(int a, String s){
myInt = a;
myString = s;
}
public String toString(){
return myInt + " " + myString;
}
public static void main(String[] args) {
LinkedList<Texteditor> myLL = new LinkedList<Texteditor>();
int isExit = 0;
System.out.println("Hello Welcome to Your Personal Texteditor! ");
System.out.println("There are many options you can do with this text editor");
System.out.println("1. If you enter a line number with no text, the line number will be deleted.");
System.out.println("2. If you enter LIST alone the editor will print everything in the list with line number.");
System.out.println("3. If you enter RESEQUENCE the line numbers will be resequenced to start at 10.");
while(isExit ==0) {
// myLL = new LinkedList<Texteditor>();
System.out.println("");
System.out.println("Please enter the line number: ");
Scanner kb = new Scanner(System.in);
int myInt = kb.nextInt();
System.out.println("Plese enter text as a string: ");
Scanner kb1 = new Scanner(System.in);
String myString = kb1.nextLine();
Texteditor a1 = new Texteditor(myInt, myString);
myLL.add(a1);
System.out.println("Would you like to keep going? Enter yes or no: " );
Scanner kb2 = new Scanner(System.in);
if (kb2.next().equals("no")){
isExit = 1;
}
}
for (Texteditor element : myLL){
System.out.println(element + "\n");
}
}
}
The problem with your code is that the variables myInt and myString are static and hence they don't belong to each individual object (they belong to the class). Thus when you reference them here:
for (Texteditor2 element : myLL){
System.out.println(element + "\n");
}
You're calling the same values you set last n amount of times.
This should fix the problem:
Create a new TextEditorObject file:
public class TextEditorObject {
int myInt;
String myString;
public TextEditorObject(int a, String s){
myInt = a;
myString = s;
}
public String toString() {
return myInt + " " + myString;
}
}
Change Texteditor like so:
public class Texteditor {
public static void main(String[] args) {
int myInt;
String myString;
LinkedList<TextEditorObject> myLL = new LinkedList<TextEditorObject>();
int isExit = 0;
System.out.println("Hello Welcome to Your Personal Texteditor! ");
System.out.println("There are many options you can do with this text editor");
System.out.println("1. If you enter a line number with no text, the line number will be deleted.");
System.out.println("2. If you enter LIST alone the editor will print everything in the list with line number.");
System.out.println("3. If you enter RESEQUENCE the line numbers will be resequenced to start at 10.");
while(isExit ==0) {
// myLL = new LinkedList<Texteditor>();
System.out.println("");
System.out.println("Please enter the line number: ");
Scanner kb = new Scanner(System.in);
myInt = kb.nextInt();
System.out.println("Plese enter text as a string: ");
Scanner kb1 = new Scanner(System.in);
myString = kb1.nextLine();
TextEditorObject a1 = new TextEditorObject(myInt, myString);
myLL.add(a1);
System.out.println("Would you like to keep going? Enter yes or no: " );
Scanner kb2 = new Scanner(System.in);
if (kb2.next().equals("no")){
isExit = 1;
}
}
for (TextEditorObject element : myLL){
System.out.println(element + "\n");
}
}
}

Repeat a method from "if" until a proper value to be returned is entered

I'm trying to learn the basics of Java when I have nothing to do at work, and I wanted to play around with input. This is what I have now:
import java.util.Scanner;
public class Input {
private static Scanner input;
public static void main(String [] args){
String name = (askName());
double age = (askAge());
System.out.println("Your name is " + name + " and your age is " + age);
}
static String askName(){
System.out.print("What is your name?");
input = new Scanner(System.in);
//listens for strings
String name = input.next();
return name;
}
static double askAge(){
System.out.print("What is your age?");
input = new Scanner(System.in);
//listens for doubles
double age = input.nextDouble();
if (input.hasNextDouble()){
return age;
} else {
System.out.println("Please insert a number:");
askAge();}
}
}
And this is what I get:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
This method must return a result of type double
at Input.askAge(Input.java:16)
at Input.main(Input.java:6)
What do I do to force the user to enter an integer (that is, how do I make the method repeat itself until it gets an int that it can return?)
Return the value of the recursive call:
System.out.println("Please insert a number:");
return askAge();
However: it would be better to use a loop rather than recursion here, since you could (eventually) get a StackOverflowError if you keep on entering an invalid value.
If condition is used for decision making and not for looping.
Use a while loop , Break the loop when u get the correct value.
I am wiring a sudo code.
while(true){
if (input.hasNextDouble()){
//Assign value to a variable ;
//Break loop
} else {
//Re ask question
System.out.println("Please insert a number:");
}
}
Example link for your help.
The exception you are getting is because you are not returning any value from askAge() in else part.
I would rather do it this way:
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
String name = getString(sc, "What is your name? ");
int age = getInt(sc, "What is your age? ");
System.out.println("Your name is " + name + " and your age is " + age);
}
/* You increase the performance when using an already existing single
scanner multiple times for different reasons (to get a name, first name,
second name, age, etc.), instead of making a new Scanner each time */
public static String getString(Scanner sc, String message) {
System.out.print(message);
return sc.nextLine();
}
public static int getInt(Scanner sc, String message) {
System.out.print(message);
if (sc.hasNextInt()) {
return sc.nextInt();
} else {
sc.next(); // required to skip the current input
return getInt(sc, "Please insert a number: ");
}
}
Please change your mathod like,
static double askAge(){
System.out.print("What is your age?");
input = new Scanner(System.in);
//listens for doubles
if (input.hasNextDouble()){
return input.nextDouble();
} else {
System.out.println("Please insert a number:");
}
return askAge();
}}

StringTokenizers for Java with regular expression

I'm working on a project that requires users input 7 information elements (all at once, separated by commas). If any invalid fields entered, display an message and ask user to input that field again. If all the info. entered correctly. Display all the fields, one field per line with label. Here what I got so far:
import java.util.Scanner;
public class Implementation
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter first name: ");
String firstName = scanner.nextLine();
System.out.println("Please enter last name: ");
String lastName = scanner.nextLine();
System.out.println("Please enter address: ");
String address = scanner.nextLine();
System.out.println("Please enter city: ");
String city = scanner.nextLine();
System.out.println("Please enter state: ");
String state = scanner.nextLine();
System.out.println("Please enter zipcode: ");
String zip = scanner.nextLine();
System.out.println("Please enter phone: ");
String phone = scanner.nextLine();
System.out.println("\nValidate Result:");
if (!validateFirstName(firstName))
System.out.println("Invalid first name");
else if (!validateLastName(lastName))
System.out.println("Invalid last name");
else if (!validateAddress(address))
System.out.println("Invalid address");
else if (!valiadteCity(city))
System.out.println("Invalid city");
else if (!validateState(state))
System.out.println("Invalid state");
else if (!validateZip(zip))
System.out.println("Invalid zipcode ");
else if (!validatePhone(phone))
System.out.println("Invalid phone");
else
System.out.println("Valid input. Thank you!");
}
public static boolean validateFirstName(String firstName)
{
return firstName.matches("[A-Z][a-zA-Z]*");
}
public static boolean validateLastName(String lastName)
{
return lastName.matches("[a-zA-z]+(['-][a-zA-Z]+)*");
}
public static boolean validateAddress(String address)
{
return address.matches("\\d+\\s+([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)");
}
public static boolean valiadteCity(String city)
{
return city.matches("([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)");
}
public static boolean validateState(String state)
{
return state.matches("([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)");
}
public static boolean validateZip(String zip)
{
return zip.matches("\\d{5}");
}
public static boolean validatePhone(String phone)
{
return phone.matches("[1-9]\\d{2}-[1-9]\\d{2}-\\d{4}");
}
}
I'm new to Java and I do not really know what to do for StringTokenizers. The code above I used basic input. However, I wrote a little part for that but do not sure and no idea where to put it.
System.out.println("Enter info. separated by comma: ");
String sentence = scanner.nextLine();
String[] tokens = sentence.split(",");
System.out.printf("Number of elements: %d%nThe tokens are:%n", tokens.length);
for (String token : tokens)
System.out.println(token);
I came up with two problems:
I do not know where/how to do StringTokenizers on my code.
How do I display all the fields if info entered correctly?
It would be nice if you can explain right on my code. Because I'm new and not really sure what to do. Thank you very much!
StringTokenizer uses for splitting the input string into tokens using the specified separator.
For such kind of tasks where you know the sequence of the elements and for each of the elements there are predefined validation I would prefer to avoid using loops.
The main idea of the tasks is firstly to split the input string into the array of elements and then perform validation.
String input = scanner.nextLine();
String[] elements = input.split(',');
if (elements.length != 7) {
System.out.println("Invalid input string");
System.exit(0);
}
String firstName = elements[0];
while (!validateFirstName(firstName)) {
System.out.println("Please enter first name: ");
firstName = scanner.nextLine();
}
String secondName = elements[1];
while (!validateSecondName(secondName)) {
System.out.println("Please enter second name: ");
secondName = scanner.nextLine();
}
// ... The same logic for the other fields.

incorrect input Scanner

hey i am trying to take inputs from user one by one but its appears to take wrong input... it actually skip the one input to be taken from user ..
e.g..in the code below i want to take name first then address and at last contact but when i do so it skip the name input...
import java.util.ArrayList;
import java.util.Scanner;
public class mainClass {
public static void main(String args[]){
int value = 0;
ArrayList<Data> Contacts = new ArrayList<Data>();
Scanner input = new Scanner(System.in);
while(true){
System.out.println("Enter 1 to add a Contact :: Enter 2 to View all Contact");
value = input.nextInt();
switch(value){
case 1:
System.out.println("Plz enter Name : ");
String name = input.nextLine();
System.out.println("Plz enter Address : ");
String address = input.nextLine();
System.out.println("Plz enter ContactNo : ");
String contact = input.nextLine();
Data objt1 = new Data(name, address, contact);
Contacts.add(objt1);
break;
case 2:
System.out.println("Name\t\tContact\t\tAddress");
for(int i=0; i<Contacts.size(); i++)
{
System.out.println(Contacts.get(i));
}
break;
default:
System.out.println("Sorry wrong input");
}
}
}
}
the data class is here
public class Data {
private String name = "";
private String address = "";
private String cell = "";
public Data(String n, String a, String c){
name = n;
address = a;
cell = c;
}
public String toString()
{
return String.format("%s\t\t%s\t\t%s", name, cell, address);
}
}
try adding input.nextLine(); after getting the value, this will consume the new line character
value = input.nextInt();
input.nextLine();
(or)
int value = Integer.parseInt(input.nextLine());

Categories