In Java's Scanner class, why does the syntax nextChar() not exist, and is there a command would do something similar with out using the String variable?
Two solutions:
use toCharArray(): this will return a char[] over which you can use a foreach loop;
use the string length in combination with .charAt().
Java's Scanner class operates on tokens, complete units of output. This is usually complete words, lines of text, numbers (integers, doubles, floats, etc). If you want to read individual characters, you should use BufferedReader in a construct like this
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Replacing System.in with whatever input you're using for Scanner. Then use char c = (char)in.read() to read the next character from the input.
If you want char level access you can go a level below and simply use the InputStream interface :
public class Test
{
public static void main(String[] args) throws Exception
{
while (true)
{
char c = (char)System.in.read();
System.out.println("[" + c + "]");
}
}
}
Scanner s = new Scanner(System.in);
s.next(“.{1,}”);
So, you can use Scanner#next() method and pass regular expression which consumes only one char as a parameter.
You can use an example above.
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 scanner with many lines of text(representing number) and I want to convert all the text in the scanner to a List.
Example:
Scanner myScanner = new Scanner(new File("input.txt"));
input.txt:
000110100110
010101110111
111100101011
101101001101
011011111110
011100011001
110010011100
000001011100
101110100110
010001011100
011111001010
100111100101
111111000010
My first thought was to convert it to a String by changing the delimiter to something I know is not in the file:
myScanner.useDelimiter("impossible String");
String content = myScanner.next();
and then use
List<String> fullInput = Arrays.asList(content.split("\n"));
However, it gives me problems later on with parsing the numbers on the scanner. I've tried debugging it but I can't seem to understand the problem. For example, I made it print the String to the console before parsing it. It would print a proper number(asString) and then give me NumberFormatException when it is supposed to parse.
Here's the runnable code:
public static void main(String[] args) throws FileNotFoundException {
Scanner myScanner = new Scanner(new File("input.txt"));
myScanner.useDelimiter("impossible String");
String content = myScanner.next();
List<String> fullInput = Arrays.asList(content.split("\n"));
System.out.println(fullInput.get(1));
System.out.println(Long.parseLong(fullInput.get(1)));
}
This is what I ended up using after the first didn't work:
Scanner myScanner = new Scanner(new File("input.txt"));
List<String> fullInput = new ArrayList<>();
while (sc.hasNextLine())
fullInput.add(myScanner.nextLine());
Do you know what's wrong with the first method or is there a better way to do this?
Because you are parsing a string that represents a number that's beyond the size of an integer.
int values can be between -2,147,483,648 to 2,147,483,647.
fullInput.get(1) gives you 010101110111 which is greater than 2,147,483,647.
You can use long.
long val = Long.parseLong(fullInput.get(1));
If the string represents binary numbers and you want to convert them to int, then you need to provide the base when parsing the string.
int val = Integer.parseInt(fullInput.get(1), 2);
For what you are trying to do here, Scanner is the wrong solution.
If your goal is to simply read the all lines of the file as String[] you can use the Files.readAllLines(Path, Charset) method (javadoc) to do this. You could then wrap that as a List using Arrays.asList(...).
What you are actually doing could work under some circumstances. But one possible problem is that String.split("\n") only works on systems where the line terminator is a single NL character. On Windows, the line terminator is a CR NL sequence. And in that case, String.split("\n") will leave a CR at the end of all but the last string / line. That would be sufficient to cause Long.parseLong(...) to throw a NumberFormatException. (The parseXxx methods do not tolerate extraneous characters such as whitespace in the argument.)
A possible solution to the extraneous whitespace problem is to trim the string; e.g.
System.out.println(Long.parseLong(fullInput.get(1).trim()));
The trim() method (javadoc) returns a string with any leading and/or trailing whitespace removed.
But there is another way to deal with this. If you don't care whether each number in the input file is on a separate line, you could do something like this:
Scanner myScanner = new Scanner(new File("input.txt"));
List<Long> numbers = new ArrayList<>();
while (myScanner.hasNextLong()) {
numbers.append(myScanner.nextLong());
}
Finally, #ChengThao makes a valid point. It looks like these are binary numbers. If they are in fact binary, then it makes more sense to parse them using Long.parseLong(string, radix) with a radix value of 2. However if you parse them as decimal using parseLong (as you are currently doing) the values in your question will fit into a long type.
I'm doing a java project on codeZinger where I need to take in a character value from the scanner and print the ASCII value. So far the code I have works for everything besides the "/n" character. In that case, codezinger returns the error "Exception in thread "main" java.lang.NullPointerException scanner".
I have attached my code below, I've tried everything and it won't work. I'm new to java from c++.
I tried even manually testing for /n using an if statement and that didn't work
public class Solution {
public static void main(String[] args) {
//creating input stream
Scanner input = new Scanner(System.in);
// allows character input from input stream
char charIn = input.findInLine(".").charAt(0);
if(input.equals("\\n"))
{
System.out.print("10");
}
// casts character to type int to get ascii value
int intVal = (int)charIn;
System.out.print(intVal);
}
}
input.equals() method in java never takes its parameter in apostrophe.
Please go through this once :
https://www.jquery-az.com/learn-java-equals-method-5-examples/
Moreover /n doesn't exist in java. If you have to print a line(Give a break) then you have to use System.out.println() , simply, and it will be printed in next line.
Also go through this for printing ASCII value
https://www.javatpoint.com/how-to-print-ascii-value-in-java
int code;
while ((code = System.in.read()) != -1) {
System.out.format("0x%02X ", code);
}
I need to parse an input-line character by character, and this will be done through several methods. To do it char by char, I am using useDelimiter(""). My question is: do i need to set this delimiter in every method? Or is it enough once, at the beginning?
e.g.
void start() {
Scanner in = new Scanner(System.in);
in.useDelimiter("");
char first = in.next();
readSecond(in);
...
}
void readSecond(Scanner in) {
//in.useDelimiter(""); <-- is this needed?
char second = in.next();
...
}
Example input: A5c*vd
Thanks !
You wouldn't have to set it every time if you declare and initialize the Scanner object in the class body that the methods are in. If you initialize the Scanner in each method, then I think you would have to set the delimiter in each method body.
Once set, the delimiter stays the same.
Therefore, you do not need to set it again to the same value.
package cornett1;
import java.util.Scanner;
public class CodeRat {
public static boolean makes10(int a , int b)
{
return (a + b == 10 || a == 10 || b == 10);
}
public static void main (String[] args) {
Scanner s = new Scanner(System.in);
System.out.print(makes10(s.nextInt(),s.nextInt());
}
}
I am using a website called codingbat to do programming exercises and I solved the question
"Given 2 ints, a and b, return true if one of them is 10 or if their sum is 10." How can I apply this program and Input actual numbers.
Write a main method in the class, and pass in two numbers when invoking the program.
In the main method, Use
int a = Integer.parseInt(argument 0);
int b = Integer.parseInt(argument 1);
Now create a new instance of JOption class and invoke the method 'makes10' in the method with the arguments.
JOption opt = new JOption();
boolean answer = opt.makes10(a, b);
System.out.println(answer);
One of the easiest option you have is
java.util.Scanner
Defention: A simple text scanner which can parse primitive types and strings
using regular expressions.
A Scanner breaks its input into tokens
using a delimiter pattern, which by default matches whitespace.
The resulting tokens may then be converted into values of different types
using the various next methods.
Why using Scanner API?
1. A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
2. A scanning operation may block waiting for input.
3 .A Scanner is not safe for multithreaded use without external synchronization.
For example:
Scanner input = new Scanner(System.in);
int i = sc.nextInt();
System.out.println("the number you entered is " + i);
Explanation:
you read from console and feed scanner variable which is input and you just want to read int. at the end, you print the read number on the console
Resources
first one
second one
Another option is using BufferedReader API
Reads text from a character-input stream, buffering characters so as
to provide for the efficient reading of characters, arrays, and lines.
The buffer size may be specified, or the default size may be used. The
default is large enough for most purposes.
take a look at this sample for your BufferReader need
BufferReader vs Scanner
BufferedReader has significantly larger buffer memory than Scanner. Use BufferedReader if you want to get long strings from a stream, and use Scanner if you want to parse specific type of token from a stream.
Scanner can use tokenize using custom delimiter and parse the stream into primitive types of data, while BufferedReader can only read and store String.
BufferedReader is synchronous while Scanner is not. Use BufferedReader if you're working with multiple threads.
In your case:
int a = 0;
int b = 0;
Scanner input = new Scanner(System.in);
System.out.println("Please enter two numbers");
a = input.nextInt();
b = input.nextInt();
JOption jp = new JOption();
jp.makes10(a, b);
}
public boolean makes10(int a, int b) {
return ((a + b) == 10 || a == 10 || b == 10);
}
Read up on this:
http://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html
This tells you how to take arguments form the command line and use those as variables in your program.
public static void main (String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
System.out.print(makes10(a,b));
}
If you want input at runtime, you can use the Scanner class or the Console class
Scanner s = new Scanner(System.in);
System.out.print(makes10(s.nextInt(),s.nextInt()));
You can use a Scanner to get input from a user :
Scanner sc = new Scanner(System.in);
System.out.println(makes10(sc.nextInt(),sc.nextInt()));