How to make a Scanner accept only alphabetical character using If statement - string

I am very much a beginner at Java programming I'm in the middle of writing a program that sorts names in alphabetical order. How can I code an "if" statement so that it only accepts alphabetical characters? In my code I have "if (in.hasNext() != String)" which is clearly wrong, but im just trying anything now. Here is my code.
import java.util.*;
public class AlphaOrder
{
public static void main(String[] args)
{
ArrayList<String> names = new ArrayList<String>();
System.out.println("Enter a name, enter \"Sort\" to sort the names alphabetically, enter \"Quit\" to end: ");
Scanner in = new Scanner(System.in);
while (in.hasNext())
{
names.add(in.next());
if (in.hasNext("Sort"))
{
System.out.println("The names in alphabetical order are: " + names);
}
if (in.hasNext("Quit"))
{
System.out.println("This Program has stopped.");
}
if (in.hasNext() != String)
{
System.out.println("Please enter only alphabetical characters.");
}
}
}
}

1) You probably want to change your logic a bit:
import java.util.*;
public class AlphaOrder
{
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<String>();
System.out.println("Enter a name, enter \"Sort\" to sort the names alphabetically, enter \"Quit\" to end: ");
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
String sLine = in.next ();
if (sLine.equals ("Sort")) {
System.out.println("The names in alphabetical order are: " + names);
doSort ();
}
if (sLine.equals ("Sort")) {
System.out.println("This Program has stopped.");
doExit ();
}
if (!isAlpha (sLine)) {
System.out.println("Please enter only alphabetical characters.");
continue;
}
names.add(sLine);
}
}
}
2) There are lots of ways to check "isAlpha()". I would look at "regular expressions":
http://www.vogella.com/articles/JavaRegularExpressions/article.html
3) Here's one "naive" implementation:
boolean isAlpha (String s)
{
String s2 = s.toUpperCase();
for (int i = 0; i < s2.length(); i ++) {
if (s2.charAt(i) < 'A' || s2.charAt(i) > 'Z')
return false;
}
return true;
}

Related

C sharp error and concat strings doesn't work

Why this simple program doesn't work?
using System;
namespace ConsoleApp7
{
class Program
{
static void Main(string[] args)
{
string name;
string all;
for (int i = 1; i <= 3; i++)
{
Console.WriteLine("enter name");
name = Console.ReadLine();
Console.WriteLine(name);
all =string.Concat(all, name);
}
Console.WriteLine("all the names are ");
// Console.WriteLine(s1);
}
}
}
It gives an error and does not cascade all strings?
Thanks
You need to initialize the value of variable all. Here's a sample that works:
static void Main(string[] args)
{
string name;
string all = null;
for (int i = 1; i <= 3; i++)
{
Console.WriteLine("enter name");
name = Console.ReadLine();
Console.WriteLine(name);
all = string.Concat(all, name);
}
Console.WriteLine("all the names are ");
Console.WriteLine(all);
}
Note, however, that there are no separators added beween the three names. If someone would enter "one" and "two" and "three", for instance, then the output would be "onetwothree". Maybe you want something different, maybe not.

How to avoid java.util.NoSuchElementException

The code below is giving me the error java.util.NoSuchElementException right after I Ctrl+Z
to indicate that the user input is complete. By the looks of it seems as if it does not know how to just end one method without messing with the other scanner object.
I try the hasNext method and I ended up with an infinite loop, either way is not working. As a requirement for this assignment I need to be able to tell the user to use Ctrl+Z or D depending on the operating system. Also I need to be able to read from a text file and save the final tree to a text file please help.
/* sample input:
CSCI3320
project
personal
1 HW1
1 HW2
1 2 MSS.java
2 p1.java
*/
import java.util.Scanner;
import java.util.StringTokenizer;
public class Directory {
private static TreeNode root = new TreeNode("/", null, null);
public static void main(String[] args) {
userMenu();
System.out.println("The directory is displayed as follows:");
root.listAll(0);
}
private static void userMenu(){ //Displays users menu
Scanner userInput = new Scanner(System.in);//Scanner option
int option = 0;
do{ //I believe the problem is here since I am not using userInput.Next()
System.out.println("\n 1. add files from user inputs ");
System.out.println("\n 2. display the whole directory ");
System.out.println("\n 3. display the size of directory ");
System.out.println("\n 0. exit");
System.out.println("\n Please give a selection [0-3]: ");
option = userInput.nextInt();
switch(option){
case 1: addFileFromUser();
break;
case 2: System.out.println("The directory is displayed as follows:");
root.listAll(0);
break;
case 3: System.out.printf("The size of the directory is %d.\n", root.size());
break;
default:
break;
}
}while( option !=0);
userInput.close();
}
private static void addFileFromUser() {
System.out.println("To terminate inp1ut, type the correct end-of-file indicator ");
System.out.println("when you are prompted to enter input.");
System.out.println("On UNIX/Linux/Mac OS X type <ctrl> d");
System.out.println("On Windows type <ctrl> z");
Scanner input = new Scanner(System.in);
while (input.hasNext()) { //hasNext being used Crtl Z is required to break
addFileIntoDirectory(input); // out of the loop.
}
input.close();
}
private static void addFileIntoDirectory(Scanner input) {
String line = input.nextLine();
if (line.trim().equals("")) return;
StringTokenizer tokens = new StringTokenizer(line);
int n = tokens.countTokens() - 1;
TreeNode p = root;
while (n > 0 && p.isDirectory()) {
int a = Integer.valueOf( tokens.nextToken() );
p = p.getFirstChild();
while (a > 1 && p != null) {
p = p.getNextSibling();
a--;
}
n--;
}
String name = tokens.nextToken();
TreeNode newNode = new TreeNode(name, null, null);
if (p.getFirstChild() == null) {
p.setFirstChild(newNode);
}
else {
p = p.getFirstChild();
while (p.getNextSibling() != null) {
p = p.getNextSibling();
}
p.setNextSibling(newNode);
}
}
private static class TreeNode {
private String element;
private TreeNode firstChild;
private TreeNode nextSibling;
public TreeNode(String e, TreeNode f, TreeNode s) {
setElement(e);
setFirstChild(f);
setNextSibling(s);
}
public void listAll(int i) {
for (int k = 0; k < i; k++) {
System.out.print('\t');
}
System.out.println(getElement());
if (isDirectory()) {
TreeNode t = getFirstChild();
while (t != null) {
t.listAll(i+1);
t = t.getNextSibling();
}
}
}
public int size() {
int s = 1;
if (isDirectory()) {
TreeNode t = getFirstChild();
while (t != null) {
s += t.size();
t = t.getNextSibling();
}
}
return s;
}
public void setElement(String e) {
element = e;
}
public String getElement() {
return element;
}
public boolean isDirectory() {
return getFirstChild() != null;
}
public void setFirstChild(TreeNode f) {
firstChild = f;
}
public TreeNode getFirstChild() {
return firstChild;
}
public void setNextSibling(TreeNode s) {
nextSibling = s;
}
public TreeNode getNextSibling() {
return nextSibling;
}
}
}
Exception Details:
/*Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Directory.userMenu(Directory.java:36)
at Directory.main(Directory.java:21)*/
Your problem is this line:
option = userInput.nextInt(); //line 24
If you read the Javadoc, you will find that the nextInt() method can throw a NoSuchElementException if the input is exhausted. In other words, there is no next integer to get. Why is this happening in your code? Because you this line is in a loop once that first iteration completes (on the outer while loop) your initial input selection has been consumed. Since this is a homework, I am not going to write the code. But, if you remove the loop, you know this works at least once. Once you try to loop, it breaks. So I will give you these hints:
Change the do/while to a while loop.
Prompt the user once outside the loop.
Recreate the prompt and recapture the user input inside the loop.
For example, the code below can be used for the basis of your outer loop.
import java.util.Scanner;
public class GuessNumberGame {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Guess the secret number: (Hint: the secret number is 1)");
int guess = input.nextInt();
while (guess != 1) {
System.out.println("Wrong guess. Try again: ");
guess = input.nextInt();
}
System.out.println("Success");
input.close();
}
}
The reason why this works is because I don't reuse the same, exhausted, scanner input object to get the next integer. In your example, the initial input is inside the loop. The second time around, that input has already been consumed. Follow this pattern and you should be able to complete your assignment.

Console project fails with console.writeline but not console.readline

I have a small sample program which breaks when it reaches line 50 with "Error CS1513: } expected". It's typical, except that I counted the number of curly brackets over and over and found no error. I was told on another forum that the problem is probably my placement of the using keyword and class declarations, but I couldn't find anything wrong.
I would like to know if I'm making a mistake. This is the entire program; written with SharpDevelop if it makes any difference.
using System;
namespace Problem
{
public class ClassA
{
public static void Main(string[] args)
{
ClassB MyObject = new ClassB();
MyObject.MethodA();
}
}
public class ClassB
{
public String str_a = "";
public String str_b = "";
public String str_c = "";
public bool bool_a = false;
public int[] int_a = new int[6];
public void MethodA()
{
while (str_a == "" || str_a == null)
{
String str_a2 = Console.ReadLine();
if (str_a2 == "" || str_a2 == null)
{
}
else
{
str_a = str_a2;
}
}
while (str_c == "")
{
String str_c2 = Console.ReadLine();
if (str_c2 == "" || str_c2 == null)
{
}
else
{
str_c = str_c2;
}
}
while (bool_a == false)
{
Console.WriteLine(""); //Fails to compile, asks for ending brackets here
for (int i = 0; i < 6; i += 1)
{
int_a[i] = 0;
}
bool_a = true;
}
}
}
}
I'm pretty sure you could be a victim of UNICODE quotes.
ʺ ̋“”″"
Try just removing the double-quote characters and typing them in your code editor.
Doh! Classic error! I had a declaration in a while loop:
while {
public int[] int_b = new int[6];
}
Sorry about that, SO. I was having one of those days...

I'm getting Resource Leaks

Whenever I run this code, it works pretty smoothly, until the while loop runs through once. It will go back and ask for the name again, and then skip String b = sc.nextLine();, and print the next line, instead.
static Scanner sc = new Scanner(System.in);
static public void main(String [] argv) {
Name();
}
static public void Name() {
boolean again = false;
do
{
System.out.println("What is your name?");
String b = sc.nextLine();
System.out.println("Ah, so your name is " + b +"?\n" +
"(y//n)");
int a = getYN();
System.out.println(a + "! Good.");
again = askQuestion();
} while(again);
}
static public boolean askQuestion() {
System.out.println("Do you want to try again?");
int answer = sc.nextInt();
if (answer == 1) {
return true;
}
else {
return false;
}
}
static int getYN() {
switch (sc.nextLine().substring(0, 1).toLowerCase()) {
case "y":
return 1;
case "n":
return 0;
default:
return 2;
}
}
}
Also, I'm trying to create this program in a way that I can ask three questions (like someone's Name, Gender, and Age, maybe more like race and whatnot), and then bring all of those answers back. Like, at the very end, say, "So, your name is + name +, you are + gender +, and you are + age + years old? Yes/No." Something along those lines. I know there's a way to do it, but I don't know how to save those responses anywhere, and I can't grab them since they only occur in the instance of the method.
Don't try to scan text with nextLine() AFTER using nextInt() with the same scanner! It may cause problems. Open a scanner method for ints only...it's recommended.
You could always parse the String answer of the scanner.
Also, using scanner this way is not a good practice, you could organize questions in array an choose a loop reading for a unique scanner instantiation like this:
public class a {
private static String InputName;
private static String Sex;
private static String Age;
private static String input;
static Scanner sc ;
static public void main(String [] argv) {
Name();
}
static public void Name() {
sc = new Scanner(System.in);
String[] questions = {"Name?","Age","Sex?"};//
int a = 0;
System.out.println(questions[a]);
while (sc.hasNext()) {
input = sc.next();
setVariable(a, input);
if(input.equalsIgnoreCase("no")){
sc.close();
break;
}
else if(a>questions.length -1)
{
a = 0;
}
else{
a++;
}
if(a>questions.length -1){
System.out.println("Fine " + InputName
+ " so you are " + Age + " years old and " + Sex + "." );
Age = null;
Sex = null;
InputName = null;
System.out.println("Loop again?");
}
if(!input.equalsIgnoreCase("no") && a<questions.length){
System.out.println(questions[a]);
}
}
}
static void setVariable(int a, String Field) {
switch (a) {
case 0:
InputName = Field;
return;
case 1:
Age = Field;
return;
case 2:
Sex = Field;
return;
}
}
}
Pay attention on the global variables, wich stores your info until you set them null or empty...you could use them to the final affirmation.
Hope this helps!
Hope this helps!

Reverse String Palindrome

Hi I am trying to reverse a String to make a palindrome. Can someone please give me a tutorial on how to reverse a string? I have read some tutorials online and I have tried applying them to the palindrome program that i am writing but have not been successful.
import java.util.Random;
public class IterativePalindromGenerator {
public static void main(String[] args) {
Random random = new Random();
int floorValue = 1;
int cielingValue = 20;
int randomNumber = random.nextInt(cielingValue - floorValue)
+ floorValue;
String alphabetLetters = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < randomNumber; i++) {
char generatedLetters = alphabetLetters.charAt(random
.nextInt(alphabetLetters.length()));
String generatedLetterSTRINGType = Character
.toString(generatedLetters);// converts char to string
System.out.print(generatedLetterSTRINGType);
}
}
}
To reverse a string you can use StringBuffers reverse() method:
public String reverse(String stringToReverse) {
return new StringBuffer(stringToReverse).reverse().toString();
}
Hey here is my code from a college course. Our task was to implement a recursive procedure. Hope this can help the community.
package DiskreteMathe;
import java.util.*;
public class AufgabePalindromTestRekursiv {
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Please enter text here:");
String text= sc.next();
System.out.println(testPalindrom(text));
}
public static boolean testPalindrom (String text){
if (text.length()==2 && text.charAt(0)==text.charAt(1) || text.length()==1)
return true;
if(text.charAt(0)!=text.charAt(text.length()-1)){
return false;
} else {
text = text.substring(1, text.length()-1);
return testPalindrom(text);
}
}
}
When creating a palindrome for existing string, you need to think of the cases of even and odd outcome strings. For example, if you input String "abc", you should expect there are two outcome palindrome strings: abccba (even) and abcba (odd).
Here is my code:
public class PalindromeGenerator {
public static void main(String[] args) {
String str = "abc";
String reverse_str = "";
for (int n = str.length(); n>0; n--){
reverse_str += str.substring(n-1, n);
}
String even_str = str + reverse_str;
String odd_str = str.substring(0, str.length()-1) + reverse_str;
System.out.println(even_str); // print "abccba"
System.out.println(odd_str); //print "abcba"
}
}
I Hope this can help you.

Resources