Error while trying command line output of arguments - java

What is the error in following code while trying command line arguments ? I am getting an error at line System.out.println(args[i]);
public class CommandLA{
public static void main(String []args)
{
int s = 0;
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
s = s + Integer.parseInt(args[i]);
System.out.println("Sum is : "+s);
}
}

maybe
public static void main(String []args)
{
int s = 0;
for (String str : args) {
s = s + Integer.parseInt(str);
}
System.out.println("Sum is : "+s);
}
or using an indexed for
public static void main(String []args)
{
int s = 0;
for (int i = 0; i < args.length; i++) {
s = s + Integer.parseInt(args[i]);
}
System.out.println("Sum is : "+s);
}

Simple:
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
followed by
s = s + Integer.parseInt(args[i]);
But - you are missing the { after the loop! Therefore the scope in which i exists (is visible) is only the line directly after the "for-loop" line!
In other words you need for (..) { all stuff that uses i }!

To elaborate on the answer of GhostCat:
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
s = s + Integer.parseInt(args[i]);
is the same as
for(int i=0;i<args.length;i++){
System.out.println(args[i]);
}
s = s + Integer.parseInt(args[i]);
Which means that in the last line, i is not known, resulting in an error.
I wonder why the error was detected at the line before, because until that, the code is technically correct.
That said, I recommend to use brackets in any case. Some people omit them to get shorter code, but that means that if one adds a line later on, he could easily make a mistake. This is personal preference, of course.

Related

Java program to reverse a string not working?

I have written a piece of code to reverse a string in Java. However, its showing multiple errors and I wish to understand where it is that I am going wrong. I know that there are alternative methods of reversing a string. However, I want to know where I am going wrong with my code.
public class RevString {
public static void main(String[] args)
{
public Reverse (String str)
{
int len = str.length();
String rev;
for (int i = 0; i <= len; i++)
{
rev = str[i] + rev;
}
System.out.println(rev);
}
Reverse("Canyon");
}
}
Errors:
Multiple markers at this line
- Syntax error on token ")", ; expected
- Syntax error on token "(", . expected
- Reverse cannot be resolved to a type
- Illegal modifier for parameter str; only final is
The method Reverse(String) is undefined for the type
RevString
Could someone provide me with a resolution?
There are many errors in your code :
For loop condition should be i < len
String rev should be initialized to "" (empty string), else it will throw error when you try to append another string to it.
You can't access characters in a string using str[i], use str.charAt(i) instead.
You are trying to initialize a function (Reverse) inside another function (main), you must initialize it outside the main function.
Also, here is a simple one liner for string reversal:
new StringBuilder(str).reverse().toString()
A good tip might be to use the StringBuilder class whenever you want to do any kind of string manipulation in Java.
Your code has many issues:
You are declaring the method Reverse() inside the main method.
You also need to initialize rev to an empty string.
You can use str.charAt(i) to access each character of the string.
Your for loop goes beyond the string if you use i <= len; so it
should be i < len;.
Your Reverse() method should be static since you are calling it in main
method (which is static)
Here is working code.
public class RevString {
public static void main(String[] args) {
Reverse("Canyon");
}
public static void Reverse (String str) {
int len = str.length();
String rev="";
for (int i = 0; i < len; i++) {
rev = str.charAt(i) + rev;
}
System.out.println(rev);
}
}
Please see the below code:
public class Hello {
public static String reverse (String str){
int len = str.length();
String rev="";
char[] strArray = str.toCharArray();
for (int i = 0; i < len; i++)
{
rev = strArray[i] + rev;
}
return rev;
}
public static void main(String[] args) {
String result = reverse("Canyon");
System.out.println("Reversed String: " + result);
}
}
public class reverseString
{
public static void main(String[] args)
{
System.out.println("Welcome to the the string reverser.");
System.out.println("Here is where a person may put is a sentence and the orintation" +
" of the words is reversed.");
Scanner keyboard = new Scanner(System.in);
String word = keyboard.nextLine();
int lengthOf = word.length();
int j = 0;
char loopStr;
String LoopStr;
String Nstr = "";
for(int n = lengthOf; n >0 ;n--)
{
j = n;
LoopStr = word.substring(j-1,j);
Nstr = Nstr + LoopStr;
}
System.out.println(Nstr);
}
}

Counting the amount of times each letter shows in a file

Essentially, this code takes a file (which is a few paragraphs of text) and counts the amount of times each letter appears and prints it onto the console. While I've finished all the code in terms of calculation, I'm running into an exception. When I run this, it shows:
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at LetterCount.countOccurrences(LetterCount.java:29)
at LetterCount.main(LetterCount.java:20)
Here is my code:
// Document your class here
import java.util.Scanner;
import java.io.File;
import java.io.FileInputStream;
public class LetterCount {
public final static String FILENAME = "testFile.txt";
// Driver to test LetterInventory class
public static void main(String[] args) {
Scanner inputFile = null;
try {
inputFile = new Scanner(new File(FILENAME));
} catch (Exception e) {
System.out.println("File could not be opened: " + FILENAME);
System.exit(0);
}
int[] counts = countOccurrences(inputFile);
displayTable(counts);
resetTable(counts);
}
public static int[] countOccurrences (Scanner inputFile) {
int[]counts = new int[26];
char[] characters = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
while (inputFile.hasNextLine()) {
String theWord = inputFile.next();
theWord = theWord.toLowerCase();
for (int j = 0; j < theWord.length(); j++) {
for (int counter = 0; counter < 26; counter++) {
if (theWord.charAt(j) == characters[counter]) {
counts[counter] += 1;
}
}
}
}
return counts;
}
public static void displayTable (int[] counts) {
for (int index = 0; index < 26; index++) {
System.out.println((char)('a' + index) + ":\t" + counts[index]);
}
}
public static void resetTable (int[] counts) {
System.out.println();
for (int index = 0; index < 26; index++) {
System.out.println((char)('a' + index) + ":\t0");
}
}
}
When I clicked on the highlighted parts of NoSuchElementException, I saw that it was referring to the String I created. What am I doing wrong, and what can I do to fix it?
The method you use to read the data should be of the same type as the one you use to check if there is more data.
In your while statement, you use inputFile.hasNextLine(), so on the line after it, you should use inputFile.nextLine() (rather than inputFile.next() as you do now).
Alternatively, you can change the while statement to use inputFile.hasNext().
No guarantees, but try using inputFile.hasNext() in your while instead of inputFile.hasNextLine(). A next line being available is not necessarily the same thing as a next word being available.
You don't need the characters array (you can use the same math you have in display to perform the addition of counts). Also, you should be consistent with how you call Scanner.hasNextLine() and Scanner.next() (check for next with hasNext()). Something like,
public static int[] countOccurrences(Scanner inputFile) {
int[] counts = new int[26];
while (inputFile.hasNext()) {
String theWord = inputFile.next().toLowerCase();
for (char ch : theWord.toCharArray()) {
if (Character.isLetter(ch)) {
counts[ch - 'a']++;
}
}
}
return counts;
}

Why the program output is not displaying each string separately after getting UpperCased?

the program is written for converting every first letter of the word to UpperCase
public class MainClass {
public static void main(String[] args) {
int i;
String toBeCapped="";
String str[] ={"This is a ball","This is a bat","this is the wicket"};
int e=str.length;
for(int j=0;j<e;j++)
{
String[] tokens = str[j].split("\\s");
for( i = 0; i < tokens.length; i++)
{
char capLetter = Character.toUpperCase(tokens[i].charAt(0));
toBeCapped += " " + capLetter + tokens[i].substring(1);
}
System.out.println(toBeCapped);
}
}
}
The output produced is as:-
This Is The Ball
This Is The Ball This Is The Bat
This Is The Ball This Is The Bat This Is The Wicket
I wanted the output to be as:-
This Is The Ball
This Is The
This Is The Wicket
Please tell me what is the mistake I'm making. Thank You
The problem is that you never reset toBecapped to "" in the loop after printing.
Adding toBeCapped="" at the end of the loop after printing will fix this problem:
System.out.println(toBeCapped);
toBeCapped=""; // <<== Add this line
Note that string concatenation is relatively expensive in Java. A better approach is to use StringBuilder. See this Q&A for an in-depth discussion of this topic.
Below is the problematic code. The += appends the characters to an already built toBeCapped String. You need to set the toBeCapped String to an empty one after the innermost for loop
for( i = 0; i < tokens.length; i++)
{
char capLetter = Character.toUpperCase(tokens[i].charAt(0));
toBeCapped += " " + capLetter + tokens[i].substring(1);
}
System.out.println(toBeCapped);
}
toBeCapped = "";
Your code has a problem because toBeCapped variable is never reset after being used in the loop. A good coding practice is to declare and use loop variables inside the loop (not outside of it)
public static void main(String[] args) {
String str[] ={"This is a ball","This is a bat","this is the wicket"};
int e = str.length;
for(int j=0;j<e;j++) {
String toBeCapped="";
String[] tokens = str[j].split("\\s");
for(int i = 0; i < tokens.length; i++) {
char capLetter = Character.toUpperCase(tokens[i].charAt(0));
toBeCapped += " " + capLetter + tokens[i].substring(1);
}
System.out.println(toBeCapped);
}
}

how can I change the lowercase array values to uppercase?

I need "args[i]" to be converted to Uppercase so the output will be:
"$ARG1" line break
"$ARG2" line break
"$ARG3" line break
and so on. I need to use the "toUpperCase" method but don't know how.
public class Main {
public static void main(String[] args) {
System.out.println("Number of args:" +
args.length);
for(int i=0; i<args.length; i++){
char dollar = '\u0024';
System.out.println(dollar + args[i]);
}
}
}
Java has this functionality built into the String object like so:
System.out.println(dollar + args[i].toUpperCase());
See the Oracle documentation here
Just use .toUpperCase() on any String, and it will return an all-upper-case String.
System.out.println(dollar + args[i].toUpperCase());
java has String method :public String toUpperCase()
public class Main {
public static void main(String[] args) {
System.out.println("Number of args:" + args.length);
for(int i=0; i<args.length; i++){
char dollar = '\u0024';
System.out.println(dollar + args[i].toUpperCase());
}
}
}
See the Oracle documentation here
public class Main {
public static void main(String[] args) {
System.out.println("Number of args:" +
args.length);
char dollar = '\u0024';
for(int i=0; i<args.length; i++){
System.out.println(dollar + args[i].toUpperCase());
}
}
}

Finding specific argument then adding value of next one to variable

I'm new to java and i need some help. I got few things to do and i'm stuck
with this problem. I really have no idea how to do it...
So in CMD line if i enter banana banana apple apple -name Carlos banana Mike -c 8
it will print "Hello Carlos!" eight times.
public class cheese {
public static void main(String args[]) {
for(String s: args){
if(s.equals("-name")){
String p = (GIVE VALUE OF FIRST ARGUMENT AFTER "-name");
if (s.equals("-c")){
int i = Integer.parseInt(THE FIRST ARGUMENTS AFTER "-c");
for(int j=0; j >= i ; j++)
System.out.println("Hello "+p+"!");
}
}
}
}
}
Parsing command-line arguments properly is surprisingly hard, and there are lots of libraries that can help. Your example code can be rearranged as follows to make it work (but it has no real error handling, so there are lots of ways to make it go wrong, such as passing "-name" twice, or not supplying enough arguments).
public class CmdLine {
public static void main(String args[]) {
String p = "";
int i = 0;
for (int k = 0; k < args.length; k++) {
if (args[k].equals("-name")) {
p = args[k + 1];
} else if (args[k].equals("-c")) {
i = Integer.parseInt(args[k + 1]);
}
}
for (int j = 0; j < i; j++) {
System.out.println("Hello " + p + "!");
}
}
}

Categories