How can i use EOF in java (whitout using file) - java

In C i do this:
int main(){
int N = 0;
while(scanf("%d",&N) != EOF){ // <--- how to do this condition in java?
... Code ...
}
My input is some numbers: 10 20 5 9 7 6... and when i hit enter my output is some matrix.
Print with example
I know there is another topic, here, similar to this, but not solve my problem.
Any suggestion?
My problem is solved by Elliot, i just do this:
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
int N = 0;
#SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
while(scanner.hasNextLine()){
N = (int) scanner.nextDouble();
... code ...
}
}
Working fine.

Related

What does the reset() method of Scanner do?

I have a simple Java program using java.util.Scanner as follows:
package com.company;
import java.io.IOException;
import java.util.Scanner;
public class Favorite_Number {
public static void main(String[] args) throws IOException {
int X,sum = 0,rem = 0,t;
Scanner s = new Scanner(System.in);
t = s.nextInt();
while(t!=0) {
s.reset(); // <-- what does it do?
X = s.nextInt();
while (X > 0) {
rem = X % 10;
if (rem == 5) {
sum++;
}
X = X / 10;
}
System.out.println(sum);
sum = 0;
t--;
}
}
}
What does s.reset() do? If I remove it, the program still works fine.
reset() is explained here with examples
and as per documents purpose stated as:
On resetting a scanner discards all of its explicit state information which may have been changed by invocations of useDelimiter(java.util.regex.Pattern), useLocale(java.util.Locale), or useRadix(int).
Docs reference:
https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#reset--

Reading a .dat file into an array in Java

The code that I'm writing has two classes: writeInts and readInts. I wrote writeInts to randomly generate 100 numbers between 0 and 1000 and output them to a data.dat file.
readInts is supposed to open a DataInputStream object and read in the "raw" data from the data.dat file and store the 100 integers in an array. My problem is that I can't seem to read the data correctly. Any help with this would be greatly appreciated. Thanks!
writeInts:
import java.io.*;
public class WriteInts {
public static void main(String[] args) throws IOException {
DataOutputStream output = new DataOutputStream(new FileOutputStream("data.dat"));
int num = 0 + (int)(Math.random());
int[] counts = new int[100];
for(int i=0; i<100; i++) {
output.writeInt(num);
counts[i] += num;
System.out.println(num);
}
output.close();
}
}
readInts:
import java.io.*;
import java.util.*;
public class ReadInts {
public static void main(String[] args) throws IOException {
// call the file to read
Scanner scanner = new Scanner(new File("data.dat"));
int[] data = new int[100];
int i = 0;
while (scanner.hasNextInt()) {
data[i++] = scanner.nextInt();
System.out.println(data[i]);
scanner.close();
}
}
}
If you want to write binary data, use DataInputStream/DataOutputStream. Scanner is for text data and you can't mix it.
WriteInts:
import java.io.*;
public class WriteInts {
public static void main(String[] args) throws IOException {
DataOutputStream output = new DataOutputStream(new FileOutputStream(
"data.dat"));
for (int i = 0; i < 100; i++) {
output.writeInt(i);
System.out.println(i);
}
output.close();
}
}
ReadInts:
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class ReadInts {
public static void main(String[] args) throws IOException {
DataInputStream input = new DataInputStream(new FileInputStream(
"data.dat"));
while (input.available() > 0) {
int x = input.readInt();
System.out.println(x);
}
input.close();
}
}
More. If you want to generate a random number in range from 0 to 1000 (both inclusive), you use this statement:
int rndNum = (int) (Math.random() * 1001);
It works that way: Math.random() generates a double in range from 0 to 1 (exclusive), which you then should map to integer range and floor. If you want you maximal value to be 1000, you multiply it by 1001 - 1001 itself is excluded.
Yep, like that:
import java.io.*;
public class WriteRandomInts {
public static void main(String[] args) throws IOException {
DataOutputStream output = new DataOutputStream(new FileOutputStream(
"data.dat"));
for (int i = 0; i < 100; i++) {
int rndNum = (int) (Math.random() * 1001);
output.writeInt(rndNum);
System.out.println(rndNum);
}
output.close();
}
}
I'd recommend that you abandon DataInputStream and DataOutputStream.
Write the ints one to a line using FileWriter and read them using a BufferedReader, one per line. This is an easy problem.

.hasNext() wont turn false

I have the following code and I cannot understand why .hasNext() wont turn false. I am reading from a file called test.
My code:
package printing;
import java.io.File;
import java.util.Scanner;
public class Printer {
public int count() throws Exception{
int num = 0;
File f = new File("C:\\Users\\bob\\Desktop\\test.txt");
Scanner in = new Scanner(f);
while (in.hasNext()){
num++;
}
return num;
}
}
Main:
public class Main {
public static void main(String[] args) throws Exception{
Printer mine = new Printer();
System.out.println(mine.count());
}
}
File content:
4
4
6
3
8
8
8
What is wrong?
You need to consume the input from the Scanner
while (in.hasNext()){
in.next();
num++;
}
You didn't consume any of the input. hasNext() doesn't consume any input.
The scanner does not advance past any input.
Add a call to next() inside the while loop to consume the input.

Inputting sets of numbers in java - Null pointer exception

import java.util.Scanner;
import java.lang.Integer;
public class points{
private class Vertex{
public int xcoord,ycoord;
public Vertex right,left;
}
public points(){
Scanner input = new Scanner(System.in);
int no_of_pts = Integer.parseInt(input.nextLine());
Vertex[] polygon = new Vertex[no_of_pts];
for(int i=0;i<no_of_pts;i++){
String line = input.nextLine();
String[] check = line.split(" ");
polygon[i].xcoord = Integer.parseInt(check[0]);
polygon[i].ycoord = Integer.parseInt(check[1]);
}
}
public static void main(String[] args){
new points();
}
}
This is a very simple program in which I want to input n number of points into the system with their x and y co-ordinates
Sample Input :
3
1 2
3 4
5 6
However after entering "1 2" it throws a NullPointerException . I used Java debug to find the troubling line is
polygon[i].xcoord = Integer.parseInt(check[0]);
However the check variable correctly shows '1' and '2' . Whats going wrong ?
EDIT :
Thanks to the answers, I realized I had to initialize each element of the array to a new object using
polygon[i] = new Vertex();
Because the Vertex reference in the array is null.
import java.util.Scanner;
import java.lang.Integer;
public class points{
private class Vertex{
public int xcoord,ycoord;
public Vertex right,left;
}
public points(){
Scanner input = new Scanner(System.in);
int no_of_pts = Integer.parseInt(input.nextLine());
Vertex[] polygon = new Vertex[no_of_pts];
for(int i=0;i<no_of_pts;i++){
String line = input.nextLine();
String[] check = line.split(" ");
polygon[i] = new Vertex(); // this is what you need.
polygon[i].xcoord = Integer.parseInt(check[0]);
polygon[i].ycoord = Integer.parseInt(check[1]);
}
}
public static void main(String[] args){
new points();
}
}
polygon[i] is null as it has not been initialised

Exception in thread main error [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Causes of 'java.lang.NoSuchMethodError: main Exception in thread “main”'
I'm hoping this is just a simple error here, I've looked up numerous other instantces of people getting the same error message but none of their solutions really seem to apply for me. I was just wondering if you guys could help me find the error in my code. I'm not even sure if it's functional because I can't get it to run, so I suppose it could be a logic error.
When I try to run the following cold I am met with fatal exception error occured. Program will exit.
Eclipse also gives me:
java.lang.NoSuchMethodError: main
Exception in thread "main"
Thank you very much for any assistance you can offer!
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class JoPuzzle
{
public static Integer main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of soliders");
int soldiers = input.nextInt();
System.out.println("Please enter the how many soldiers are skipped before the next death");
int count = input.nextInt();
List<Integer> soldiersList = new ArrayList<Integer>(soldiers);
for (int i = 1; i <= count; i++) {
soldiersList.add(i);
}
int currentIndex = 0;
while(soldiersList.size() > 1) {
currentIndex = (currentIndex - 1 + count) % soldiersList.size();
soldiersList.remove(currentIndex);
}
return soldiersList.get(0);
} //end main
}//end class
We know that to execute any java Program we should have a main function. because this is a self callable by JVM.
And the signature of the function must be..
public static void main(String[] args){
}
but in your code it's seem like this...
public static Integer main(String[] args){
}
so its consider as a different function , so change your main return type..
The signature for main method is
public static void main(String[] args).
When you run your program the JVM will look for this method to execute. You need to have this method in your code
Your program does not contain the main method, change it to
public static void main(String[] args)
If you want to return an Integer object, then define a custom mehod and call that method inside the main method and handle that returned value.
Java main() function doesn't have a return-statement. This line
public static Integer main(String[] args)
should be
public static void main(String [] args)
Also since it has no return value, you should delete the return statement.
Java's main method should have below signature.
public static void main(String[] args){
..
..
}
Try to run this code and tell if it works.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class JoPuzzle
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of soliders");
int soldiers = input.nextInt();
System.out.println("Please enter the how many soldiers are skipped before the next death");
int count = input.nextInt();
List<Integer> soldiersList = new ArrayList<Integer>(soldiers);
for (int i = 1; i <= count; i++) {
soldiersList.add(i);
}
int currentIndex = 0;
while(soldiersList.size() > 1) {
currentIndex = (currentIndex - 1 + count) % soldiersList.size();
soldiersList.remove(currentIndex);
}
// return soldiersList.get(0);
System.out.println(soldiersList.get(0));
} //end main
}//end class

Categories

Resources