I wrote a method that adds 1 to an int called total each time it sees a new word:
public int GetTotal() throws FileNotFoundException{
int total = 0;
Scanner s = new Scanner(new BufferedReader(new FileReader("Particles/Names.txt")));
while(s.hasNext()){
if(s.hasNext()){
total++;
}
}
return total;
}
Is that the right way to write it?
It looks fine. But the inner IF is unnecessary, also the next() method is required. Below should be fine.
public int GetTotal() throws FileNotFoundException{
int total = 0;
Scanner s = new Scanner(new BufferedReader(new FileReader("Particles/Names.txt")));
while(s.hasNext()){
s.next();
total++;
}
return total;
}
The Scanner implements Iterator.You should at least make the iterator step forward, like this:
public int GetTotal() throws FileNotFoundException{
int total = 0;
Scanner s = new Scanner(new BufferedReader(new FileReader("Particles/Names.txt")));
while(s.hasNext()){
s.next();
total++;
}
return total;
}
or the loop will run infinitely.
Use a regular expression to match all non-whitespace. :-)
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ScanWords {
public ScanWords() throws FileNotFoundException {
Scanner scan = new Scanner(new File("path/to/file.txt"));
int wordCount = 0;
while (scan.hasNext("\\S+")) {
scan.next();
wordCount++;
}
System.out.printf("Word Count: %d", wordCount);
}
public static void main(String[] args) throws Exception {
new ScanWords();
}
}
As others have said you have an infinite loop. Also there is a much simpler way to use Scanner.
int total = 0;
Scanner s = new Scanner(new File("/usr/share/dict/words"));
while(s.hasNext()){
s.next();
total++;
}
return total;
Related
My Issue is that this code does not return and values when I call it.
I need to to read a set of values from another txt file and print out the answers.
Then I need to be able to have it print to another empty text file.
The values in the txt file is (without space in-between lines):
1 2 3 4 5 6
4 5 6
7.5 8.5 9
8.1 9.2 10.3
The source code as follows:
public class Lab5d {
public static void main(String args[]) {
// Scan the input
Scanner scan = new Scanner(System.in);
String line = scan.nextLine();
Scanner lineScan = new Scanner(line);
// Process each line separately
// If the next token is a double, assume there is an input line
while (scan.hasNextDouble()) {
processLine(line);
}
}
public static void processLine(String line) {
Scanner scan = new Scanner(System.in);
Scanner lineScan = new Scanner(line);
double a = lineScan.nextDouble();
double sum;
double product;
double count;
double average;
sum = 0;
count = 0;
product = 1;
while (lineScan.hasNext()) {
sum = sum + a;
product = product * a;
++count;
}
double ave = sum / count;
System.out.printf("sum= %.1f, product= %.1f, ave= %.1f, count= %.1f%n", sum, product, ave, count);
}
}
Can anyone help?
You're not reading the file in. Use the file path as a parameter for the Scanner object.
It can be two cases, you can either read values from a file or values from a command line.
First a main method look:
public static void main(String args[]) {
// Scan the input
processSystemIn();
// San the file
processFile("resource/values.txt");
}
The values.txt is following the format you presented in your question.
And read a value line by line using a hasNextLine method of a Scanner class then, use an another scanner instance for the each number from the line input.
case 1: A processSystemIn method with System.in
private static void processSystemIn() {
Scanner scanner = new Scanner(System.in);
String line = null;
while (scanner.hasNextLine()) {
line = scanner.nextLine();
processLine(line);
}
scanner.close();
}
case 2: A processFile method with file.
private static void processFile(String fileName) {
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
String line = null;
while (scanner.hasNextLine()) {
line = scanner.nextLine();
processLine(line);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
The processLine method is a little bit different with yours.
With a hasNextDouble method, you can get a value.
See the method as follows:
public static void processLine(String line) {
Scanner lineScan = new Scanner(line);
double a;;
double sum;
double product;
double count;
double average;
sum = 0;
count = 0;
while(lineScan.hasNextDouble())
{
a = lineScan.nextDouble();
product = 1;
sum += a;
product *= a;
++count;
average = sum / count;
System.out.printf("sum= %.1f, product= %.1f, ave= %.1f, count= %.1f%n", sum, product, average, count);
}
lineScan.close();
}
The result is here:
Does this result meet your expectation?
I hope this helps.
I've just made this simple student program which reads the data and writes into the file.
What I need is if I want to enter 100 data of students how to make it in a list and that should be from user side
For example,
Enter students you want to enter : 2
Name : Satish devnani
Roll No : 1
Name : Sonu
Roll No : 2
And if user enters 100 then it should be 100.
made until this :
import java.util.*;
import java.io.*;
class filesatish2{
String name;
int number;
//int i=0;
public static void main(String args[]) throws IOException {
//int i;
filesatish2 stname= new filesatish2();
Students.READ();
Students.FILEWRITE();
}
int HOWMANY()
{
int count;
Scanner sc=new Scanner(System.in);
printit("How many data you want to enter ?");
count=sc.nextInt();
//printit(""+count);
return count;
}
void READ()
{
Scanner sc=new Scanner(System.in);
Scanner text=new Scanner(System.in);
printit("Name :");
name=text.nextLine();
printit("Number :");
number=sc.nextInt();
}
public static void printit(String a)
{
System.out.print(a);
}
public void FILEWRITE() throws IOException
{
File student = new File("Student.txt");
FileWriter printer = new FileWriter(student);
student.createNewFile();
printer.write(""+name);
printer.write("\t"+number);
printer.flush();
printer.close();
}
}
try the following:
import java.util.*;
import java.io.*;
class filesatish2 {
List studentList = new ArrayList();
String name;
int number;
int count = 0;
public static void main(String args[]) throws IOException {
// int i;
filesatish2 stname = new filesatish2();
stname.count = stname.HOWMANY();
stname.READ();
stname.FILEWRITE();
}
int HOWMANY() {
int count;
Scanner sc = new Scanner(System.in);
printit("How many data you want to enter ?");
count = sc.nextInt();
// printit(""+count);
return count;
}
void READ() {
Scanner sc = new Scanner(System.in);
Scanner text = new Scanner(System.in);
for (int i = 0; i < count; i++) {
printit("Name :");
name = text.nextLine();
printit("Number :");
number = sc.nextInt();
studentList.add(name + "\t" + number + "\n");
}
}
public static void printit(String a) {
System.out.print(a);
}
public void FILEWRITE() throws IOException {
File student = new File("Student.txt");
FileWriter printer = new FileWriter(student);
student.createNewFile();
for (int i = 0; i < count; i++) {
printer.write((String) studentList.get(i));
}
printer.flush();
printer.close();
}
}
Hi guys sorry I'm a newbie to Java, this is one of the exercise in my class.
I supposed to ask user input 5 numbers, then compare them if they are the same number that entered before.
These are my code so far, but I can't get it work.
Thanks.
import java.util.Scanner;
public class Source {
private static int num = 0;
private static int[] enterednum = new int[5];
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
for(int count = 0; count < enterednum.length; count++) {
System.out.println("Enter a number.");
num = input.nextInt();
compare(enterednum);
}
System.out.println("These are the number you have entered: ");
System.out.println(enterednum);
}
public static void compare(int[] enterednum) {
for(int count = 0; count < 6; count++)
if(num == enterednum[count])
System.out.println("The number has been entered before.");
}
}
You may want something like this:
import java.util.Scanner;
public class Source
{
private static int enterednum[]=new int[5];
public static void main(String args[])
{
int num=0; // make this local variable since this need not be class property
Scanner input = new Scanner(System.in);
for(int count=0;count<enterednum.length;count++)
{
System.out.println("Enter a number.");
num = input.nextInt();
compare(num, count);
enterednum[count] = num; // store the input
}
System.out.println("These are the number you have entered: ");
// print numbers in array instead the array
for(int count=0;count<enterednum.length;count++)
{
System.out.println(enterednum[count]);
}
}
// change the method signature to let it get the number of input
public static void compare(int num, int inputcount)
{
for(int count=0;count<inputcount;count++)
{
if(num==enterednum[count])
System.out.println("The number has been entered before.");
}
}
}
You can do this way if you need.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Source {
public static void main(String[] args) throws IOException {
// I used buffered reader because I am familiar with it :)
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// Create a Set to store numbers
Set<Integer> numbers = new HashSet<>();
for (int i = 0; i < 5; i++) {
System.out.print("Enter a number: ");
String line = in.readLine();
int intValue = Integer.parseInt(line);
// You can check you number is in the set or not
if (numbers.contains(intValue)) {
System.out.println("You have entered " + intValue + " before");
} else {
numbers.add(intValue);
}
}
}
}
I am trying to print the returned string value in the main method but I can't figure it out. can someone give me a hand?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String in_word;
int number_input;
Scanner input_word = new Scanner (System.in);
Scanner input_times = new Scanner (System.in);
System.out.println("Enter word: ");
in_word = input_word.next();
System.out.println("Enter number of times to concatenate: ");
number_input = input_times.nextInt();
multiConcat(in_word, number_input);
}
public static String multiConcat(String word, int times) {
//String word;
String s = "";
int number;//times, ;
for (number = 0; number < times; number++)
s = word.concat(s);
return s;
}
}
System.out.println(multiConcat(in_word, number_input));
//I am not able to figure out what is wrong? Please help me. I was able to use the //scanner .I am not able to input the values.Java.Util.NoSuchElementException: No Line //Found.
//String arrayValue = null;
int Rows= boardsize, Columns=boardsize;
int[][] sudokuArray = new int[Rows][Columns];
String[] sudokuTempArray;
String delimiter = "\\,";
#SuppressWarnings("resource")
Scanner userInput = new Scanner(System.in);
for(int i=0;i<Rows;i++ ){
System.out.println("Enter the value of array separated by ',' for row" + i);
while(userInput.hasNext())
{
String arrayValue = userInput.next();
sudokuTempArray = arrayValue.split(delimiter);
if(sudokuTempArray.length == Rows)
{
for (int j = 0;j<Columns;j++)
{
sudokuArray[i][j] = Integer.parseInt(sudokuTempArray[j]);
System.out.println(sudokuArray[i][j]);
}
}
}
/*
else
{
System.out.println("Try again!");
}*/
}
If you have used a scanner previously reading from System.in and have closed that scanner, you will have closed the System.in InputStream.
Have you previously closed a scanner reading from System.in?
Yes this is a common error. Look at my answer to this question.
java - Scanner class NoSuchElementFoundException
He essentially closed the input in another method, which you are likely doing as well.
Search for .close in your code base.
See this:
java - Scanner class NoSuchElementFoundException
import java.util.*;
import java.util.StringTokenizer;
class shift
{
Scanner sc=new Scanner(System.in);
void test(int x)
{
String s=sc.nextLine();
StringTokenizer st=new StringTokenizer(s);
String wen="";
{
while(st.hasMoreTokens())
{
String temp=st.nextToken();
for(int i=1;i<=x;i++)
{
wen=wen+temp+" ";
}
}
System.out.print(wen);
}
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
shift reff=new shift();
if(n<=0)
{
System.out.print("EMPTY");
}
else
{
reff.test(n);
}
}
}
//output : java.util.NoSuchElementException: No line found