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);
}
}
Related
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 tried coderbyte and looks something is wrong with it. The first challenge is simply to reverse a string. I did this in java:
import java.util.*;
import java.io.*;
class Main {
public static String FirstReverse(String str) {
char[] chars = str.toCharArray();
String ret = "";
for (int i = chars.length - 1; i >= 0; i--) {
ret += chars[i];
}
return ret;
}
public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
System.out.print(FirstReverse(s.nextLine()));
}
}
It said, that three test cases had wrong output and there was the correct output. I tried running the code with the specified cases and it printed the same string as correct output for that case. So I tried resubmitting it and it said that only one test case was correct and all other had wrong out put. So I said OK and rewrote my code this way:
import java.util.*;
import java.io.*;
class Main {
public static String FirstReverse(String str) {
return new StringBuilder(str).reverse().toString();
}
public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
System.out.print(FirstReverse(s.nextLine()));
}
}
Unfortunately it still says only one test case was successful... Any ideas what happened? Thanks
I want to print out the nth string using the
Queue data type.
Ex.
$ java NthString 5
a b c d e f
< ctrl -d >
should give me:
b (the fifth string from the right)
This is what I have so far, but I do not know my next step:
public class NthString {
public static void main(String[] args) {
Queue<Integer> q = new Queue<Integer>();
while(!StdIn.isEmpty()){
q.enqueue(StdIn.readInt());
}
}
}
Thanks
public class NthString {
public static void main(String[] args) {
Integer n = Integer.parseInt(args[0]);
Queue<Integer> q = new Queue<Integer>();
while(!StdIn.isEmpty()){
q.enqueue(StdIn.readInt());
}
while(q.size() > n){
q.dequeue();
}
StdOut.println(q.peek().toString());
}
}
First of all you should know how these stuff work, so read my comments carefully. I have written a sample for you but it is not exactly what you need but with small changes you can reach the requirement.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
public class NthString {
public static void main(String[] args) {
// java NthString 5
// when you run this command 5 will come from args as first parameter
int nth = Integer.parseInt(args[0]);
// Since we get alfabetic from console input your queue must be type of String
Queue<String> q = new LinkedList<>();
// This is in place of your StdIn
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
try {
String s = "";
// '/' this is the exit String that is expected from user to give at last to stop reading furthermore
// in your case it is different, ctrl -d ?
while (!"/".equals((s = bufferRead.readLine()))) {
q.add(s);
}
} catch (IOException e) {
e.printStackTrace();
}
String polled = "";
int count = 1;
// now you have to poll from queue back and count to get the nth string
// since the queue is implemented as linkedlist in my case 5th element will output e instead of b
while ((polled = q.poll()) != null) {
if (count == nth) {
System.out.println(nth + " th string is " + polled);
}
count++;
}
}
}
I've been working on an assignment for quite sometime now. The program compiles fine, but when ran, the driver class does not produce any results. The program I'm writing extends another class and is used to find the average word length of a text file as well as how often words with one letter, two letters, three letters, etc appear (any word that is 15 or greater letters is grouped).
Here is the class of which mine extends:
public abstract class FileAccessor{
String fileName;
Scanner scan;
public FileAccessor(String f) throws IOException{
fileName = f;
scan = new Scanner(new FileReader(fileName));
}
public void processFile() {
while(scan.hasNext()){
processLine(scan.nextLine());
}
scan.close();
}
protected abstract void processLine(String line);
public void writeToFile(String data, String fileName) throws IOException{
PrintWriter pw = new PrintWriter(fileName);
pw.print(data);
pw.close();
}
}
Here is my work:
import java.util.Scanner;
import java.io.*;
public class WordPercentages extends FileAccessor{
int[] length1 = new int[15];
double[] percentages = new double[15];
int totalWords = 0;
double average = 0.0;
public WordPercentages(String s)throws IOException{
super(s);
}
public void processLine(String file){
super.fileName=file;
while(super.scan.hasNext()){
totalWords+=1;
String s = super.scan.next();
if (s.length() < 15){
length1[s.length()]+=1;
}
else if(s.length() >= 15){
length1[15]+=1;
}
}
}
public double[] getWordPercentages(){
for(int j = 1; j < percentages.length; j++){
percentages[j] += length1[j];
percentages[j]=(percentages[j]/totalWords)*100;
}
return percentages;
}
public double getAvgWordLength(){
for(int j = 1; j<(percentages.length); j++){
average+=((j*(percentages[j])/totalWords));
}
return average;
}
}
And here is the driver class:
import java.util.Scanner;
import java.io.IOException;
public class WordPercentagesDriver{
public static void main(String[] args) throws IOException{
try{
String fileName;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a text file name to analyze:");
fileName = scan.nextLine();
System.out.println("Analyzed text: " + fileName);
WordPercentages wp = new WordPercentages(fileName);
wp.processFile();
double [] results = wp.getWordPercentages();
printWordSizePercentages(results);
System.out.printf("average word length: %4.2f",wp.getAvgWordLength());
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void printWordSizePercentages(double[] data){
for(int i = 1; i < data.length; i++)
if (i==data.length-1)
System.out.printf("words of length " + (i) + " or greater: %4.2f%%\n",data[i]);
else
System.out.printf("words of length " + (i) + ": %4.2f%%\n",data[i]);
}
}
I've tried placing a text file with known results in the same folder, everything complies, I then type in the name of the text file (including the .txt) and unfortunately nothing happens. Any help would be greatly appreciated.
NOTE: The FileAccessor Class and the Driver class were both provided by my instructor, so any source of error would come from the WordPercentage class.
Just ran the code, It looks like your code is throwing a "FileNotFoundExeption". What you have to do to fix this is place the file that you are looking for into the workspace you are working in. You can either save the txt file into your workspace or specify where the txt file is located. Example: C:Programs/documents/Alice...
good luck!
I have written a simple program in the NetBeans IDE using Java. After making a few changes to the main method this morning, the console does not print anything when I run the program. I simply want it to reach startMenus(sc). EDIT: I have now put in a few System.out.println() and it does not reach "Blah2" which is right after my first loop...
public class Calculator {
public static int[] NUMBERS; //global value for the array
public static void main(String[] args) throws FileNotFoundException {
File file = new File("data.txt");
Scanner sc = new Scanner(file);
System.out.println("Blah1");
int counter = 0;
while (sc.hasNextInt()) {
counter = counter++;
}
System.out.println("Blah2");
int lenth = counter;
NUMBERS = new int[lenth];
System.out.println("Blah3");
sc.close();
File file2 = new File("data.txt");
Scanner sc2 = new Scanner(file2);
System.out.println("Blah4");
int i = 0;
while (sc2.hasNextInt()) {
NUMBERS[i] = sc2.nextInt();
++i;
}
System.out.println("Blah5");
sc2.close();
System.out.println("Welcome to Calculation Program!\n");
startMenus(sc);
}
}
Are you sure you aren't throwing any other exceptions that are killing your app before it reaches System.out.println? Judging by your description you may want to either debug or put some other println statements further up the chain as it could be dying due to something.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class Calculator {
public static int[] NUMBERS; //global value for the array
public static void main(String[] args) throws FileNotFoundException, IOException {
File file = new File("data.txt");
file.createNewFile();
Scanner sc = new Scanner(file);
int counter = 0;
while (sc.hasNextInt()) {
counter = counter++;
}
int lenth = counter;
NUMBERS = new int[lenth];
sc.close();
File file2 = new File("data.txt");
file2.createNewFile();
Scanner sc2 = new Scanner(file2);
int i = 0;
while (sc2.hasNextInt()) {
NUMBERS[i] = sc2.nextInt();
++i;
}
sc2.close();
System.out.println("Welcome to Calculation Program!\n");
startMenus(sc);
}
private static void startMenus(Scanner sc) {
System.out.println("Run your code here!!!");
}
}
Couple of things:
You need to import additional classes that are not part of your core project. Exceptions, File, and Scanner all fall into this category.
You need to run the createNewFile() method to actually create your file. Your original code was throwing a FileNotFound exception because the file was never being created.
You need to have the startMenus method defined before calling it.
I've included some corrected code. Hope this helps!
The System.out calls probably wheren't reached yet, because one of your loops took too long to execute, longer then you were willing to wait. Log something from inside a loop to get some more feedback, the program is probably fine.