Getting infinite loop when reading file from method - java

I am trying to refactor my code, and adding methods where possible. When I read a file from a method and return the result of the computation, the code goes into extreme memory consumption, infinite loop.
My modification looks like this:
import java.util.Scanner;
public class NumberOfLines {
public static int compute () {
// read this file
String theFile = "numbers.txt";
Scanner fileRead = null;
if (NumberOfLines.class.getResourceAsStream(theFile) != null) {
fileRead = new Scanner(NumberOfLines.class.getResourceAsStream(theFile));
}
else {
System.out.print("The file " + theFile + " was not found");
System.exit(0);
}
System.out.println("Checkpoint: I am stuck here");
// count number of lines
int totalLines = 0;
while(fileRead.hasNextInt()) {
totalLines++;
}
fileRead.close();
return totalLines;
}
public static void main (String[] args) {
System.out.println("The total number of lines is: " + compute());
}
}
If instead of writing the method, and placing the code on main, then it works. Why is this?
EDIT
Contents of numbers.txt is:
5
2
7
4
9
1
5
9
69
5
2
5
6
10
23
5
36
5
2
8
9
6
So I expect out put to be:
The total number of lines is: 22

The reason you are getting stuck in an infinite loop is because you are reading the file but not incrementing the scanners token in the while loop. So the while condition is always true.
while (fileRead.hasNextInt()) {
totalLines++;
fileRead.nextInt(); // change made here only
}

Related

Trying to print out some sequence of numbers [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I want to print out a sequence of numbers using this formula
Enter a number
if number is even divide number by 2.
But if number is odd multiply number by 3 and add 1
continue doing this until number becomes 1
sample input=3
Sample output=10 5 16 8 4 2
this is what I tried but still not getting it
package victor;
import java.util.Scanner;
public class proj {
public static void main(String[] args) {
Scanner put=new Scanner(System.in);
int temp=0;
boolean notOne=true;
System.out.println("input::: ");
int num=put.nextInt();
while(temp!=1){
if (num%2==0){
temp=num;
System.out.println(temp/2);
break ;
}
else {
temp=num;
System.out.println(temp*3+1);
break;
}
}
if(temp!=1){
notOne=false;
}
}
}
It's not working because you keep re-assigining the variable temp to the initially scanned num.
You keep checking if the initially scanned num is odd or even, when you should check if temp is odd or even.
You also break out of the loop for no reason.
And finally, you're not saving the result of the operations, you're only printing out the result.
Try to understand the points I mentioned above by noticing the differences between your code and the following:
while(temp!=1){
if (temp%2==0){
temp = temp/2;
}
else {
temp = temp*3+1;
}
System.out.println(temp);
}
You are not updating the value of temp. You are just printing it. Take the following statement
if (num%2==0){
temp=num;
System.out.println(temp/2);
break ;
}
Here you are setting temp to num and just printing temp/2 and never setting a value.
I wrote my version of it which is a bit more simpler. I hope this will help you. You can create a string to get a better output of course.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number:");
int number = scan.nextInt();
while (number != 1) {
number = number % 2 == 0 ? number / 2 : ((number * 3) + 1);
System.out.println("Number became " + number);
}
}
}
Try this:
public class Main
{
public static void main(String[] args) throws Exception
{
System.out.println("Starting...");
//Lets start the program, first we need
//the Scanner class to access to the input
Scanner stdin = new Scanner(System.in);
System.out.print("Type a num: ");
//I dont use: nextInt() because when asking for another input, will scan only
//the rest of the line (Maybe just \n - line break )
int num = Integer.parseInt(stdin.nextLine());
//Optional
int loops = 0;
while(num!=1){
//Pair, so num/2
if ( num %2 == 0){
num/=2;
}
else{
//num*3 +1
num=num*3 +1;
//Note that:
//1 + num*3
//Doesnt alter the result
}
System.out.println("num: "+num);
loops++;
}
System.out.println("total loops: "+loops);
}
}

Multiple values with only one scanner method?

I have an assignment where I need to do certain calculations in separate methods using data entered by the user. My problem is with the user input. It is supposed to be done with a separate method (I do not think I am allowed to use arrays for storing the inputs). The user should be able to enter as many values they want and then exit with "q". The program should then take the first two numbers, calculate e.g. an area and volume with those (with other methods I did not include here), present the result, take the next two numbers the user entered, calculate and present results. This should be repeated until it reaches the "q" value. So for example:
Enter your values: 9 5 3 7 q
radius: 9 height: 5
Area = 254
Volume = 424
radius: 3 height: 7
Area = 28
Volume = 65
A problem I am having is that only the first value is assigned to a variable and then the user has to enter data again for the next variable, even though there's still more numbers left from the first time.
import java.util.Scanner;
public class Stack {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int radie, height;
radie = userInput("");
height = userInput("");
}
public static int userInput(String message) {
int number = Integer.MAX_VALUE;
while (number == Integer.MAX_VALUE) {
System.out.print(message);
if (input.hasNextInt()) {
number = input.nextInt();
}
input.nextLine();
}
return number;
}
}
I understand there are massive flaws in my code here, I'm very lost and not sure where to even start with solving the problem. Any help or tips are very welcome! Thanks in advance!
Did you read 'Scanner.hasNextInt()' method documentation?
There is written:
Returns:
true if and only if this scanner's next token is a valid int value
So question if
number == Integer.MAX_VALUE
doesn't make sens.
Try to ask if hasNextInt()
returns true or false
Edit: Also
Why do you assume that after number is always 'q'?
Change condition in while statement
Don't really understand your mean, but i did some changes:
import java.util.Scanner;
public class stack {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
userInput();
}
public static void userInput() {
while (true) {
System.out.println("Enter your values:");
String message = input.nextLine();
//Split data with space
String[] data = message.split(" ");
int pointer = 2;
for (String i : data) {
if (i.equals("q")) {
System.out.println("Stopped.");
System.exit(0);
}
if (pointer % 2 == 0) {
System.out.println("radius: " + i);
}
if (pointer % 2 == 1) {
System.out.println("height: " + i);
}
pointer++;
}
}
}
}
Affect:
Enter your values:
1 2 3 4 5 6 7 8
radius: 1
height: 2
radius: 3
height: 4
radius: 5
height: 6
radius: 7
height: 8
Enter your values:
1 q
radius: 1
Stopped.
Process finished with exit code 0

Displaying loop in JOptionPane

I'm a beginner in Java programming, and I have an assignment on while loops.
The assignment was to have windows open up with the numbers 1-10 on display.
The first two, I got down. The third one was to have the user enter a number 'x', and the next window was to show all integers between 1 and 'x' using a while loop.
As I have it coded now, each loop iteration pops up in it's own window, instead of all at once, in one window.
TL;DR I want to have 1 window with 10 loops, not 10 windows with 1 loop each.
JOptionPane and while loops were in the handouts and notes he had us take, but no mention of how to combine them.
import javax.swing.JOptionPane;
public class Pr27
{
public static void main(String[] args)
{
JOptionPane.showMessageDialog(null, "1\n2\n3\n4\n5\n6\n7\n8\n9\n10");
JOptionPane.showMessageDialog(null, "1 2 3 4 5 6 7 8 9 10");
String text;
text=JOptionPane.showInputDialog("Please enter a number: ");
int f,x;
f=0;
x=Integer.parseInt(text);
while (f<=x)
{//What am I doing wrong between here
JOptionPane.showMessageDialog(null, f);
f++;
}//and here?
}
}
I believe that you wish to print out all numbers from x that are less than or equal to f in a single DialogBox and not every time the loop iterates.
import javax.swing.JOptionPane;
public class Pr27
{
public static void main(String[] args)
{
JOptionPane.showMessageDialog(null, "1\n2\n3\n4\n5\n6\n7\n8\n9\n10");
JOptionPane.showMessageDialog(null, "1 2 3 4 5 6 7 8 9 10");
String text;
text = JOptionPane.showInputDialog("Please enter a number: ");
int f, x;
//if you wish to loop from 1 to x then f must start at 1 and not 0 because in your loop you print out f before it increases thus it would be 0.
f = 1;
x = Integer.parseInt(text);
StringBuilder sb = new StringBuilder();
while (f <= x)
{
//rather than show a message dialog every iteration append f and a new line to a StringBuilder for later use.
sb.append(f).append("\n");
//JOptionPane.showMessageDialog(null, f);
f++;
}
//string builder has a "\n" at the end so lets get rid of it by getting a substring
String out = sb.substring(0, sb.length() - 1);
JOptionPane.showMessageDialog(null, out);
}
}

Im having trouble getting this txt.file to print 1-100 integers correctly

Im trying to have this code print 1-10 on first line, then 11-20 on the second, 21-30 on the third, etc.
But with the code now Its printing 1-10 on first line, then 10-20 on the second, 20-30 on the third, etc.
Basically I'm stuck here and have been doing trial and error to try and fix it but nothings working.
import java.util.Scanner;
import java.io.*;
public class P4C {
public static void main ( String [] args )throws IOException {
PrintWriter writer = new PrintWriter ( new File ( "Write100Project" )); //creates a PrintWriter object to allow us to create and write to a file.
int integer = 1;
int margin = 1;
int counter = 1;
while ( margin <=100){
if ( margin == 10*counter ){
System.out.println ( integer + " ");
counter+=1;
integer = integer+1;
}
System.out.print ( integer + " " );
integer+=1;
margin++;
}
}
}
When you loop over an array and want to treat certain elements differently there basically are two approaches:
Do something for the special element. Do something else for everything but the special element. In code this means an if-else in your while loop.
Do something generic for every element and do something extra for the special elements.
Which approach to choose depends on the amount of overlap. If the code for the special element is very different from the code for the other elements, use 1. If the code is almost the same, use 2.
You seem to do a hybrid of these, which is why every multiple of 10 is printed twice. Translating your problem two these approaches:
Print the number and a new line for every multiple of 10. Print the number for every other element. Code snippet of the while body (using %, I hope you got is meaning from the other answers):
if (margin % 10 == 0) {
System.out.println(margin + " ");
margin++;
} else {
System.out.print(margin + " ");
margin++;
}
Print the number for every element. Additionally, print a new line for every multiple of 10 (note how I need to reorder your code; you first want to print the multiple of 10, then the new line, then increment margin):
System.out.print(margin + " ");
if(margin % 10 == 0) {
System.out.println();
}
margin++;
Besides, notice how I don't need integer and counter any more?
With this type of thing the modulus % which shows you the remainder. Here you want a new line after every 10 so #MadProgrammer 's (margin % 10 == 0) is saying when the remainder after dividing it by 10 is 0
You can do this all with one variable instead of using three which should make it a bit simpler. The logic is while your number is less than 100, add one to it then print it out. If it is the 10th number in the row print a new line.
import java.util.Scanner;
import java.io.*;
public class P4C {
public static void main ( String [] args )throws IOException {
PrintWriter writer = new PrintWriter ( new File ( "Write100Project" )); //creates a PrintWriter object to allow us to create and write to a file.
int integer = 0;
while ( integer <100){
if ( integer % 10 == 0 ){ //If integer is divisible by 10
System.out.println (); //Time to go onto a new line
}
integer++;
System.out.print ( integer + " " );
}
}
}
The '%' is modulus.
Modulus basically returns the remainder; for example:
5 % 4 = 1;
3 % 2 = 1;
8 % 3 = 2;
10 % 10 = 0;
i++ is the same as saying either;
i = i + 1;
or
i += 1;
import java.util.Scanner;
import java.io.*;
public class IntegerCounting {
public static void main ( String [] args )throws IOException {
PrintWriter writer = new PrintWriter ( new File ( "Write100Project" ));
int i = 0;
while(i < 100){
if(i % 10 == 0 && i != 0){
System.out.println(i++ + "");
}
System.out.print(i++ + " ");
}
}
}
This may help...
int integer = 1;
while(integer<=100){
System.out.print(" "+integer++);
if(integer%10==0){
System.out.println(" "+integer++);
//System.out.println();
}
}

How to count row values from file?

i am trying to read the txt file and add up row values i.e i am passing the parameters to java code. it should print the line numbers of added values
i am passing filename and int value to java program.
for ex: read.txt contains
2
2
3
4
4
6
7
7
8
8
9
0
now i am passing parameter as 5, so it should add up the rows and print the line number and it should print the line number if the sum >= 5
for ex
2+2+3 = 7 is > 5
because the last number added up is 3 and it is in line number 3
so it should print line number 3
4+4 = 8 is > 5
so it should print line number 3
6 is > 5
so it should print line number 6
because its in line number 6
and so on..
how can i do this?
here is what i have tried
code:
import java.io.*;
class CountR
{
public static void main(String args[])
{
setForSum("read.txt",3);
}
public static void setForSum(String filename,int param2)
{
try
{
FileInputStream fstream = new FileInputStream(filename);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
int i = 0;
while ((strLine = br.readLine()) != null)
{
i++;
if(param2 == Integer.parseInt(strLine))
{
System.out.println(i);
}
}
in.close();
}
catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
}
}
First thing I've noticed, is this if statement is only going to work if you land on your specified number, exactly.
if(param2 == Integer.parseInt(strLine))
{
System.out.println(i);
}
Should be:
if(param2 >= Integer.parseInt(strLine))
{
System.out.println(i);
}
Secondly, you're not totalling up the values, are you? You're just reading each value, so declare some value outside of the loop:
int currentTotal = 0;
then in the loop:
currentTotal += Integer.valueOf(strLine);
THEN use currentTotal in your statement:
if(currentTotal >= Integer.parseInt(strLine))
{
System.out.println("Line Number " + i);
}
And as Heuster mentioned, make sure you're resetting currentTotal back to 0 inside your if statement!

Categories