Create console application in java

Creating console application in Java in VS Code

Below programs illustrate readPassword() method in Console class in IO package: Program 1:Output: Program 2: Output: 2. Also, before you beat your head against the wall the following statement won’t work for you: == tests for reference equality. .equals() tests for value equality.

Creating console application in Java in VS Code

How do I go about creating a simple console application (like one that prints hello world to console) using VS Code in Java? How do I get VS Code to generate proper setup files for project?

There is a very good tutorial on Visual Studio Code page that you can find here teaching you to use that for Java Development.

I’ve put some references here as well!

Create a new file like Name.java

Then write your Class. You can run it with ‘F5’

And do you have installed java extensions for vsCode? Here’s the link:

Java Console Class, The Java Console class is be used to get input from console. It provides methods to read texts and passwords. If you read password using Console class, it will not be displayed to the user. The java.io.Console class is attached with system console internally. The Console class is introduced since 1.5. Let’s see a simple example to read text

Simple java console calculator

Without directly giving me the answer can someone help me with this simple calculator that I am trying to write? Everything seem to work well except for the very end when I ask the user to make a choice for add,subtract, multiply, or divide. It does not allow me to enter my choices in the console. I think it has something to do with the array of String that I created and the if statement. Not sure. Any tips would be much appreciated.

import java.util.Scanner; public class simpleCalculator < public static void main(String[] args) < Scanner input = new Scanner(System.in); //declare my variables int firstNum; int secondNum; int division = 0, addition = 0, subtraction = 0, multiplication = 0; String userChoice = ""; String choices[] = ; //ask for user input System.out.print("Please enter first number: "); firstNum = input.nextInt(); System.out.print("Please enter second number: "); secondNum = input.nextInt(); System.out.println("What type of operation would you like to perform on these numbers?"); System.out.println("add " +"multiply " +"subtract " + "divide "); userChoice = input.nextLine(); if (userChoice == "add") < System.out.print("Answer = " + addition); >//calculator formulas addition = firstNum + secondNum; multiplication = firstNum * secondNum; subtraction = firstNum - secondNum; division = firstNum / secondNum; > > 

nextInt() reads just the number and not the end of the line after the number. You will need a nextLine() after each nextInt() to consume the rest of the line.

Also, before you beat your head against the wall the following statement won’t work for you:

== tests for reference equality.

.equals() tests for value equality. So you need something like this instead:

I wanted to give you that freebie because I love your attitude that you don’t want anyone to give you the answer. That is great that you wan to learn it. Keep up the good work.

Saying that String a == String b means that you’re comparing two strings to see if they have reference equality, while saying a.equals(b) will compare the values stored in the string.

Reference equality is used to compare whether two object references point to the same object, which in this case you shouldn’t be using as you’re trying to compare whether the value of two variables are equal. So definitely go with

Читайте также:  About abstract class in php

Console writer() method in Java with Examples, Syntax: public PrintWriter writer () Parameters: This method does not accept any parameter. Return value: This method returns the PrintWriter which is associated with the console. Exceptions: This method does not any throw exception. Note: System.console () returns null in an online IDE. Below programs …

Console readPassword() method in Java with Examples

The readPassword() method of Console class in Java is of two types:

1. The readPassword() method of Console class in java is used to read a password or passphrase from the console with disabled echoing.

Parameters: This method does not accept any parameter.

Return value: This method returns a character array that contains the password or passphrase read from the console. It returns null if the stream is ended.

Exceptions: This method throws IOError if an I/O error occurs.

Note: System.console() returns null in an online IDE.

Below programs illustrate readPassword() method in Console class in IO package:

Источник

Java console application

Java console application tutorial shows how to create a Java console application. The application computes some statistics.

Java console example

The following example creates a Java console application which reads data from a CSV file and computes some basic statistics.

The example uses Apache Commons libraries to parse command line arguments, do math, and transform data. The OpenCSV library is used to read CSV data.

2.3, 3.5, 5, 6.7, 3.2, 1.2, 6.7, 7.8 4.5, 2.1, 6.6, 8.7, 3.2, 1.0, 1.2, 3

This is the data file. The file name will be a console parameter to our program.

pom.xml src ├───main │ ├───java │ │ └───com │ │ └───zetcode │ │ JavaStatsEx.java │ │ MyStatsApp.java │ └───resources │ data.txt └───test └───java

This is the project structure.

  4.0.0 com.zetcode javastatsex 1.0-SNAPSHOT UTF-8 12 12   commons-cli commons-cli 1.4  com.opencsv opencsv 4.6  org.apache.commons commons-math3 3.6.1    

In the pom.xml file, we define the dependencies of the application. The commons-cli artifact is for parsing command line arguments, opencsv for reading CSV data, commons-math for statistical calculations, and commons-lang3 for transforming list into an array.

The exec-maven-plugin executes Java programs from Maven. In the arguments tag, we give the application the option and the filename.

package com.zetcode; /** * Starter class for MyStats application. * * @author janbodnar */ public class JavaStatsEx < /** * Application entry point. * * @param args application command line arguments */ public static void main(String[] args) < var app = new MyStatsApp(); app.run(args); >>

JavaStatsEx is the application entry point. It creates the instance of MyStatsApp and passes it the application arguments.

package com.zetcode; import com.opencsv.CSVReaderBuilder; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.math3.stat.StatUtils; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; /** * MyStatsApp is a simple console application which computes * basic statistics of a series of data values. The application takes * a file of data as its single argument. * * @author janbodnar */ public class MyStatsApp < /** * Runs the application * * @param args an array of String arguments to be parsed */ public void run(String[] args) < CommandLine line = parseArguments(args); if (line.hasOption("filename")) < System.out.println(line.getOptionValue("filename")); String fileName = line.getOptionValue("filename"); double[] data = readData(fileName); calculateAndPrintStats(data); >else < printAppHelp(); >> /** * Parses application arguments * * @param args application arguments * @return CommandLine which represents a list of application * arguments. */ private CommandLine parseArguments(String[] args) < Options options = getOptions(); CommandLine line = null; CommandLineParser parser = new DefaultParser(); try < line = parser.parse(options, args); >catch (ParseException ex) < System.err.println("Failed to parse command line arguments"); System.err.println(ex.toString()); printAppHelp(); System.exit(1); >return line; > /** * Reads application data from a file * * @param fileName file of application data * @return array of double values */ private double[] readData(String fileName) < var data = new ArrayList(); double[] mydata = null; try (var reader = Files.newBufferedReader(Paths.get(fileName)); var csvReader = new CSVReaderBuilder(reader).build()) < String[] nextLine; while ((nextLine = csvReader.readNext()) != null) < for (String e : nextLine) < data.add(Double.parseDouble(e)); >> mydata = ArrayUtils.toPrimitive(data.toArray(new Double[0])); > catch (IOException ex) < System.err.println("Failed to read file"); System.err.println(ex.toString()); System.exit(1); >return mydata; > /** * Generates application command line options * * @return application Options */ private Options getOptions() < var options = new Options(); options.addOption("f", "filename", true, "file name to load data from"); return options; >/** * Prints application help */ private void printAppHelp() < Options options = getOptions(); var formatter = new HelpFormatter(); formatter.printHelp("JavaStatsEx", options, true); >/** * Calculates and prints data statistics * * @param data input data */ private void calculateAndPrintStats(double[] data) < System.out.format("Geometric mean: %f%n", StatUtils.geometricMean(data)); System.out.format("Arithmetic mean: %f%n", StatUtils.mean(data)); System.out.format("Max: %f%n", StatUtils.max(data)); System.out.format("Min: %f%n", StatUtils.min(data)); System.out.format("Sum: %f%n", StatUtils.sum(data)); System.out.format("Variance: %f%n", StatUtils.variance(data)); >>
CommandLine line = parseArguments(args);

The parseArguments method parses the command line arguments. It returns CommandLine , which represents a list of arguments parsed against a Options descriptor.

Читайте также:  Css content before html code

if (line.hasOption(«filename»)) < System.out.println(line.getOptionValue("filename")); String fileName = line.getOptionValue("filename"); double[] data = readData(fileName); calculateAndPrintStats(data); >else

The application has a mandatory filename option, which points to the file to be read and compute statistics from. If it is not present, we provide the application help message.

Options options = getOptions();

The getOptions method returns the options of the application.

try < line = parser.parse(options, args); >catch (ParseException ex) < System.err.println("Failed to parse command line arguments"); System.err.println(ex.toString()); printAppHelp(); System.exit(1); >return line;

CommandLineParser parses the command line arguments. The application exits if there is a ParseException . The parser returns parsed arguments in CommandLine object.

try (var reader = Files.newBufferedReader(Paths.get(fileName)); var csvReader = new CSVReaderBuilder(reader).build()) 

CSVReader is used to read CSV data.

String[] nextLine; while ((nextLine = csvReader.readNext()) != null) < for (String e : nextLine) < data.add(Double.parseDouble(e)); >>

In this while loop, we read the CSV file line by line and parse the data into a list of Double values.

mydata = ArrayUtils.toPrimitive(data.toArray(new Double[0]));

We need primitive data types to calculate the statistics; therefore, we transform the list into an array of primitive double values. ArrayUtils comes from the Apache Commons Lang library.

private Options getOptions()

The getOptions provides the application options.

private void printAppHelp()

The printAppHelp prints the help of the application. It uses HelpFormatter to do the job.

private void calculateAndPrintStats(double[] data)

With StatUtils , we compute some statistics. The StatUtils takes a Java array as a parameter.

src/main/resources/data.txt Geometric mean: 3.412562 Arithmetic mean: 4.168750 Max: 8.700000 Min: 1.000000 Sum: 66.700000 Variance: 6.158292

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

In this article we have created a simple Java console application, which computes basic statistics from a CSV file.

Источник

Как написать простое консольное приложение с аргументами на Java

В данном посте я хочу рассказать , как создать простое консольное приложение на Java с использованием библиотеки args4j.

Не давно мне дали задание написать консольную утилиту при помощи библиотеки для парсинга аргументов. Я выбрал args4j и хочу поделиться своим опытом.

Разработать консольную утилиту, которая соединяет заданные в командной строке входные текстовые файлы в выходной, указываемый после ключа -out. С ключом -u делает обратную операцию, принимая один входной файл и разбивая его на несколько. Выходной файл тоже является текстовым. Придумать для него формат, позволяющий запоминать имена входных файлов и находить их границы. Command Line: tar -u filename.txt или tar file1.txt file2.txt … -out output.txt.

Сначала надо подключить зависимость, я использовал Maven. Тут все простенько:

Теперь можно реализовать парсинг аргументов. Создадим класс Parser и добавим туда две переменные и список для остальных аргументов.

Аннотация сверху дает понять библиотеке args4j, где хранить аргументы , значения опций и всякое , в общем все прям для ленивых. Сейчас будет чуть сложнее, нужно осмыслить то , что получили из консоли:

public static void main(String[] args) < new Parser().run(args); >private void run(String[] args) < CmdLineParser parser = new CmdLineParser(this); try < parser.parseArgument(args); if ((arguments == null && out != null) || (u != null && out != null)) < System.err.println("Ошибка ввода аргументов!"); System.err.println("tar [опции. ] аргументы. "); System.err.println("\nПример: tar -u \"filename.txt\" \n tar \"file1.txt file2.txt\" -out output.txt"); throw new IllegalArgumentException(""); >if (out != null) < new Delimiter().tar(arguments.split(" "), out); >else < if((u!=null && !Objects.requireNonNull(u).exists()) )< throw new IOException("Папки или файла не существует"); >new Delimiter().tar(u); > > catch (CmdLineException | IOException e) < System.err.println(e.getMessage()); System.exit(1); >>

В данном кусочке в основном можно обойтись самой популярной комбинацией клавиш у программистов , но я все же попробую часть разжевать. В начале стоит понимать , что мои проверки могут вам не подойти (9 строчку скорее всего придется переделать) там просто проверяю правильно ли пользователь ввел аргументы и если да , то смотрю , что дальше с ними делать. Если опция -out активирована, то идем в эту часть кода:

public void tar(String[] arguments, String out) throws IOException, CmdLineException < File f = new File(out); FileWriter writer; StringBuilder builder; if (f.createNewFile()) < writer = new FileWriter(f); for (String argument : arguments) < if(new File(argument).exists()) < FileReader fr = new FileReader(argument); BufferedReader reader = new BufferedReader(fr); builder = new StringBuilder(); int countLines = 0; String temp; while ((temp = reader.readLine()) != null) < builder.append(temp).append("\n"); countLines++; >writer.write(argument + " " + countLines + "\n"); writer.write(builder.toString()); >else < System.out.println("Неверный аргумент "+ argument + "\n пример: \"text1.txt text2.txt\" -out text3.txt"); >> writer.close(); > else < throw new IOException("Не возможно создать новый файл"); >>

Предварительно создал новый класс Delimiter и написал две простенькие функции. Не думаю , что кому-то это сильно пригодится , да и тут в принципе не сложно , так что рассказывать не буду. Второй метод (просто перегрузил метод tar) :

public void tar(File u) throws IOException < FileReader fr = new FileReader(u); BufferedReader reader = new BufferedReader(fr); String buf = reader.readLine(); FileWriter writer; if(buf.matches("([A-Za-z0-9-_.]+/?)+ 7+")) < while (buf != null) < String[] data = buf.trim().split(" "); String name = data[0]; int size = Integer.parseInt(data[1]); File f = new File(name); if (f.createNewFile()) < StringBuilder builder = new StringBuilder(); writer = new FileWriter(f); for (int i = 0; i < size; i++) < builder.append(reader.readLine()).append("\n"); >writer.write(builder.toString()); writer.close(); > else < System.out.println("Файл уже существует"); >buf = reader.readLine(); > >else < reader.close(); throw new IOException("Неверные данные , нужен другой файл!"); >reader.close(); >

Эта функция тоже простая , основная идея в том , что когда файлы соединяются, метод пишет название файла, который был добавлен + число строчек в файле , а когда файлы нужно разделить , метод считывает название файла и количество строк которые нужно бездумно считывать и так далее пока файл не закончится.

Осталось самое главное

Нужно как-то собрать jar файл , чтобы запускать его из консоли. Есть два пути , один сложный и правильный , второй простой , но он не имеет ничего общего с хорошей программой. Для первого способа нужно прописывать все зависимости в manifest , но я пока для этого способа сыроват , есть второй - с помощью плагина:

--> org.apache.maven.plugins maven-assembly-plugin 3.5.0   org.apache.maven.plugins maven-assembly-plugin 3.5.0   org.spbstu.gorchatovra.Parser   jar-with-dependencies    assemble-all package single    

Надеюсь , код , который я написал выше, хотя бы частично понятен, ну если что загуглите , я сделал все, что мог.

Вот и подошел к концу пост , надеюсь кому-то смог помочь, я программист мягко говоря начинающий , так что я открыт для предложений , готовый проект тут.

Источник

Оцените статью