Java File IO scan into variables - java

this is basically my first true Java assignment and I've hit a brick wall. I basically wrote my entire project as if the user were to input the information into the program. upon rereading the assignment I saw that we are to input the info from a .txt file in the following format:
1.17 12 15( and then sort them)
7 54 9873 1867 4425 878 365 783 (where the first number n indicates how many n will folow)
4 (flyods triangle problem)
20 (fizz buzz problem)
I have all of the code written to solve these parts of the project but am completely stuck on how to implement the numbers from the .txt file. I am not asking for code merely some advice on how you guys might go about doing so/
import java.util.Arrays;
import java.util.Scanner;
public class FunTime {
public static void main(String args[])
{
int n, num = 1, c, d;
Scanner in = new Scanner(System.in);
n = in.nextInt();
for ( c = 1 ; c <= n ; c++ )
{
for ( d = 1 ; d <= c ; d++ )
{
System.out.print(num+" ");
num++;
}
System.out.println();
}

Fortunately, reading from a file is exactly like reading from the terminal. Instead of reading from System.in, read from a file that you open with something like FileInputStream.

Related

how to get the final output without pressing enter?

In the below code when i enter the input as***(i just don't enter the input one by one instead i copy and paste the entire input)***
4
101
1111
00110
111111
i am supposed to get
5
15
6
63
instead i get
5
15
6
and after i press enter here
i get the 63
import java.util.Scanner;
public class VonNeumanLovesBinary {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int no = scn.nextInt();
while (no > 0)
{
int binary = scn.nextInt();
int i = 0 ;
int sum = 0;
while(binary > 0 )
{
int digit = binary % 10;
sum += Math.pow(2,i) * digit ;
binary /= 10;
i++;
}
System.out.println(sum);
no--;
}
}
}
This code is written Intellij IDE.
Please help me out . this is the problem of the ide ?
Its not the fault of the IDE. It is how it deals with copy-pasting text into the console.
The text is handed over to the Java code as you paste it, line by line. Input is only handed over once you finish the line. The previous lines are all terminated already with a newline symbol but the last line is not.
So you have to either add a newline to the end of your copy-pasta or hit enter to produce one yourself. So before you terminate the last line, the last line is never handed over to Java but is still only in the console.
For example, if you copy pasta this instead:
4
101
1111
00110
111111
(note the last, empty line)
it will work as expected, since you finished the 111111 line, i.e. it is 111111\n and not just 111111.

How to add a variable to another variable that's already set

My homework is to create a program that takes a list of numbers and prints out the highest number divisible by four.
List would look like this:
12
16
87
58
25
73
86
36
79
40
12
89
32
Input should be:
40 because it is the highest number there divisible by four.
Here is my code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int saved = 0;
int saved2 = 0;
for (int i = scanner.nextInt(); i % 4 == 0; i = scanner.nextInt()) {
for (boolean bull = true; bull == true; bull ^= true) {
if (i > saved) {
saved -= saved2;
saved += i;
saved2 += i;
}
}
System.out.println(saved);
}
}
}
The input of my code is
12
16
I don't really understand why this is doing it, but it seems to me that I'm adding the variables wrong. The homework page on adding variables does not specify how to add variables to each other.
Does anyone have a tip to improve the code in anyway, or find a way to make a fix my code? Thank you.
welcome to Java.
First you are saying you got input, but that is output. Input is what you enter, and output is what you get printed.
Then there is a mistake in your for loops. You have too much going on in one place. By the logic which is implemented, your program will exit first level for loop whenever your entered value is not divisable by 4.
Read on for loops if you want to learn more https://www.learnjavaonline.org/en/Loops.
I recommend to start from while loops instead. The logic whould be this:
1. create variable to hold the correct answer saved
2. create another one to hold the value read from console i
3. start the while loop with condition i = scanner.nextInt()
3.1 check if the value just entered i is divisable by 4
3.2 if it is, then compare if it's larger than the one was saved before (initially saved value will be 0)
3.3 if it is larger, then assign the read value i to the saved
4. At the end of the loop, you will have the highest number divisable by four in your saved variable. Print it.
I will provide some help, according to
How do I ask and answer homework questions?
for (int i = scanner.nextInt(); i % 4 == 0;i = scanner.nextInt())
This only reads as long as ALL inputs are divisible by 4, that is why it ends at 16, because 87 is not divisible by 4.
for (boolean bull = true; bull == true ;bull ^= true)
This needs explanation by you, but I am pretty sure that it unconditionally executes the body of the inner loop exactly once. (Not 100% sure, because the representation of true and false could be weird in your machine. Should 0 be the representation of true, i.e. really weird, then it is an endless loop, which does not match the output you describe...)
System.out.println(saved);
This executes exactly once per input, except the last one, which is not a multiple of 4.
The value of saved is identical to input, as long as it is increasing.
These hints explain the unexpected output.
If you inspect the details of what the problem is, you should be able to improve your coding attempt.
This is how I super-quickly fixed in your code.
Note that there are no statements about the possible minimum value and about how do you stop the input. Therefore the solution is pretty-straightforward, it just reads the input until integers are present there.
This article may be useful about handling the input from the Scanner.
I hope the comments in the code will help. Add comments if there are any questions. Good luck!
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int currentMax = Integer.MIN_VALUE; // you may set negative or 0 if you know that all the input is positive
// int saved2 = 0; // no need for this variable
while (scanner.hasNextInt()) { // you can make a better input handling, especially if you know when it should end the input. Now it will end on any non-integer input line
int i = scanner.nextInt();
// for (int i = scanner.nextInt(); i % 4 == 0; i = scanner.nextInt()) {
// for (boolean bull = true; bull == true; bull ^= true) {
if (((i % 4) == 0) && (i > currentMax)) {
currentMax = i;
// saved -= saved2;
// saved += i;
// saved2 += i;
// }
}
}
System.out.println(currentMax); // moved out of "for" or "while" cycles. Print the value after the input has ended.
}
}

Java- Saving score in a game

I'm having problems tyring to keep score in my "guessing" game. I have to use a for loop or while loop. I have it so 10 random numbers are created in a text file called mystery.txt and a file reader reads these numbers from the text file.
Your score starts at 0. If the user guesses the correct number from the text file they get -10 points. If they get the number wrong they add the the absolute value difference of the number they guessed from a number in the file. The lower the score in the end the better.
When I only run my if else statement once, it works correctly. Once I loop it more than once it starts to act up.
I have to use an if else statement and a for or while loop. Thanks!
Edit- Turns out I have to use a for loop not a while loop, I'm completely lost now.
How it should work:
When you run the program a text file gets generated with 10 different numbers (I already have the code for that ready) The user gets asked to enter a number, the number the user enters gets compared to the first file on the text file. If it is the same never they get -10 points to their score. If they get it wrong they get the difference of the number the guessed and the number in the text file added to the score. This is suppose to repeat ten times.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.Random;
import java.lang.Math;
public class lab4Fall15 {
public static void numberGuessingGame() throws IOException {
Scanner myscnr = new Scanner (System.in);
PrintWriter mywriter = new PrintWriter("mysteryNumber.txt");
int randomNumber;
int i = 0;
i=1;
while (i<=10) {
Random randomGen = new Random();
randomNumber= randomGen.nextInt(11);
// then store (write) it in the file
mywriter.println(randomNumber);
i = i + 1;
}
//Decided to use a loop to generate the numbers-------
mywriter.close();
FileReader fr = new FileReader("./mysteryNumber.txt");
BufferedReader textReader = new BufferedReader(fr);
int numberInFile;
// the number in your file is as follows:
numberInFile = Integer.valueOf(textReader.readLine());
int score= 0;
int a = 1;
while (a<=10) {
a=a+1;
System.out.print ("Please enter a number between 0 and 10: ");
int userNumber= myscnr.nextInt();
if (userNumber==numberInFile){
score = score-10;
}
else{
score = score + Math.abs(userNumber-numberInFile);
}
System.out.println ("current score is: "+score);
}
System.out.println ("your score is "+score);
textReader.close();
}
public static void main(String[] args) throws IOException {
// ...
numberGuessingGame();
}
}
if (userNumber==numberInFile){
score = score-10;
}
I don't understand what you going to mean. but I can guess this. your above code not show any error. normally , you check your , above part of code. you take variable 'numberInFile'. sometime , your file reader take this with 'whitespace or String or e.t.c' . first you check this out put .you put manual data to this variable and check out put. if it work fine , you correct that function.
OK, first, let's just go over for loops, since that's what your question was asking about. From the code you provided, it seems that you already understand while loops, and that's good, because in Java, for loops are (usually) just while loops in disguise. In general, if you have this while loop,
int a = 0;
while (a < 10) {
// do stuff with a
a = a + 1; // or ++a or a++
}
You can always rewrite it like this:
for (int a = 0; a < 10; a = a + 1) {
// do stuff with a
}
By convention (and this convention is useful when you study arrays and Collection types) you'll want to index your loops from 0 rather than 1. Since you're just learning, take my word for it for now. Loop from 0 to n-1, not from 1 to n.
With that out of the way, let's tackle why you're getting the wrong answer (which, incidentally, has nothing at all to do with loops). Rewritten as a for loop, the ask-and-score part of your program looks like this.
for (int a = 0; a < 10; ++a) {
System.out.print ("Please enter a number between 0 and 10: ");
int userNumber = myscnr.nextInt();
if (userNumber == numberInFile){
score = score - 10;
} else {
score = score + Math.abs(userNumber - numberInFile);
}
System.out.println ("current score is: "+score);
}
You will note that nowhere in this section do you update the value of numberInFile. That means that every run of this loop is still looking at whatever value that variable had at the beginning of the loop. That value came from this line:
// the number in your file is as follows:
numberInFile = Integer.valueOf(textReader.readLine());
That line is executed exactly once, before the loop runs. If you want to load the next number every time the user guesses a number, you'll need to move it inside the loop. I'll leave that as an exercise to the reader.
You are not actually capturing the number the user is entering. Try this:
int userNumber = Integer.parseInt(KeyIn.readLine());

NZEC runtime error for 2 testcases out of 3 in Java

I am trying to solve a question on Hackerearth. The competition had ended long time back.
http://www.hackerearth.com/lenskart-hiring-challenge/algorithm/big-p-and-punishment-5/description/
The Problem Statement
Big P has become a Physical Education teacher at Hack International School.
Today, the students of class XII have been very indisciplined and he decides to punish them all.
He makes all of the N student (numbered 1 to N ) to stand in a line and asks them to sit down on their knees.
Students know that Big P is a very cruel and sadistic person and students start to sit down themselves when they see a friend sit down.
However, there are always some students who do not follow the trend. Now when Big P sees that happen , he slaps that student and makes him sit down. The same process as above is followed and is stopped when any - one student in the line refuses to sit down by himself.
Given the students that Big P slaps to make them sit down , you need to tell the total no. of students who sat down in that line.
Note: It is not necessary that if A is friend of B then B is also friend of A.
Input Format :
First Line Contains an integer T denoting no of test cases. Each test case begins with a line containing three integers N, F, S where N is the number of students in the line . Next F lines have two integers A and B denoting the friendship between the students A and B. Next S lines have one integer X denoting the student that was slapped by Big P .
Output Format:
For each test case, output a line containing one integer, the total number of students that sit down in that line.
[ T<=10 , N ,F , S <=10000 ]
Sample Input
1
3 2 1
1 2
2 3
2
Sample Output
2
I have written a Java Code for the same.
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Arrays;
#SuppressWarnings("unchecked")
class Graph
{
static int visited[];
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int testcases;
int N,F,S,n;
int a,b;
testcases=Integer.parseInt(br.readLine());
while(--testcases>=0)
{
String[] s = br.readLine().split(" ");
N=Integer.parseInt(s[0]);
F=n=Integer.parseInt(s[1]);
S=Integer.parseInt(s[2]);
visited=new int[N+1];
Arrays.fill(visited,0);
ArrayList[] adj=new ArrayList[N+1];
while(--n>=0)
{
s = br.readLine().split(" ");
a=Integer.parseInt(s[0]);
b=Integer.parseInt(s[1]);
if(adj[a]==null){
adj[a]=new ArrayList<Integer>();
}
(adj[a]).add(b);
}
int root;
for(int i=1;i<=S;i++)
{
root=Integer.parseInt(br.readLine());
dfs(adj,root);
}
int ans=0;
for(int i=1;i<=N;i++)
{
if(visited[i]==1){
++ans;
}
}
System.out.println(ans);
}
}
static void dfs(ArrayList adj[],int r)
{
int curr;
if(visited[r]!=1)
{
ArrayList base=adj[r];
if(base!=null)
{
Iterator itr=base.iterator();
while(itr.hasNext())
{
curr=(int)itr.next();
if(visited[curr]==0)
{
dfs(adj,curr);
}
}
}
visited[r]=1;
//System.out.println(r);
}
}
}
It passes for the 1st testcase,but gives an NZEC error for the remaining testcases.
I tried making changes like :
Used Scanner instead of Stream Reader.
Removing static arrays
None of these is helping.
Please help me out in identifying the fault.

SPOJ ADDREV Problem

I did go through the other threads on this SPOJ problem, ADDREV (Adding Reversed Numbers), but sadly, I was not able to get an answer by any of the three programs that I have written (in C, Python and Java). I am attaching the code snippets of all three.
Python:
def find_rev(a):
d=0
while(a>=1):
d=d*10+a%10
a=a/10
return d
n=input('enter a number')
for i in range(int(n)):
num1=input('enter the first number')
num2=input('enter the second number')
num=0
num1=find_rev(int(num1))
num2=find_rev(int(num2))
num=num1+num2
num=find_rev(num)
print num
With Python, I get a runtime error.
With C, I get a wrong answer.
#include<stdio.h>
long rev(long);
int main()
{
long int n;
long int n1;
long int n2;
long int i=0;
scanf("%ld",&n);
//printf("%d",n);
for (i=0;i<n;i++)
{
//printf("\n%d",i);
//printf("\nenter the two numbers");
scanf("%ld%ld",&n1,&n2);
n = rev(rev(n1)+rev(n2));
printf("%ld\n",n);
}
return 0;
}
long rev(long a)
{
long d=0;
while(a>=1)
{
d = d*10+a%10;
a = a/10;
}
return d;
}
With Java, I get a compilation error.
import java.util.*;
//import java.io.*;
public class spoj_prob {
public static void main(String args[])
{
long n=0;
System.out.println("enter a number \n");
Scanner in=new Scanner(System.in);
n=in.nextLong();
long n1=0;
long n2=0;
long sum=0;
for (int i=0; i<n; i++)
{
System.out.println("enter two numbers \n ");
n1=in.nextLong();
n2=in.nextLong();
n1=rev(n1);
n2=rev(n2);
System.out.println(n1);
System.out.println(n2);
sum=rev(n1+n2);
System.out.println(sum);
}
}
static long rev(long a)
{
long d=0;
while (a>=1)
{
d=d*10+a%10;
a=a/10;
}
return d;
}
}
}
Of course, those errors are reported by the SPOJ Judge. The programs work fine on my system. Test cases I use are:
2
999999999 11
999 11
Answer
101
101
Also
3
34 54
123 091
00034 00054
Update: Guys, I got the answer in C. Thank you for all the help.
Before you start using any service, it's generally a good thing to read its FAQ. It explains how exactly the program should receive data.
In particular, please notice that printing enter a number and other junk to the console will always lead to a wrong answer. Because a correct program would output something like
34
1998
1
and yours
enter a number
enter two numbers
34
enter two numbers
1998
enter two numbers
1
I can't tell why Java fails to compile, though. You probably should find some information on how to submit in Java with the reference solution.
Also, the problem definition gives no limit for input numbers, so they can possibly be too big for standard integer types in Java and C++.
With Python I think you're getting Runtime Error because you're calling a restricted function input, nothing else comes to mind.
In C you're getting WA because the input integers can be very large, and you're overflowing.
For JAVA there are 2 potential problems that you may have. One is that you're using Scanner class which may not be supported by SPOJ (due to security or other considerations). Second, is that your class name needs to be Main I think. Please search SPOJ forum for more details on this.
Try this solution in Python 3:
import sys
t = int(input())
i=0
while i<t:
a,b = map(int,sys.stdin.readline().split()) #to take both inputs in single line
c=str(a) #converting the number into string
d=str(b)
e=int(c[::-1]) #converting reverse of the string c to int
f=int(d[::-1]) #converting reverse of the string d to int
s=e+f #adding the two reverse numbers
s1=str(s)
s2=int(s1[::-1]) #reverse s and display it
print(s2)
i+=1

Categories

Resources