Setting required length of a string - java

Pretty basic question I believe... lets say I had this program and the access code had to specifically be 13 characters long. How would I make it so that if it wasn't 13 long then the user would have to retry and enter it again?
import java.util.Scanner;
public class access code
{
Scanner scan;
public void go()
{
String code = ("Enter your access code: ");
}
}

Per request, here's some explanation as to why this works. You need to repeatedly ask for information until the user enters something consisting of 13 characters. This code gets user input while the length of input is not 13. Which means that the loop terminates when the length is 13.
String input = "";
while (input.length() != 13){
System.out.print("Enter code: ");
input = scan.nextLine();
}

Related

Why does the getValidStr method turn into an infinite loop?

import java.util.Scanner;
public class ValidateMe {
public static void main(String[] args) {
int c;
String d;
Scanner scnr = new Scanner(System.in);
c = getValidIntScore(scnr);
d = getValidStrName(scnr);
}
public static int getValidIntScore(Scanner scnr){
int c;
System.out.println("Enter an integer test score between 0-100 inclusive:");
c = scnr.nextInt();
while (c < 0 || c > 100) {
System.out.println("Test score must be a value between 0-100 inclusive. Enter the test score:");
c = scnr.nextInt();
}
return c;
}
public static String getValidStrName(Scanner scnr){
String c;
System.out.println("Enter student's full name:");
c = scnr.nextLine();
while (c.isEmpty()){
System.out.println("Name must be non-empty and non-blank. Enter the student's full name:");
}
return c;
}
}
When I run this, I can get the test score just fine, but when I get to the student's name, I cannot even enter input and it keeps running over and over... How can I fix this?
You have 2 problems in this;
mixing nextX and nextLine without setting delimiter
You can't mix nextLine and next(anything else) without things going rather wrong. It sounds like you want one enter to be equal to one input. That's easily done:
Update the scanner to tell it that you want it to scan for newlines, not whitespace. After making the scanner (new Scanner), immediately run:
scanner.useDelimiter("\r?\n");
Which tells it that input is separated by newlines (enter presses). All other solutions (such as throwing nextLine() calls in to 'reset' it) result in issues if the user enters space-separated things when you ask for non-full-line inputs (even though it is extremely common advice here on SO, the delimiter thing is simpler and doesn't fail in such cases).
Not re-reading in the loop
Computer does as it is told.
You are asking it: Hey, as long as c is empty, do the following: print that c is not empty.
So, it'll just spam that line over and over. c is empty and will remain empty forever, which is why it does that. You'd have to update c inside that while block at the end there, e.g. with c = scanner.nextLine();.

How to control how many letters and numbers the user enters into an input prompt?

I'm new to programming and we were given our first assignment! My whole code is working fine, but here is my problem:
We have to prompt the user to enter in an account ID that consists of 2 letters followed by 3 digits.
So far I only have a basic input/output prompt
//variables
String myID;
//inputs
System.out.println("Enter your ID:");
myID = input.nextLine();
So all it does is let the user enter in how many letters and digits they want, in any order and length. I don't understand how to "control" the user's input even more.
As you said you are not aware of regex ,I have written this code to iterate by while loop and check if each character is a alphabet or digit. User is prompted to provide account number till the valid one is entered
import java.util.Scanner;
class LinearArray{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
boolean isIdValid = false;
String myId;
do{
System.out.println("account ID that consists of 2 letters followed by 3 digits");
myId = input.nextLine();
//Check if the length is 5
if (myId.length() == 5) {
//Check first two letters are character and next three are digits
if(Character.isAlphabetic(myId.charAt(0))
&& Character.isAlphabetic(myId.charAt(1))
&& Character.isDigit(myId.charAt(2))
&& Character.isDigit(myId.charAt(3))
&& Character.isDigit(myId.charAt(4))) {
isIdValid = true;
}
}
}while(!isIdValid);
}
}

Java Strange String Spacing Issue

I am creating a java program that uses a cipher to encode any message the user types in. It works flawlessly with single words like "hello" and "testing", but begins to fall apart when you add spaces, like the message "hello world." Here is the code:
import java.util.Scanner;
import java.util.ArrayList;
public class Code {
public static void main(String[] args) {
Scanner shiftValue = new Scanner(System.in);
System.out.print("Please enter shift value: ");
int shift = shiftValue.nextInt();
String alphabet = "abcdefghijklmnopqrstuvwxyz";
Scanner input = new Scanner(System.in);
String codeInput = "anything";
int index = 0;
while(!codeInput.equals("end")) {
System.out.println();
System.out.println("Please enter message: ");
codeInput = input.next();
for(int i = 0; i < codeInput.length(); i++){
if(Character.isWhitespace(codeInput.charAt(i))){
System.out.print(" ");
}
else {
while(alphabet.charAt(index) != codeInput.charAt(i)){
index++;
}
if(index > 25 - shift){
index = index - (26 - shift);
System.out.print(alphabet.charAt(index));
}
else {
System.out.print(alphabet.charAt(index + shift));
}
}
index = 0;
}
}
} //method
} //class
When I type start the program, it asks for a shift value, which decides how many letters to shift the cipher. After that, it goes into a while loop, forever asking the user for input, then outputting an encoded version of the input, until the word "end" is typed. In the eclipse console, it looks like this:
Please enter shift value: 3
Please enter message:
hello
khoor
Please enter message:
testing
whvwlqj
Please enter message:
However, when I type multiple words with spaces between them, it looks like this:
Please enter shift value: 3
Please enter message:
hello world
khoor
Please enter message:
zruog
Please enter message:
For some reason, instead of displaying both words in the same sentence format as the input, it encodes the first word, then goes through the entire while loop again before encoding the second word.
I have no idea why this happens, so I would appreciate any help or advice you guys could give me.
Thank you for reading my post, and have a wonderful day.
The Scanner splits the input for you already and by default by whitespaces.
JavaDoc:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

ArrayIndexOutOfBoundsException on a Split String in a array

So I am doing some problems on the UVa online problem judge, but on a relativity easy problem, I keep on getting a ArrayIndexOutOfBoundsException. To understand the code, here is the problem.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
int sum = 0;
for (int i = 0; i <= t; i++){
String d = scan.nextLine();
if (d.equals("report")) {
System.out.println(sum);
} else {
String[] parts = d.split(" ");
int z = Integer.parseInt(parts[1]);
sum+=z;
}
}
}
}
The error message is:
reportException in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Main.main(Main.java:16)
And I am using the sample input given.
Edit:
I have already tried added println statements in the code and figured out that the number is not being read. I am trying to understand why.
OK, after some messing around on my machine I think I found what might be at least part of the problem. The issue is that I'm not sure what the precise input is, so I'm going off of what I could get working on my machine.
So you start up your program, and it waits for a prompt at this line:
int t = scan.nextInt();
You enter your integer, and the program moves on as expected:
Input: 100 // Then press enter to continue
The input is parsed, and now t is set to 100.
Then when your program enters your for loop, it comes across this line:
String d = scan.nextLine();
Yet for some reason the program doesn't wait for input! (Or at least it didn't on my machine)
I believe the issue lies here:
Input: 100 // Then press enter to continue
^^^^^^^^^^^
What I think is happening is that your input is really
Input: 100\n
^^
That character (\r\n on Windows) is what's input when you hit enter. It's a newline character that tells the console to go to the next line.
So as a result, what I think happens is this:
Input: 100\n
Scanner parses 100, leaving the \n in the input stream
Then at the nextLine() call, the scanner sees \n on the input stream, which denotes end of line, so it thinks you already input the entire line! Because what it thought was your input was only the newline character, it returns an empty string, because your "input" was an empty string and the newline character. Your program then goes to split the newline character by spaces, rightly returns an array with a single element, and then your program promptly crashes when accessing an out-of-bounds index.
What might work better is reading an entire line first and parsing the integer so your scanner doesn't get ahead of itself, like this:
int t = Integer.parseInt(scan.nextLine());
Just as a warning: This is what I've been able to come up with based on using OP's code as-is on my machine. I was unable to get a situation where the only element in parts was "donate". I will update further as I get more info.
The error message means the array parts's length less than 2, sometimes.
It means the variable d does not always contain the string BLANK SPACE, " ", what you split by.
try this code:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
int sum = 0;
for (int i = 0; i <= t; i++){
String d = scan.nextLine();
if (d.equals("report")) {
System.out.println(sum);
} else {
String[] parts = d.split(" ");
/*
* Add IF statement,
*/
if (parts.length() > 1) {
int z = Integer.parseInt(parts[1]);
sum+=z;
}
}
}
}
}

how to avoid pressing several time enter affects the input data?

I'm writting a JAVA Class to validate input data, especifically integer numbers.
The class I develop is running fine but when I press more than one time enter and then a char type, it display several times " Error!! Invalid number. Try again. " and I would like to avoid it.
I have use nextLine() method but it doesn't seems to correct it.
Here is the Class:
package chapter07.libro;
import java.util.Scanner;
public class Validator_integer
{
public static int getInt (Scanner scanner, String promt)
{
int numberInteger = 0;
boolean isValid = false;
System.out.println(promt);
while(isValid == false)
{
if(scanner.hasNextInt())
{
numberInteger= scanner.nextInt();
isValid = true;
}//if
else
{
System.out.println("Error!! Invalid number. Try again.");
}//else
scanner.nextLine();
}//while
return numberInteger;
}//getInt
}//Validator_integer
and next is the app to use the class:
package chapter.prueba;
import java.util.Scanner;
import chapter07.libro.Validator_integer;
public class Test_Validator_Integer
{
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
String choice = "y";
while(choice.equalsIgnoreCase("y"))
{
int number = Validator_integer.getInt(sc, "Enter integer number: ");
System.out.println(number);
System.out.println("Continue (y/n): ");
choice = sc.next();
}//while
}//main
}//Test_Validator_Integer
The results I get are next:
Enter integer number:
2
2
Continue (y/n):
y
Enter integer number:
(Here I press several time enter)
xx
Error!! Invalid number. Try again.
Error!! Invalid number. Try again.
Error!! Invalid number. Try again.
Error!! Invalid number. Try again.
2
2
Continue (y/n):
n
So the part of (Error!! Invalid number. Try again.) displayed several times, is the one I would like to avoid.
Does any one know how to fix it???
Thanks in advance!!!
Before you read from System.in, make sure to "clear" it's contents to get rid of buffered/queued-up input. If there are n characters queued-up, then skip that many chars and you'll need to enter something new.
int n = System.in.available();
System.in.skip(n);
http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html

Categories

Resources