I got error from my code,
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.print("a = ");
int a=in.read();
System.out.print("b = ");
int b=in.read();
System.out.print(" = "+a);
System.out.print("b = "+b);
i try to input 1,
and i dont understand why the result like this?
a = 1
b = = 49b = 13
Where is the second input going?
You can try something like this:
a = in.readLine();
System.out.print("b = ");
String b=in.readLine();
int aInt = Integer.valueOf(a);
int bInt = Integer.valueOf(a);
System.out.print("a = "+aInt);
System.out.print("b = "+bInt);
read() reads character by character, so newline will be counted as new character. To read more about it you can read here.
Related
Seeing the code.
When I start the program, it doesn't let me insert the scanner class input into the switch, how come?
Scanner in = new Scanner(System.in);
System.out.println("select:");
int select = in.nextInt();
switch (select) {
case 1:
System.out.println("first name:");
String n = in.nextLine();
System.out.println("surname:");
String s = in.nextLine();
System.out.println(n + s);
break;
}
Output:
select:
1
first name:
surname:
The nextLine method is ignored because there is a newline character left in the nextInt method. There are two ways to fix this problem.
Solution 1:
Scanner in = new Scanner(System.in);
System.out.println("select:");
int select = in.nextInt();
in.nextLine();
Solution 2:
Scanner in = new Scanner(System.in);
System.out.println("select:");
int select = Integer.parseInt(in.nextLine());
Replacing Scanner with BufferedReader and InputStreamReader could fix it, try:
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.println("select:");
int select = Integer.parseInt(input.readLine());
switch (select) {
case 1:
System.out.println("first name:");
String n = Integer.parseInt(input.readLine());
System.out.println("surname:");
String s = Integer.parseInt(input.readLine());
System.out.println(n + s);
break;
}
I'm working on a java assignment and was stuck on this part. Basically we are to get the user to input three positive non-zero integers using the scanner.
It's supposed to look something like this
Enter three integer values: 2 2 10
The numbers (2, 2, 10) cannot form a triangle.
I was wondering how can I code it so that entering the "2 2 10" could be read as three different integers that are separated by a comma. Thank you very much in advance.
Read the input with java.util.Scanner and a for loop:
Scanner sc = new Scanner(System.in);
int[] values = new int[3];
for (int i = 0; sc.hasNextInt() && i < 3; i++) {
values[i] = sc.nextInt();
}
Try this:
Scanner scan = new Scanner(System.in);
String line = scan.nextLine();
String[] inValues = line.split(" ");
int[] values = new int[inValues.length];
for(int i = 0; i < inValues.length; i++){
values[i] = Integer.parseInt(inValues[i]);
}
scanner.nextInt is your answer
final BufferedReader input = new BufferedReader(
new InputStreamReader(System.in));
// enter yours 2 2 10 and press Enter
final String line = input.readLine();
final Scanner s = new Scanner(line);
int a = s.nextInt(); // reads 2
int b = s.nextInt(); // reads 2
int c = s.nextInt(); // reads 10
if (a + b > c || a + c > b || b + c > a ) {
System.out.println(
"No triangle can be composed from " + a + ", " + b + ", " + c );
}
You can make it as follows:
String sentence = scanner.nextLine();
And you can make:
String[] splittedByComma = sentence.split(",");
Or by space:
String[] splittedBySpace = sentence.split(" ");
Or an array list like the following example:
How to split a comma-separated string?
Then parse each of them to integers.
I used BufferedReader to read data from the user, but it gives NumberFormat Exception prvovided I give the input in a certain way. Suppose in C, I write the code like this:
scanf("%d %d", &x, &y);
and i try to give the input to the console like this : 23 45, it assigns values like this:
x = 23, y = 45
How can I do something like this in java. I tried like this :
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
BufferedReader br2 = new BufferedReader(new InputStreamReader(System.in));
String line1 = br1.readLine();
String line2 = br2.readLine();
int x = Integer.parseInt(line1);
int y = Integer.parseInt(line2);
But this gives:
Exception in thread "main" java.lang.NumberFormatException: For input
string: "23 45" at
java.lang.NumberFormatException.forInputString(Unknown Source) at
java.lang.Integer.parseInt(Unknown Source) at
java.lang.Integer.parseInt(Unknown Source) at AB.main(AB.java:23)
readLine() reads until there is a newline, usually meaning that the user pressed enter.
If you input 12 34, this is one line, a line that isn't formatted like an integer.
You can either read a single char at a time by using read() instead, split the line manually and parse the results, or preferably use the Scanner class instead. It has a more user-IO oriented api, exposing methods such as nextInt() or next() (returning the next "token" instead of the next char) and so on.
Scanner in = new Scanner(System.in);
int x = in.nextInt();
int y = in.nextInt();
If you really want to pass both parameters on the same line, split the line on the white spaces, then use each token separately :
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
String line1 = br1.readLine();
String[] tokens = line1.split("\\s+")
int x = Integer.parseInt(tokens[0]);
int y = Integer.parseInt(tokens[1]);
Now here we are - many, many answers just explaining how to read correct input. But you'll get NumberFormatExceptions any other odd way. Like if your input would be...
98765432109876543210 9876543210987654321
This would in turn throw NumberFormatException as these are too large to fit into int.
So while splitting at " " and addressing tokens manually is good advice, you'd also run into ArrayIndexOutOfBounds if for instance only one number was given.
My recommendation would be to check if the input looks valid before you do any further parsing:
Scanner s = new Scanner(System.in);
String line = s.nextLine();
Pattern p = Pattern.compile("(\\d{1,10})\\s+(\\d{1,10})");
Matcher m = p.matcher(line);
if(m.matches()) {
long x1 = Long.parseLong(m.group(1));
long y1 = Long.parseLong(m.group(2));
if(x1 <= Integer.MAX_VALUE&& y1 <= Integer.MAX_VALUE) {
int x = (int)x1;
int y = (int)y1;
System.out.printf("Your input: %d / %d", x, y);
} else {
System.err.println("Numbers too big");
}
} else {
System.err.println("Input does not match criteria");
}
One InputStreamReader is enough:
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
String line1 = br1.readLine();
String[] args = line1.split(" ");
if (args.length != 2) {
throw new IllegalArgumentException("The input is wrong");
}
int x = getIntFromInput(args[0]);
int y = getIntFromInput(args[1]);
and as Jan pointed out you will need a convertion method:
public static int getIntFromInput(String inputString) {
//sanity checks
if (inputString == null || inputString.trim().length() == 0) {
throw new IllegalArgumentException("empty or null string passed");
}
try {
return new BigInteger(inputString, 10).intValueExact();
} catch (Exception ignored) {
throw new IllegalArgumentException(String.format("input string is not a valid integer number: '%s'", inputString));
}
}
This will solve your purpose
int x, y;
String[] input;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
input = str.split(" ");
x = Integer.parseInt(input[0]);
y = Integer.parseInt(input[1]);
You have to do something like that:
String in = *getline*;
String[] tab = in.split(' ');
List<int> nums = new ArrayList<int>();
for(String a : tab){
nums.add(Integer.parseInt(a)); // or push() not remember...
}
// Your nums have your integers now
You can read data from file and split string based upon 1 or more space and can handle multiple inputs separated by space.
Scanner s = new Scanner(System.in);
String line = s.nextLine();
//String line = "98765432109876543210 9876543210987654321 ";
String[] splited = line.split("\\s+");
Then compare each string to check whether it is valid number.
Then create a new BigDecimal from that number. A BigDecimal on 64bit jvm with with memory permitting can hold upto 646456993 digits.
for (int i=0;i<splited.length;i++) {
if(splited[i].matches("[0-9]*")){
BigDecimal num = new BigDecimal(splited[i]);
System.out.println("num "+(i+1)+"="+num);
}
}
Results
line ="98765432109876543210 9876543210987654321 "
num 1=98765432109876543210
num 2=9876543210987654321
line ="1212312312312312312312313 123432432432432423432423432"
num 1=1212312312312312312312313
num 2=123432432432432423432423432
I have problem with this class (sorry for really messy code).
After while(scan.hasNextLine()) code is done with loop , nothing happens. Code just freezes. Java doesn't report any error , but it should continue running.
Class is implementation of server which collects messages with Rock, Paper or Scissors from socket , randomly makes it's own decisions and sends it back to client.
while (keepRunning == true) {
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
StringBuffer stringBuffer = new StringBuffer();
String line = null;
Scanner scan = new Scanner(br);
while (scan.hasNextLine()) {
line = scan.nextLine();
stringBuffer.append(line);
stringBuffer.append("\n");
listForServer.add(line);
System.out.println(line);
if (line.contentEquals("SHAPE") == false) {
counter = counter + 1;
}
Random rn = new Random();
int n = 2 - 0 + 1;
int i = rn.nextInt() % n;
int randomNum = 0 + i;
if (randomNum == 0) {
shape = "Rock";
randServerList.add(shape);
} else if (randomNum == 1) {
shape = "Paper";
randServerList.add(shape);
} else {
shape = "Scissors";
randServerList.add(shape);
}
}
scan.close();
System.out.println("Shapes are chosen");
System.out.println("Client has send " + (counter - 1) + "shapes");
}
From the java docs of hasNextLine()
Returns true if there is another line in the input of this scanner. This method may block while waiting for input. The scanner does not advance past any input.
Since you have line = scan.nextLine() in the loop it and you scan is open it will continue to wait for the input. Hence the code blocked and you don't see any output.
I'm basically new to this programming stuff. There is a part of the code that I couldn't understand and don't know how to do. Probably what our instructor didn't discuss. What I want to happen is that when I input "Y", it would retry the whole program. If I input "N", it would exit. Here is the code
import java.io.*;
import javax.swing.JOptionPane;
public class Doge {
public static void main(String[] args)
{
int start = 0;
int end = 0;
int step = 0;
String input = "";
BufferedReader in = new BufferedReader (
new InputStreamReader (System.in));
try
{
System.out.println("Input starting number: ");
input = in.readLine();
start = Integer.parseInt(input);
System.out.println("Input ending number: ");
input = in.readLine();
end = Integer.parseInt(input);
System.out.println("Input step number: ");
input = in.readLine();
step = Integer.parseInt(input);
}
catch (IOException e)
{
System.out.println("Error");
}
System.out.println("");
if (start>=end)
{
System.out.println("Starting number should be lesser than the ending number.");
}
while (start<=end)
{
System.out.println(start);
start = start+step;
}
String result = "";
char y = 'Y';
char n = 'N';
BufferedReader it = new BufferedReader (
new InputStreamReader(System.in));
try
{
System.out.print("Do you want to retry (Y/N)? ");
result = it.readLine();
}
catch(IOException e)
{
System.out.println("Error");
}
start = 0;
end = 0;
step = 0;
input = "";
BufferedReader in2 = new BufferedReader (
new InputStreamReader (System.in));
while ("y".equals(result))
{
try
{
System.out.println("Input starting number: ");
input = in2.readLine();
start = Integer.parseInt(input);
System.out.println("Input ending number: ");
input = in2.readLine();
end = Integer.parseInt(input);
System.out.println("Input step number: ");
input = in2.readLine();
step = Integer.parseInt(input);
}
catch (IOException e)
{
System.out.println("Error");
}
System.out.println("");
while (start<=end)
{
System.out.println(start);
start = start+step;
}
}
if ("n".equals(result))
System.exit(0);
}
}
I'm quite confused. I was thinking of writing the same codes but the input starting number line loops after placing a value for the step number.
Understand do..while loop in Java....here
Problems I found in your code
BufferedReader no reuse
Your retry result only check once but not everytime it finsh one loop of process
String compare with "y" but not the char y = 'Y'; you defined. char y = 'Y'; should be String y = "Y"; (The comparison with .equals() is case-sensitive. So if you want include 'y' into your consideration, you can use .equalsIgnoreCase()
{ and } not pairing well to display statement in same scope (ease reading)
I rewrite your code, hope can help you understand more
import java.io.*;
import javax.swing.JOptionPane;
public class Doge {
public static void main(String[] args)
{
int start = 0;
int end = 0;
int step = 0;
String input = "";
String result = "";
boolean invalidInput = false;
//String y = "Y";
//String n = "N";
//reuse same BufferedReader
BufferedReader in2 = new BufferedReader (
new InputStreamReader (System.in));
//use do while to have statement run once then only check retry
do
{
try
{
do
{
System.out.println("Input starting number: ");
input = in2.readLine();
start = Integer.parseInt(input);
System.out.println("Input ending number: ");
input = in2.readLine();
end = Integer.parseInt(input);
if (start >= end)
{
System.out.println("Starting number should be lesser than the ending number.");
invalidInput = true;
}
else
invalidInput = false;
} while (invalidInput); //loop as long as the start >= end
System.out.println("Input step number: ");
input = in2.readLine();
step = Integer.parseInt(input);
}
catch (IOException e)
{
System.out.println("Error");
}
System.out.println("");
while (start<=end)
{
System.out.println(start);
start = start+step;
}
try
{
System.out.print("Do you want to retry (Y/N)? ");
result = in2.readLine();
//it will exit if answer is "N" or "n"
//check whether result is String n (ignore case)
//if (n.equalsIgnoreCase(result))
//only accept "n"
if ("n".equals(result))
System.exit(0);
}
catch(IOException e)
{
System.out.println("Error");
}
//} while (y.equalsIgnoreCase(result)); //loop if "y" or "Y"
} while ("y".equals(result));
//if here have other process, then your result that is neither 'Y' nor 'N' will run here
}
}
After run, I only know .equals() and .equalsIgnoreCase() can only be used on String but not char