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.
Related
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.
I'm trying to get the integers I enter to be written to a text file, yet however I edit the code my notepad spits out my integers as nonsense. Example:
Integer inputted: java.util.Scanner[delimiters=\p{javaWhitespace}+][position=1][match valid=true][need input=false][source closed=false][skipped=false]...
I believe my problem is in the line which I have marked with a "*". How would I go about fixing this? I believe it has something to do with the "String.valueOf(input)" line. Full code linked below!
for (int i = 0 ; i < 10 ; i++) {
System.out.printf("Please enter integer %d: ", i+1);
numbers[i] = input.nextInt();
{
try
{
*output.format("Integer inputted: %s%n", String.valueOf(input));
}
catch (FormatterClosedException formatterClosedexception)
{
System.err.println("Error writing to the file. Terminating.");
break;
}
catch (NoSuchElementException elementException)
{
System.err.println("Invalid input. Please try again.");
input.nextLine();
}
http://pastebin.com/yV6dhSMt
You can use this to write in to a file:
PrintWriter writer = new PrintWriter(fileName);
writer.println("1");
writer.println("2");
writer.close();
And this to read from that file:
String line, newLine; // Variable to store a line and to check for a new line
String[] splited; // Variable to split text
int lines = 0; // Variable to check how many lines in a file
Scanner myReader = new Scanner(new File(fileName));
BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName));
Numbers[] numbers = new numbers[2];
while ((line = bufferedReader.readLine()) != null) {
lines++;
for (int i = 1 ; i < 2 ; i++) {
while (myReader.hasNextLine()) {
newLine = myReader.nextLine();
splited = newLine.split(",");
numbers[i] = Integer.parseInt(splited[i]);
}
}
}
myReader.close();
I just wrote this here, but from what I remember this is how I did it.
I try to add only even numbers to ArrayList. I work with file using scanner as the most proper tool in my opinion. Path to the file should be written in console. Also I use 2 the most popular ways to define even numbers.
The problem is - not only even numbers are adding to my ArrayList.
There is my code:
BufferedReader bfReader = new BufferedReader(new InputStreamReader(System.in));
InputStream inputStream = null;
List<Integer> myInts = new ArrayList<Integer>();
String filePath = null;
try {
filePath = bfReader.readLine();
inputStream = new FileInputStream(filePath);
} catch (IOException e) { }
Scanner scanner = new Scanner(inputStream);
while (scanner.hasNext()) {
if ((scanner.nextInt() % 2) == 0 && scanner.nextInt() != 1)
myInts.add(scanner.nextInt());
// if ((scanner.nextInt() & 1) == 0)
// myInts.add(scanner.nextInt());
}
for (Integer x : myInts) {
System.out.println(x);
}
I suppose I misunderstand something about Scanner.
Would be glad to receive any answers!
The reason is that every new call of nextInt() read new integer from input.
Here is a modified code snippet that illustrates what you might want to try:
Scanner scanner = new Scanner(inputStream);
int myInt;
while (scanner.hasNext()) {
myInt = scanner.nextInt();
if ((myInt % 2) == 0 && myInt != 1)
myInts.add(myInt);
}
For more information look at the docs.
Every time you call nextInt, it takes an item out of the scanner. That means that one pass through your loop removes as many as three items, and the items being added are not the same as the ones you're doing your checks on.
Imagine your input is 4 3 1
Your code will do this:
if ((scanner.nextInt() /* 4 */ % 2) == 0 && scanner.nextInt() /* 3 */ != 1)
myInts.add(scanner.nextInt() /* 1 */);
And add 1 to your list.
You should change your code to this:
while (scanner.hasNext())
{
int value = scanner.nextInt();
if ((value % 2) == 0)
myInts.add(value);
}
This will only read a single value, and use it in all comparisons.
The problem here lies in
if ((scanner.nextInt() % 2) == 0 && scanner.nextInt() != 1)
Every time you call scanner.nextInt(), you consume the next input. Because of this, you end up discarding most of the input. To fix this, you would need to have something like
while (scanner.hasNext())
{
int i = scanner.nextInt;
if ((i % 2) == 0 && i != 1)
myInts.add(i);
}
This will properly consume the input and should work properly.
The scanner javadoc, which contains this information, is found here: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Yes I think you have understood it wrong. Whenever you use nextInt() method of the scanner class pointer which scanning file will move to the nextInt(). So it is better to save that integer values in temporary variable. Below is the modification of your code,
BufferedReader bfReader = new BufferedReader(new InputStreamReader(System.in));
InputStream inputStream = null;
List<Integer> myInts = new ArrayList<Integer>();
String filePath = null;
try
{
filePath = bfReader.readLine();
inputStream = new FileInputStream(filePath);
}
catch (IOException e)
{
}
Scanner scanner = new Scanner(inputStream);
while (scanner.hasNext())
{
int firstNumber = scanner.nextInt();
if ((firstNumber % 2) == 0 && firstNumber != 1)
myInts.add(firstNumber);
//if ((scanner.nextInt() & 1) == 0)
// myInts.add(scanner.nextInt());
}
for (Integer x : myInts)
{
System.out.println(x);
}
Every time you call scanner.nextInt() you get another number. If you want to refer to the same number multiple times, assign to a variable.
Also, having checked that a number is even, you don't also have to check that it isn't the number 1.
while (scanner.hasNext()) {
int n = scanner.nextInt();
if (n%2 == 0) {
myInts.add(n);
}
}
In the line
if ((scanner.nextInt() % 2) == 0 && scanner.nextInt() != 1)
You are reading two integers from the input, instead of checking the same one twice:
int nextInt = scanner.nextInt();
if ((nextInt % 2) == 0 && nextInt != 1)
So I am trying to create a loop that accepts number "0 - 10". If it is less than "0" than the loop exits and the program prints out all the numbers and the number of times each was entered. So Lets say you enter values like 1 2 3 4 5 1 It will print out something like Number:1 Times Entered:2 then next line will print out Number:2 Times Entered:1. If it goes higher than 10 I will just give them an input error. If someone can just help me out creating the correct variables and format I think I can take it from there. Here is what I have thus far... I know it's not correct but this is the idea I am trying to do.
import java.io.*;
public class test {
public static void main(String[] args) throws IOException{
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(reader);
String str;
Integer[] numbers = new Integer[1000]
int count = 0;
str = input.readLine();
while(str != null){
numbers[count] = Integer.parseInt(str);
// Here I will create some [if else] statements like
if(numbers < 0)
break;
else if(numbers >= 0 || numbers <= 50)
numbers[count]++;
else
System.out.print("You must enter a value less than 51");
} // Close while loop here
System.out.println("Number:" + number + " Times Entered:" + count);
}
}
import java.io.*;
public class Demo {
public static void main(String[] args) throws IOException{
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(reader);
String str;
int i,number;
Integer[] numbers = new Integer[10];
int count = 0;
for(i=0;i<10;i++)
numbers[i]=0;
str = input.readLine();
while(str != null){
number = Integer.parseInt(str);
// Here I will create some [if else] statements like
if(number == 0)
break;
else if(number >= 0 && number <= 10)
numbers[number-1]++;
else
System.out.print("You must enter a value less than 11");
str = input.readLine();
} // Close while loop here
for(i=0;i<10;i++)
System.out.println("Number:" + (i+1) + " Times Entered:" + numbers[i]);
}
}
This should work.And put some efforts form your side so that you can learn
I am trying to check if the word given by the user already exists in the text file or a substring of it already exists. Here's my code:
String ans = null;
Scanner scanner = null;
do
{
System.out.print("Please enter a new word: ");
String Nword = scan.next();
System.out.print("And its appropriate Hint: ");
String Nhint = scan.next();
Word word = new Word(Nword , Nhint);
File file = new File("C:\\Users\\Charbel\\Desktop\\Dictionary.txt");
file.createNewFile();
scanner = new Scanner(file);
if (scanner != null)
{
String line;
while (scanner.hasNext()) {
line = scanner.next();
for(int i = 0 ; i<line.length(); i++)
if ((line.equals(Nword)) || (Nword.equals(line.substring(i))))
{
System.out.println("The word already exists.");
break;
}
}
}
else
{
FileWriter writer = new FileWriter(file , true);
writer.write(word.toString());
writer.write(System.lineSeparator());
writer.flush();
writer.close();
System.out.println("Your word has successfuly added.");
System.out.print("\nWould you like to add another word ?\nPress 0 to continue.");
ans = scan.next();
}
} while(ans.equals("0"));
Eclipse said that the statements after the else condition are "Dead Code" and I don't know why.
scanner = new Scanner(file);
scanner is initialized, can never be null, so the else statement will never be reached.
See the constructor:
Throws: FileNotFoundException - if source is not found
So if the file doesn't exists, scanner won't be null, you'll have an exception.
scanner = new Scanner(file);
This statement is creating a new instance here. So this:
if (scanner != null) will never be false.
Dead-Code is which never gets executed, for example:
if(true) {
// do something
}else {
// do something else <-- this is dead code, or else-block is dead code
}
In your case since Scanner is getting created before if(scanner != null) there is no way of execution of associated else. If Scanner creation fails error will be thrown again in which else will not be executed, hence from compiler point-of-view no chance of else block getting executed hence dead-code.
if-else would have made sense if scanner instance is passed as argument.
To solve this, else should be removed!
Following should correct your code:
scanner = new Scanner(file);
FileWriter writer = new FileWriter(file, true);
if (scanner != null) {
String line;
while (scanner.hasNext()) {
line = scanner.next();
for (int i = 0; i < line.length(); i++)
if ((line.equals(""))
|| ("".equals(line.substring(i)))) {
System.out.println("The word already exists.");
break;
} else {
writer.write(word.toString());
writer.write(System.lineSeparator());
writer.flush();
System.out.println("Your word has successfuly added.");
System.out.print("\nWould you like to add another word ?\nPress 0 to continue.");
ans = scan.next();
}
}
}
writer.close();