Copied this exact code from my book and does not work - java

I copied this exact code from my textbook, and when I try to run it it does nothing but load, the file is in the same location of the java file, and the name is correct. Im using Dr. Java. So im just wondering why it wont run and just keeps loading. The book I am using is Java Illuminated 3rd edition. Also, the newscores.txt file just has 10 numbers, seperated by spaces.
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class TestScoresAndSummaryStatistics {
public static void main(String[] args) throws IOException {
int number;
File inputFile = new File("newscores.txt");
Scanner scan = new Scanner(inputFile);
while (scan.hasNext()); {
number = scan.nextInt();
System.out.println(number);
}
System.out.println("End of file.");
}
}

you have a semicolon end of while statement .you should remove it.because of this semicolon your while loop run repeatedly and your code inside while loop become separate block from the loop.
while (scan.hasNext()); {
number = scan.nextInt();
System.out.println(number);
}
change to
while (scan.hasNext()) {
number = scan.nextInt();
System.out.println(number);
}

Related

How to read float input without knowing size in java?

Sample Input:
9.1 9.0 8.9 8.8 9.4 7.9 8.6 9.8
Here is my code for getting input.
I dont know how to get this type of input without knowing the number of inputs.
import java.io.*;
import java.util.*;
/**
* Diving_Competition
*/
public class Diving_Competition {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
ArrayList<Float> lst = new ArrayList<Float>();
while (in.hasNextFloat()) {
lst.add(in.nextFloat());
}
System.out.print(lst);
in.close();
}
}
This loop runs infinite time. How to get input in a single line without knowing its size?
I'm from python background
As long as there are numerical inputs, your code will not exit the while loop because the condtion in.hasNextFloat() is satisfied.
Assuming you are entering the sample in the terminal: To exit the loop, just enter any non-numerical value like a or enter the EOF-command. In Unix this is Ctrl+D and in Windows it is Ctrl+Z (not sure about Windows-Command)
Haven't java in a bit but I think this works. I read the whole line and separate them.
import java.io.*;
import java.util.*;
/**
* Diving_Competition
*/
public class read {
public static void main(String[] args) throws IOException{
Scanner in = new Scanner(System.in);
String string = in.nextLine();
String[] stringLst = string.split(" ");
ArrayList<Float> numLst = new ArrayList<Float>();
for (String num : stringLst) {
numLst.add(Float.parseFloat(num));
}
System.out.print(numLst);
in.close();
}
}
The best way to figure out such issues is either by debugger OR use console to print helpful information. Your program is perfectly fine, it hangs because it is expecting an input that needs to be entered (unless you want to scan input as program args then its a different question).
Here I made a simple change in your program
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
ArrayList<Float> lst = new ArrayList<Float>();
while (in.hasNextFloat()) {
float x = in.nextFloat();
System.out.println("Number Entered: " + x);
lst.add(x);
}
System.out.print(lst);
in.close();
}
and here is console output
2.3
Number Entered: 2.3
re
[2.3]
Notice how to end the input, I had to enter non-float letters. If I don't enter that, the program will continue to take input from the console, one-by-one.
That being said, from your question it looks like you want to get a line of float input from console. If that the case, then you should read by line and parse it based on "space" character.

Program that returns input \t as *

The code is supposed to read an unidentified number of inputs from the keyboard and return any tabs as *. My program seems to work when I run it in eclipse and get no errors. When I turn in the code on the submission website, this is the error I get.
Exception in thread "main" java.util.NoSuchElementException: No line found at java.util.Scanner.nextLine(Scanner.java:1589) at replaceHW.main(replaceHW.java:9)
import java.util.Scanner;
public class replaceHW {
public static void main(String[] args) {
//write a program that converts all TABS in your code
//with STARS i.e. *
Scanner in = new Scanner(System.in);
String ans;
while(!(ans = in.nextLine()).equals(""))
System.out.println(ans.replace("\t","*"));
}
}
Your problem is simple: nextLine() works in tandem with hasNextLine(): the correct code is:
try (Scanner in = new Scanner(System.in)) {
while (in.hasNextLine()) {
String line = in.nextLine();
if (!"".equals(line)) {
System.out.println(ans.replace("\t","*"));
}
}
The try-with-resources is best practice. But be wary than with System.in, it will close it when done.
hasNextLine() will try to read has much input is needed to find a line.

I am getting a runtime error in this code written in java. Kindly check the mistake ill send the error too

/* package codechef; // don't place package name! */
import java.util.*; import java.lang.*; import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef {
public static void main (String[] args) throws java.lang.Exception {
int x=0,y=0,b,z=0,ctr=0,c;
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in)); String s = buf.readLine();
System.out.println("Enter No. of Test cases");
int a = Integer.parseInt(s);
int arr[] = new int[a];
if(a>=1 && a<=1000)
{
for (x=0;x<=a-1;x--)
{
System.out.println("Enter the cases");
arr[x]=Integer.parseInt(s);
}
}
for(y=0;y<a;y++)
{
if(arr[y]>=1 &&arr[y]<=1000000 )
{
c= arr[y];
b=a*2;
for(z=1;z<a;z++)
{
if(z==1||z==2||z==a)
{
if(b%z==0)
{
ctr++;
}
}
else
{
if(b%z==0)
{
ctr++;
}
}
if(ctr>3)
{
System.out.println("Sorry");
}
else
{
System.out.println("lucky Number");
}
}
}
} }
}
Your code has a few issues. Not sure what you are trying to do with this, but first thing I noticed is that you probably want to put your System.out.println before you read from System.in.
As you have it written, it will wait for the user to enter a number without prompting for it. Move System.out.println("Enter No. of Test cases"); above the BufferedReader buf = new BufferedReader(new InputStreamReader(System.in)); line. That way it will prompt for the number of test cases before reading it from System.in.
The next thing I notice is that your indexing on the first inner for loop is wrong, which is resulting in an ArrayIndexOutOfBounds exception. In your first for loop, on the inner loop you have for(x=0;x<=a-1;x--). You are decrementing your index variable x where you want to increment it. Changing that inner for loop to for(x=0;x<=a-1;x++) will get rid of the ArrayIndexOutOfBounds exception.
As for the rest of your code, I'm not sure what you are trying to do, but it executes without error once you fix the ArrayIndexOutOfBounds exception.

How to take integer and remove other data types from the file java?

I do not know how to take the integer and ignore the strings from the file using scanner. This is what I have so far. I need to know how to read the file token by token. Yes, this is a homework problem. Thank you so much.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ClientMergeAndSort{
public static void main(String[] args){
int length = 13;
try{
Scanner input = new Scanner(System.in);
System.out.print("Enter the file name with extention : ");
File file = new File(input.nextLine());
input = new Scanner(file);
while (!input.hasNextInt()) {
input.next();
}
int[] arraylist = new int[length];
for(int i =0; i < length; i++){
length++;
arraylist[i] = input.nextInt();
System.out.print(arraylist[i] + " ");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Take a look at the API for what you're doing.
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextInt()
Specifically, Scanner.hasNextInt().
"Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input."
So, your code:
while (!input.hasNextInt()) {
input.next();
}
That's going to look and see if input hasNextInt().
So if the next token - one character - is an int, it's false, and skips that loop.
If the next token isn't an int, it goes into the loop... and iterates to the next character.
That's going to either:
- find the first number in the input, and stop.
- go to the end of the input, not find any numbers, and probably hits an IllegalStateException when you try to keep going.
Write down in words what you want to do here.
Use the API docs to figure out how the hell to tell the computer that. :) Get one bit at a time right; this has several different parts, and the first one doesn't work yet.
Example: just get it to read a file, and display each line first. That lets you do debugging; it lets you build one thing at a time, and once you know that thing works, you build one more part on it.
Read the file first. Then display it as you read it, so you know it works.
Then worry about if it has numbers or not.
A easy way to do this is read all the data from file in a way that you prefer (line by line for example) and if you need to take tokens, you can use split function (String.split see Java doc) or StringTokenizer for each line of String that you are reading using a loop, in order to create tokens with a specific delimiter (a space for example) so now you have the tokens and you can do something that you need with them, hope you can resolve, if you have question you can ask.
Have a nice programming.
import static java.nio.file.Files.readAllBytes;
import static java.nio.file.Paths.get;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String args[]) throws IOException {
String newStr=new String(readAllBytes(get("data.txt")));
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(newStr);
while (m.find()) {
System.out.println("- "+m.group());
}
}
}
This code fill read the file and then using the regular expression you can get only Integer values.
Note: This code works in Java 8
I Think This will work for you requirement.
Before reading the data from the file initially,try to write some content to the file by using scanner and filewriter then try to execute the below code snippet.
File file = new File(your filepath);
List<Integer> list = new ArrayList<Integer>();
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String str =null;
while(true) {
str = bufferedReader.readLine();
if(str!=null) {
System.out.println(str);
char[] chars = str.toCharArray();
String finalInt = "";
for(int i=0;i<chars.length;i++) {
if(Character.isDigit(chars[i])) {
finalInt=finalInt+chars[i];
}
}
list.add(Integer.parseInt(finalInt));
System.out.println(list.size());
System.out.println(list);
} else {
break;
}
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
The final println statement will display all the integer in your file line by line.
Thanks

How to stop printing input at 42?

I'm doing a problem on a website where it inputs the numbers:
1
2
88
42
99
and it's supposed to output
1
2
88
The code is supposed to stop printing the input when it hits 42, and it works, but when I submit it to the site, it tells me that it gave the wrong answer.
Here's my code:
http://pastebin.com/y5e8DyHz
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner scan = new Scanner(System.in);
int res;
for(int i=0;i <5; i++) {
res = scan.nextInt();
if (res!=42) {
System.out.println(res);
} else {
System.exit(0);
}
}
}
}
It works when I run it in IDEOne, so I'm not sure what the problem is. Thanks!
Note that a solution to the TEST problem is available in the SPOJ forums. It's a good example of how to process input as fast as possible in java.
Based on your requirement, you have to use it like shown below, even in your IDE
Scanner scan = new Scanner(System.in);
int res;
while (scan.hasNext()) {
res = scan.nextInt();
if (res != 42) {
System.out.println(res);
} else {
System.exit(0);
}
}
Reason being what #jrbeverly mentioned above as his comment
update 1:
If you meant "stop printing the input" as the program must exit on encountering '42',you are good. But if your requirement is just to discard printing the number, and let the program run and accept the next number, then remove System.exit(0) . because System.exit(0) means to terminate the JVM from further execution of the program
update 2:
As #Giovanni Botta mentioned below, the exact solution is provided in the mentioned link, snippet adding here
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
java.io.BufferedReader r = new java.io.BufferedReader (new java.io.InputStreamReader (System.in));
String s;
while (!(s=r.readLine()).startsWith("42")) System.out.println(s);
}
}

Categories

Resources