Im working right now on a program that can divide, add, ect, but, im also making it for others, so, the problems usually have letters as well. What code could I implement so that my program ignores characters, and just focuses on numbers?
import static java.lang.System.out;
import java.util.Scanner;
public class Trinomial {
public static void main(final String args[]) {
final Scanner first = new Scanner(System.in);
out.print("Enter the first number: ");
final int First = first.nextInt();
final Scanner second = new Scanner(System.in);
out.print("Enter the second number: ");
final int Second = second.nextInt();
final Scanner third = new Scanner(System.in);
out.print("Enter the third number: ");
final int Third = third.nextInt();
numFactors(First);
}
}
You can have your program check whether each character it looks at is a digit using Character.isDigit()
http://www.tutorialspoint.com/java/character_isdigit.htm
You probably also want to allow your math operators through, e.g.
if (Character.isDigit(input) || input == '+' ||
input == '-' || input == '/' || input == '*')
{
// Do something with input
}
If that's not what you're looking for, please improve your question to be more specific.
Firstly, you will have to use next() method from the scanner, as nextInt() will return an exception if the next token contains non-digit characters. This will read the token as a String. Then you can get rid of non-digit characters by, for example, creating an empty String (for performance reasons StringBuilder can be better, but that makes it more complex), looping through the original string and using the already mentioned isDigit() method to determine whether the character is a digit. If it is, add it to your new string. Once you have a string containing only digits, use Integer.parseInt(string) method to get the integer value.
I am not quite sure, why you initialise a new Scanner every time, I think you should be able to use the first one throughout your program.
Related
New to programming, so my apologies if this is dumb question.
When utilizing the Scanner class, I fail to see if there is an option for obtaining a single character as input. For example,
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String a = input.nextLine();
}
}
The above code allows me to pull the next line into a string, which can then be validated by using a while or if statement using a.length() != 1 and then stored into a character if needed.
But is there a way to pull a single character instead of utilizing a string and then validating? If not, can someone explain why this is not allowed? I think it may be due to classes or objects vs primitive types, but am unsure.
You can use System.in.read() instead of Scanner
char input = (char) System.in.read();
You can also use Scanner, doing something like:
Scanner scanner = new Scanner(System.in);
char input = scanner.next().charAt(0);
For using Stringinstead of char, you can also to convert to String:
Scanner scanner = new Scanner(System.in);
String input = String.valueOf(input.next().charAt(0));
This is less fancy than other ways, but for a newbie, it'll be easier to understand. On the other hand, I think the problem proposed doesn't need amazing performance.
Set the delimiter so every character is a token:
Scanner input = new Scanner(System.in).useDelimiter("(?<=.)");
String c = input.next(); // one char
The regex (?<=.) is a look behind, which has zero width, that matches after every character.
I have a question based on character arrays. At the moment I have an input variable that takes the first letter of the word.
char input = scanner.nextLine().charAt(0);
What I want to do is for every enter, I want to put it in an array so that I can keep a log of all the letters that have been retrievied. I am assuming this is using char[] but I am having trouble implementing added each input into the array.
char input = scanner.nextLine().charAt(0);
First thing that's unclear is what Object type is scanner?
But for now I'll assume scanner is the Scanner object from Java.util.Scanner
If that's the case scanner.nextLine() actually returns a String.
String has a charAt() method that will allow you to pick out a character anywhere in the string.
However scanner.nextLine() is getting the entire line, not just one word. So really scanner.nextLine().charAt(0) is getting the first character in the line.
scanner.next() will give you the next word in the line.
If the line contained "Hello World"
scanner.next().charAt(0) would return the character 'H'.
the next call of scanner.next().charAt(0) would then return the character 'W'
public static void main(String[] args) {
boolean finished = false;
ArrayList<Character> firstLetters = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
while (!finished) {
firstLetters.add(scanner.next().charAt(0));
}
}
The above code sample might give you the behavior you're looking for.
Please note that the while loop will run forever until finished becomes true.
Your program will have to decide when to set finished to true.
AND here's a couple of links about Java's Scanner class
tutorials point
Java Docs
this is my first time asking a question. If I'm breaking any rules let me know please :)
I want to verify that the user only types in only one character and store in a variable I have already declared initially. As well, loop back the question for user to type in again if they did not do what they are asked for
Here is a what I have done so far
import java.util.Scanner;
public class arraytesting {
public static void main(String[] args) {
Scanner myKeyboard = new Scanner(System.in);
int user_Choice;
int rowAndcolumns;
char[][] user_Array;
char user_Char;
do {
System.out.print("Enter your choice (1 to 9): ");
user_Choice = myKeyboard.nextInt();
if (user_Choice < 1 || user_Choice > 9)
System.out.println("Illegal choice, please try again.");
} while (user_Choice < 1 || user_Choice > 9);
switch (user_Choice) {
case 1:
do {
System.out.print("\nHow many rows and columns (min 4 & max 20)? ");
rowAndcolumns = myKeyboard.nextInt();
if (rowAndcolumns < 1 || rowAndcolumns > 9)
System.out.println("Illegal choice, please try again.");
} while (rowAndcolumns < 4 || rowAndcolumns > 20);
do {
System.out.print("Which character do you want to fill your square with? (only one character)");
user_Char = myKeyboard.next().charAt(0);
if () // error message for user if they did not type correctly, Idk what to put in the
System.out.println("Illegal choice, please try again.");// boolean for it to compare
System.out.print(user_Char);
} while (); // using do-while loop to loop back question, if they don't type in correctly, i
// would only like for user to type in only one character
break;
}
}
}
I know I can put both of them in one do-while loop, but I want to focus on getting the boolean to check for user input.
edit: I would only like the user to enter only one single character
ex. '#' or 'a'
whereas "##" or "i am typing something that is not one character" is wrong
inside the spaces of if and while are how I want it to be verified
There is no need to do any check for "only 1 character entered". That makes no sense. You can't predict the future, so you cannot know if a user will enter more characters after 1 character has been entered. You will either just take the first character entered and work with it and ignore any potential additional characters - or you have to wait for more than 1 character, essentially breaking the program for users who do the right thing (enter only one character), just to be able to give them an error message when they finally do the wrong thing (enter another character).
That being said, this code:
user_Char = myKeyboard.next().charAt(0);
will actually wait for several characters to be entered until some kind of delimiter (per default some whitespace character, e.g. newline) is entered. That's exactly what you do not want.
You want to get one character from input, and one only. You don't have to care about more characters being entered after that:
user_Char = myKeyboard.next(".").charAt(0);
This tells myKeyboard to return the next String that matches the regex ".", which is any character, and only 1 character.
If you want to validate the entered character, e.g. only alphanumeric characters allowed, you can update your if and while to something like this:
if (!Pattern.matches("[a-zA-Z0-9]", new String(user_Char)))
or even better, use the String returned by myKeyboard.next("."):
String user_String = myKeyboard.next(".");
user_Char = user_String.charAt(0);
if (!Pattern.matches("[a-zA-Z0-9]", user_String))
or you could directly tell myKeyboard to only allow valid characters and skip the entire do/if/while error handling:
user_Char = myKeyboard.next("[a-zA-Z0-9]").charAt(0);
Edit
One thing your code doesn't handle right now is invalid inputs, e.g. letters when you call nextInt. This will actually throw a java.util.InputMismatchException, and you might want to wrap your nextInt() and next(...) calls in try-catch blocks to handle these exceptions.
Please check the code below, based on the discussion with Max, I used the .length() method to check the lenght of the string that the user typed.
You can check the type of the character to avoid the runtime exception in the first if statement using some methods in Character class that you use to check if the input is digit/letter or not ?
Character.isDigit(char)
Character.isLetter(char)
Character.isLetterOrDigit(char)
I also changed some variable names, Java is following the camel case style and class name has to be capitalized. I also refactored some code to check the range of the numbers to git rid of repeating same code on and on, check the method betweenExclusive
package stackoverflow.q2;
import java.util.Scanner;
public class Question2 {
public static void main(String[] args) {
Scanner myKeyboard = new Scanner(System.in);
int userChoice;
int rowAndcolumns;
char[][] user_Array;
char userChar;
do {
System.out.print("Enter your choice (1 to 9): ");
userChoice = myKeyboard.nextInt();
if ( !betweenExclusive(userChoice, 1,9) )
System.out.println("Illegal choice, please try again.");
} while (!betweenExclusive(userChoice, 1,9));
switch (userChoice) {
case 1:
do {
System.out.print("\nHow many rows and columns (min 4 & max 20)? ");
rowAndcolumns = myKeyboard.nextInt();
if (!betweenExclusive(rowAndcolumns ,1 , 9))
System.out.println("Illegal choice, please try again.");
} while (!betweenExclusive(rowAndcolumns ,4 , 20));
String input;
while (true){
System.out.print("Which character do you want to fill your square with? (only one character)");
input = myKeyboard.next();
// error message for user if they did not type correctly, Idk what to put in the
// boolean for it to compare
if ( input.length()>1){
System.out.print("Illegal character, try again please !!! ");
}else{
userChar = input.charAt(0);
System.out.print(userChar);
break;
}
} // using do-while loop to loop back question, if they don't type in correctly, i
// would only like for user to type in only one character
break;
}
}
public static boolean betweenExclusive(int x, int min, int max)
{
return x>=min && x<=max;
}
}
Below is the script I have at the moment
import java.util.Arrays;
import java.util.Scanner;
public class SeeWhatTo
{
public static void main(String args[]) {
Scanner scan = new Scanner(System.in); //define scan
int a = scan.nextInt();
int sum =0;
while (a>0 )
{
sum = sum +a;
a = scan.nextInt();
}
System.out.println(sum); //print out the sum
}
}
Currently, it stores an input value in a and then adds it to sum and once a negative or zero is given as an input, it suspends itself and outputs the sum.
I was wondering if there's an integer equivalent of isEmpty so that i can do while (! a.isEmpty() ) so when there's no input but an enter, then it would stop and prints out the sum.
A natural followup from that would be, is there a way to assign an input integer to a and check if it is empty or not at the same time in the while condition as in while ( ! (a=scan.nextInt()).isEmpty() )
Scanner can do 2 things:
Read line-by-line (nextLine).
Read token-by-token (next or e.g. nextInt).
These are really two different functionalities of Scanner, and if you're reading tokens then your Scanner basically doesn't know about empty lines.
If you call nextInt, Scanner does two things:
Finds the next token (default: delimited by any whitespace).
Tries to turn it in to an int.
The tokenizing behavior is an important feature of Scanner. If you enter 1 2\n and call nextInt twice, you get 1 and 2. However, if you enter an empty line, the tokenizing Scanner just skips it as whitespace and keeps looking for another token.
So the straightforward answer is "no": you can never get an "empty" int from a call to nextInt in a simply way and still retain the token-by-token behavior. (That's beyond the fact that a primitive variable in Java can't be "empty".)
One easy way to do what you're asking is to use line-by-line reading instead and call parseInt yourself:
Scanner systemIn = new Scanner(System.in);
int sum = 0;
String line;
while (!(line = systemIn.nextLine()).isEmpty()) {
sum += Integer.parseInt(line);
}
But you lose the tokenizing behavior. Now, if you enter 1 2\n, an exception is thrown because nextLine finds 1 2.
You can still read token-by-token with nextInt, but it's more complicated, using a second Scanner:
Scanner systemIn = new Scanner(System.in);
int sum = 0;
String nextLine;
while (!(nextLine = systemIn.nextLine()).isEmpty()) {
Scanner theInts = new Scanner(nextLine);
while (theInts.hasNextInt()) {
sum += theInts.nextInt();
}
}
Here, we can enter 1 2\n, get 1 2 as our next line, then ask the second Scanner to tokenize it.
So yes, you can program the functionality you're looking for, but not in an easy way, because Scanner is more complicated.
edit
Possibly another way is to use a delimiter on the line separator:
// use System.getProperty("line.separator") in 1.6
Scanner systemIn = new Scanner(System.in).useDelimiter(System.lineSeparator());
int sum = 0;
while (systemIn.hasNextInt()) {
sum += systemIn.nextInt();
}
Now, nextInt tokenizes the same way as nextLine. This will break the loop for any input that's not an int, including empty tokens. (Empty tokens aren't possible with the default delimiter.) I'm never really sure if people actually expect Scanner's default delimiting to work the way it does or not. It's possible creating a Scanner in this way makes it behave closer to what people seem to expect for reading the console, just line-by-line.
There isn't an equivalent in the sense that you describe, since String is a variable-length collection of characters, and having zero characters is still a valid String. One integer cannot contain zero integers, since by definition, it is already an integer.
However, your problem revolves around how Scanner works, rather than how int works.
Take a look at scan.hasNextInt(), which returns true if there is an int to read, and false otherwise. This may give you what you want, using something like:
Scanner scan = new Scanner(System.in);
int sum = 0;
while(scan.hasNextInt())
{
int a = scan.nextInt();
sum = sum + a;
}
System.out.println(sum);
I am working on some data structures in java and I am a little stuck on how to split this string into two integers. Basically the user will enter a string like '1200:10'. I used indexOf to check if there is a : present, but now I need to take the number before the colon and set it to val and set the other number to rad. I think I should be using the substring or parseInt methods, but am unsure. The code below can also be viewed at http://pastebin.com/pJH76QBb
import java.util.Scanner; // Needed for accepting input
public class ProjectOneAndreD
{
public static void main(String[] args)
{
String input1;
char coln = ':';
int val=0, rad=0, answer=0, check1=0;
Scanner keyboard = new Scanner(System.in); //creates new scanner class
do
{
System.out.println("****************************************************");
System.out.println(" This is Project 1. Enjoy! "); //title
System.out.println("****************************************************\n\n");
System.out.println("Enter a number, : and then the radix, followed by the Enter key.");
System.out.println("INPUT EXAMPLE: 160:2 {ENTER} "); //example
System.out.print("INPUT: "); //prompts user input.
input1 = keyboard.nextLine(); //assigns input to string input1
check1=input1.indexOf(coln);
if(check1==-1)
{
System.out.println("I think you forgot the ':'.");
}
else
{
System.out.println("found ':'");
}
}while(check1==-1);
}
}
Substring would work, but I would recommend looking into String.split.
The split command will make an array of Strings, which you can then use parseInt to get the integer value of.
String.split takes a regex string, so you may not want to just throw in any string in it.
Try something like this:
"Your|String".split("\\|");, where | is the character that splits the two portions of the string.
The two backslashes will tell Java you want that exact character, not the regex interpretation of |. This only really matters for some characters, but it's safer.
Source: http://www.rgagnon.com/javadetails/java-0438.html
Hopefully this gets you started.
make this
if(check1==-1)
{
System.out.println("I think you forgot the ':'.");
}
else
{
String numbers [] = input1.split(":"); //if the user enter 1123:2342 this method
//will
// return array of String which contains two elements numbers[0] = "1123" and numbers[1]="2342"
System.out.print("first number = "+ numbers[0]);
System.out.print("Second number = "+ numbers[1]);
}
You knew where : is occurs using indexOf. Let's say string length is n and the : occurred at index i. Then ask for substring(int beginIndex, int endIndex) from 0 to i-1 and i+1 to n-1. Even simpler is to use String::split