I have been working on a project this past few days. I run in to some weird problems with scanners.
The goal is to run an infinite loop in scanning users input and passing those input as a parameter for a method.
What I know is that the code works if the items are defined explicitly without the use of scanners as per the code below:
import java.util.Scanner;
public class TrackerConsole {
public static void main(String args[]) {
int i = 0;
Scanner scanInput = new Scanner(System.in);
LifestyleTracker app = new LifestyleTracker();
do {
System.out.println("Enter a command");
String userInput = scanInput.next();
if (userInput.contains("food")) {
System.out.println(app.addFood("pasta", 2000));
}
else if (userInput.contains("eat")) {
System.out.println(app.eat("pasta", 20));
}
else if (userInput.contains("report")) {
System.out.println(app.report());
}
i++;
} while (i < 10);
}
}
But here's the weird part when I add scanners inside the if statement like the code below:
import java.util.Scanner;
public class TrackerConsole {
public static void main(String args[]) {
int i = 0;
Scanner scanInput = new Scanner(System.in);
LifestyleTracker app = new LifestyleTracker();
do {
System.out.println("Enter a command");
String userInput = scanInput.next();
if (userInput.contains("food")) {
System.out.println("Add new food?");
String getFood = scanInput.next();
System.out.println("How many calories");
double getCalories = scanInput.nextDouble();
System.out.println(app.addFood(getFood, getCalories));
}
else if (userInput.contains("eat")) {
System.out.println(app.eat("pasta", 20));
}
else if (userInput.contains("report")) {
System.out.println(app.report());
}
i++;
} while (i < 10);
}
}
Notice when I called the command 'eat' it throws me an error saying that its not in the collections while before that I called 'food' which says 'food is added successfully'. It seems that my method call is not saved when the loop resets. This is the out put of calling the same items in the terminal:
I hope someone can help me with this
I need a lit help here. So I want my first method to read the file "./data/textfiles/zahlen01.txt" (there are some numbers i want to add together, this works). And I want my second method to do the same but with a string in the method. So how do i name the method in the main method?
public static double countSumOf(Scanner in) {
PrintWriter out = new PrintWriter(System.out);
double sum = 0;
while (in.hasNext()) {
double b = in.nextDouble();
sum = sum + b;
}
out.println(sum);
out.flush();
return sum;
}
public static double countSumOf(String filename) {
DirtyFileReader dfr = new DirtyFileReader(filename);
Scanner in = new Scanner(dfr);
return countSumOf(in);
}
public static void main(String[] args) {
Locale.setDefault(Locale.US);
PrintWriter out= new PrintWriter (System.out);
DirtyFileReader dfr = new DirtyFileReader("./data/textfiles/zahlen01.txt");
Scanner in = new Scanner(dfr);
countSumOf(in);
countSumOf();
out.flush();
}
Not sure I correctly understand so I rephrase:
You want to sum up some numbers, once using a file as source that contains the numbers and once using a java string that contains the numbers?
I found this interesting piece of code:
https://github.com/alquesh/PR1PRAXIS/blob/master/PR1PRAXIS/src/pr1/a04/FirstInput.java
To sum it up: Scanner can take a String as an argument to the constructor to scan that string instead so where you have Scanner in = new Scanner(dfr); you can instead use Scanner in = new Scanner(meineZeichenkette);
SOLVED
I'm having an issue using Scanners nextInt() method in a class constructor.
it works fine if used in a main method like the code below however when doing the same thing in a constructor I get an inputmismatchexception,
what could be the possible issues?
public class QuickTest{
public static void main(String[] args) throws Exception{
java.io.File myFile = new java.io.File("tograph.txt");
java.util.Scanner input = new java.util.Scanner(myFile);
int numberOfPoints = input.nextInt();
String[] myArray = new String[numberOfPoints];
//need to use nextLine once after reading in number of points to get to next line
input.nextLine();
int count = 0;
while(input.hasNext() == true){
myArray[count] = input.nextLine();
count++;
}
input.close();
for(int i = 0; i < myArray.length; i++){
System.out.println(myArray[i]);
}
the class version
public class MyGraph{
//filled with strings from file
String[] points;
java.io.File file;
java.util.Scanner input;
//length of points array
int numPoints;
public MyGraph(String file){
this.file = new java.io.File(file);
this.input = new java.util.Scanner(file);
this.numPoints = this.input.nextInt();
this.points = new String[this.numPoints];
fillGraphArray();
}
//after getting the number of vertices we populate the array with every
//line after those points untill the end
private void fillGraphArray(){
//used once after reading nextInt()
this.input.nextLine();
int count = 0;
while(this.input.hasNext() == true){
points[count] = input.nextLine();
count++;
}
input.close();
}
//test method to be delted later
public String[] getPoints(){
return this.points;
}
//may need a method to close the file
}
When I use the debugger the main method version will get the number of points from the file and then fill the array with a string from each following line in the file however the class version throws the exception
I am getting RUNTIME ERROR(NZEC) on my following code while running my code on competetive programming sites.But could not understand where is the problem in my code as it is running absolutely fine on eclipse:
My code is:
import java.util.*;
public class Main {
public boolean isPalindrome(int number) {
String s1 = String.valueOf(number);
StringBuffer s = new StringBuffer(s1);
String s2 = String.valueOf(s.reverse());
if ((Integer.parseInt(s1)) == (Integer.parseInt(s2)))
return true;
else
return false;
}
public static void main(String[] args) throws java.lang.Exception {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
int m1[] = new int[t];
int k=0;
for (int i = 0; i < t; i++) {
int m = sc.nextInt();
for (int j = m + 1;; j++) {
Main main = new Main();
if (main.isPalindrome(j)) {
m1[k++] = j;
break;
}
}
}
for(int l=0;l<m1.length;l++)
{
System.out.println(m1[l]);
}
}
}
Thanks in advance!!
Did you submit this code on CodeChef/Spoj?
Your code seems to be fine but you should provide the input or run your code on an interactive console(as we do in terminal).
You can observe your error by commenting on the scanner lines and initializing the variables in the code itself as I checked this by running it on CodeChef
Else, Try adding this Scanner class.
import java.util.Scanner; // Import the Scanner class
This error is caused when your code returns Non-Zero Error Code(NZEC)
In languages which have exception handling like Java, Python etc we can use exception hadling using try - catch blocks.
NZEC is a runtime error.
for detailed answer to the above question
click here
Our professor is making us do some basic programming with Java, he gave a website and everything to register and submit our questions, for today I need to do this one example I feel like I'm on the right track but I just can't figure out the rest. Here is the actual question:
**Sample Input:**
10 12
10 14
100 200
**Sample Output:**
2
4
100
And here is what I've got so far :
public class Practice {
public static int calculateAnswer(String a, String b) {
return (Integer.parseInt(b) - Integer.parseInt(a));
}
public static void main(String[] args) {
System.out.println(calculateAnswer(args[0], args[1]));
}
}
Now I always get the answer 2 because I'm reading the single line, how can I take all lines into account? thank you
For some strange reason every time I want to execute I get this error:
C:\sonic>java Practice.class 10 12
Exception in thread "main" java.lang.NoClassDefFoundError: Fact
Caused by: java.lang.ClassNotFoundException: Fact.class
at java.net.URLClassLoader$1.run(URLClassLoader.java:20
at java.security.AccessController.doPrivileged(Native M
at java.net.URLClassLoader.findClass(URLClassLoader.jav
at java.lang.ClassLoader.loadClass(ClassLoader.java:307
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.
at java.lang.ClassLoader.loadClass(ClassLoader.java:248
Could not find the main class: Practice.class. Program will exit.
Whatever version of answer I use I get this error, what do I do ?
However if I run it in eclipse Run as > Run Configuration -> Program arguments
10 12
10 14
100 200
I get no output
EDIT
I have made some progress, at first I was getting the compilation error, then runtime error and now I get wrong answer, so can anybody help me what is wrong with this:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
public class Practice {
public static BigInteger calculateAnswer(String a, String b) {
BigInteger ab = new BigInteger(a);
BigInteger bc = new BigInteger(b);
return bc.subtract(ab);
}
public static void main(String[] args) throws IOException {
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = stdin.readLine()) != null && line.length()!= 0) {
String[] input = line.split(" ");
if (input.length == 2) {
System.out.println(calculateAnswer(input[0], input[1]));
}
}
}
}
I finally got it, submited it 13 times rejected for whatever reasons, 14th "the judge" accepted my answer, here it is :
import java.io.BufferedInputStream;
import java.util.Scanner;
public class HashmatWarrior {
public static void main(String args[]) {
Scanner stdin = new Scanner(new BufferedInputStream(System.in));
while (stdin.hasNext()) {
System.out.println(Math.abs(stdin.nextLong() - stdin.nextLong()));
}
}
}
Use BufferedReader, you can make it read from standard input like this:
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = stdin.readLine()) != null && line.length()!= 0) {
String[] input = line.split(" ");
if (input.length == 2) {
System.out.println(calculateAnswer(input[0], input[1]));
}
}
A lot of student exercises use Scanner because it has a variety of methods to parse numbers. I usually just start with an idiomatic line-oriented filter:
import java.io.*;
public class FilterLine {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
String s;
while ((s = in.readLine()) != null) {
System.out.println(s);
}
}
}
public class Sol {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
}
}
Look into BufferedReader. If that isn't general/high-level enough, I recommend reading the I/O tutorial.
The problem you're having running from the command line is that you don't put ".class" after your class file.
java Practice 10 12
should work - as long as you're somewhere java can find the .class file.
Classpath issues are a whole 'nother story. If java still complains that it can't find your class, go to the same directory as your .class file (and it doesn't appear you're using packages...) and try -
java -cp . Practice 10 12
The easilest way is
import java.util.*;
public class Stdio4 {
public static void main(String[] args) {
int a=0;
int arr[] = new int[3];
Scanner scan = new Scanner(System.in);
for(int i=0;i<3;i++)
{
a = scan.nextInt(); //Takes input from separate lines
arr[i]=a;
}
for(int i=0;i<3;i++)
{
System.out.println(arr[i]); //outputs in separate lines also
}
}
}
This is good for taking multiple line input
import java.util.Scanner;
public class JavaApp {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String line;
while(true){
line = scanner.nextLine();
System.out.println(line);
if(line.equals("")){
break;
}
}
}
}
import java.util.*;
import java.io.*;
public class Main {
public static void main(String arg[])throws IOException{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
StringTokenizer st;
String entrada = "";
long x=0, y=0;
while((entrada = br.readLine())!=null){
st = new StringTokenizer(entrada," ");
while(st.hasMoreTokens()){
x = Long.parseLong(st.nextToken());
y = Long.parseLong(st.nextToken());
}
System.out.println(x>y ?(x-y)+"":(y-x)+"");
}
}
}
This solution is a bit more efficient than the one above because it takes up the 2.128 and this takes 1.308 seconds to solve the problem.
package pac001;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Entry_box{
public static final String[] relationship = {"Marrid", "Unmarried"};
public static void main(String[] args)
{
//TAKING USER ID NUMBER
int a = Integer.parseInt(JOptionPane.showInputDialog("Enter ID no: "));
// TAKING INPUT FOR RELATIONSHIP
JFrame frame = new JFrame("Input Dialog Example #3");
String Relationship = (String) JOptionPane.showInputDialog(frame,"Select Your Relationship","Married",
JOptionPane.QUESTION_MESSAGE, null, relationship,relationship[0]);
//PRINTING THE ID NUMBER
System.out.println("ID no: "+a);
// PRINTING RESULT FOR RELATIONSHIP INPUT
System.out.printf("Mariitual Status: %s\n", Relationship);
}
}