Java code prints right but returns wrong - java

The following code:
public class NewClass1 {
public static String mus = "";
public static String musCal(String[] signal, int[] time) {
int i = 0;
while (i < signal.length) {
switch (signal[i]) {
case "x": {
// System.out.print("x = ");
mus = mus + "x";
int sum = time[i];
if (signal[i + 1] == "C") {
i++;
while (i < signal.length && signal[i] == "C") {
sum += time[i];
i++;
}
} else
i++;
// System.out.print(sum + " ");
mus = sum + " ";
break;
}
case "y": {
// System.out.print("y = ");
mus = mus + "y ";
int sum = time[i];
if (signal[i + 1] == "C") {
i++;
while (i < signal.length && signal[i] == "C") {
sum += time[i];
i++;
}
} else
i++;
// System.out.print(sum + " ");
mus = sum + " ";
break;
}
case "z": {
// System.out.print("z = ");
mus = mus + "z ";
int sum = time[i];
if (signal[i + 1] == "C") {
i++;
while (i < signal.length && signal[i] == "C") {
sum += time[i];
i++;
}
} else
i++;
// System.out.print(sum + " ");
mus = sum + " ";
break;
}
}
}
return mus;
}
public static void main(String[] args) {
String signal[] = { "x", "y", "y", "C", "C", "z", "C", "C", "x", "C" };
int time[] = { 2, 5, 1, 4, 7, 8, 2, 6, 4, 3 };
musCal(signal, time);
System.out.print(mus);
}
}
The expected output from the code is:
x=2 y=5 y=12 z=16 x=7
If the comments signs // are removed to activate the System.out.print statements, the code gives the expected output. But when I was trying to collect this output in the form of 'String mus', as shown in the code, I got only the last element of the output string i.e. 7. Being new comer to java and programming, I need your help. Kindly help me to correct the return statement so that I may get the right output as String 'mus' by concatenating, or by any other suitable method.

you can also use this solution for :
replace mus=sum + " ";
with mus += sum + " ";

You overwrite mus at several places using
mus=sum + " ";
instead of concatenating it like
mus = mus + sum + " "
Also, you don't always use brackets for if and else, which is very bad code style and I condemn the Java inventors for making brackets optional if one only wants to execute a single line.

Related

How do I fix my "illegal start of type" and "<identifier> expected" errors at my return statement?

I know it has something to do with my bracket placement, but I am not sure where the error is occurring. Keep in mind this is a 2nd method within my class.
import java.util.Scanner*;
import java.util.Arrays.*;
public class BasicMathTest
{
//Creates an array to store the numbers that will be used in the math
problems
int alpha[] = {4, 8, 10, 15, 25, 30};
int beta[] = {2, 4, 5, 3, 5, 10};
double Problems = alpha.length;
public static void main(String args[])
{
System.out.println("Welcome to this Math Quiz. Here you will add, subtract, multiply and divide!");
//Ask the user to choose their type of problem
Scanner kbReader = new Scanner(System.in);
System.out.println("Select Addition (1), Subtraction (2), Multiplication (3) or Division (4): ");
int Selection = kbReader.nextInt();
//Calculates the users score
double score = Selection * 100 / Problems;
System.out.println("Your score on the test: " + score + "%");
}
public static double Selection ()
{
int score = 0; //Stores the number of correct answers
int correct; //Stores the correct answer
for (int i = 0; i < Problems; i++)
{
if (Selection == 1)
{
System.out.println(alpha[i] + " + " + beta[i]);
correct = alpha[i] + beta[i];
}
else if(Selection == 2)
{
System.out.print(alpha[i] + " - " + beta[i]);
correct = alpha[i] - beta[i];
}
else if (Selection = 3)
{
System.out.print(alpha[i] + " * " + beta[i]);
correct = alpha[i] * beta[i];
}
else if(Selection == 4)
{
System.out.print(alpha[i] + " / " + beta[i]);
correct = alpha[i] / beta[i];
}
}
System.out.println(" ");
}
return score;
}
Output: E:\Xinox Software\JCreatorV4LE\MyProjects\CreateTask\BasicMathTest.java:52: illegal start of type
return score;
^
E:\Xinox Software\JCreatorV4LE\MyProjects\CreateTask\BasicMathTest.java:52: <identifier> expected
return score;
^
2 errors
Problems:
you forgot an opening braces at "Selection == 4" if.
Write "==" instead of **"=""" in "else if (Selection == 3)"
type of score is double
Could you show us how you use score var ?
Look at this and let me know if it is right :
public static double Selection ()
{
double score = 0; //change from int to double
int correct; //Stores the correct answer
for (int i = 0; i < Problems; i++)
{
if (Selection == 1)
{
System.out.println(alpha[i] + " + " + beta[i]);
correct = alpha[i] + beta[i];
}
else if(Selection == 2)
{
System.out.print(alpha[i] + " - " + beta[i]);
correct = alpha[i] - beta[i];
}
else if (Selection == 3)
{
System.out.print(alpha[i] + " * " + beta[i]);
correct = alpha[i] * beta[i];
}
else if(Selection == 4)
{ // missing brace
System.out.print(alpha[i] + " / " + beta[i]);
correct = alpha[i] / beta[i];
}
System.out.println(" ");
}
return score;
}

Problems with while() loop [duplicate]

This question already has answers here:
Comparing two integer arrays in Java
(10 answers)
Closed 7 years ago.
The statement before the begining of while loop System.out.println("Value of i before loop = " + i); is not being printed and the value of i in the loop is not being printed starting from 1. Instead it starts printing from a random big int.
package main;
import java.util.Random;
public class Main {
public static void main(String args[]){
Random ran = new Random();
int[] in = {2,5,9};
int[] c_gen = new int[3];
int i = 0;
System.out.println("Value of i before loop = " + i);
while(!(c_gen.equals(in))){
c_gen[0] = ran.nextInt(10);
c_gen[1] = ran.nextInt(10);
c_gen[2] = ran.nextInt(10);
i++;
System.out.println(c_gen[0] + " " + c_gen[1] + " " + c_gen[2] + " .................." + i);
}
System.out.print("in = ");
for(int x : in)
System.out.print(x + " ");
System.out.print("\n" + "c_gen = ");
for(int x : c_gen)
System.out.print(x + " ");
System.out.println("\n" + "i = " + i);
}
}
You are directly comparing arrays resulting in an infinite loop. Those results are being printed but are going to be at the top of tons and tons of output. Fix your comparison.
Sotirios' intuition is correct - your bug is in the line while(!(c_gen.equals(in))). You can't compare arrays for equality using the .equals(...) method because "arrays inherit their equals-method from Object, [thus] an identity comparison will be performed for the inner arrays, which will fail, since a and b do not refer to the same arrays." (source). Thus because c_gen and in will always refer to different arrays (even if their contents are the same), your loop will go forever.
Try Arrays.equals(..) instead:
public static void main(String[] args) {
Random ran = new Random();
int[] in = {2,5,9};
int[] c_gen = new int[3];
int i = 0;
System.out.println("Value of i before loop = " + i);
while(!Arrays.equals(in, c_gen)){
c_gen[0] = ran.nextInt(10);
c_gen[1] = ran.nextInt(10);
c_gen[2] = ran.nextInt(10);
i++;
System.out.println(c_gen[0] + " " + c_gen[1] + " " + c_gen[2] + " .................." + i);
}
System.out.print("in = ");
for(int x : in)
System.out.print(x + " ");
System.out.print("\n" + "c_gen = ");
for(int x : c_gen)
System.out.print(x + " ");
System.out.println("\n" + "i = " + i);
}
This works (terminates in finite time) for me, with sample output:
Value of i before loop = 0
1 9 9 ..................1
5 4 1 ..................2
1 1 6 ..................3
1 3 6 ..................4
.... //Omitted because of space
6 5 8 ..................1028
2 5 9 ..................1029
in = 2 5 9
c_gen = 2 5 9
i = 1029
I get:
Value of i before loop = 0
2 2 1 ..................1
2 2 4 ..................2
...
Suggest you rebuild the project and try again.
As originally posted your code will not terminate because int[].equals(int[]) will not do what you expect.
You could try this though.
private static boolean equals(int[] a, int[] b) {
if (a == null && b == null) {
// Both null
return true;
}
if (a == null || b == null) {
// One null
return false;
}
if (a.length != b.length) {
// Differ in length.
return false;
}
for (int i = 0; i < a.length; i++) {
if (a[i] != b[i]) {
// Mismatch
return false;
}
}
// Same.
return true;
}
public void test() {
Random ran = new Random();
int[] in = {2, 5, 9};
int[] c_gen = new int[3];
int i = 0;
System.out.println("Value of i before loop = " + i);
while (!equals(c_gen, in)) {
c_gen[0] = ran.nextInt(10);
c_gen[1] = ran.nextInt(10);
c_gen[2] = ran.nextInt(10);
i++;
System.out.println(c_gen[0] + " " + c_gen[1] + " " + c_gen[2] + " .................." + i);
}
System.out.print("in = ");
for (int x : in) {
System.out.print(x + " ");
}
System.out.print("\n" + "c_gen = ");
for (int x : c_gen) {
System.out.print(x + " ");
}
System.out.println("\n" + "i = " + i);
}

Java String letter counter not working [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
This is my code for a program that should count the number of each letter in an inputted string. When I run the program, it says that there is 0 of each letter, no matter what I input. Thanks for the help in advance!
import java.util.Scanner;
public class stringprogram {
public static void stringinputmethod()
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a String");
String strs = scan.nextLine();
int strslength = strs.length();
int numa = 0;
int numb = 0;
int numc = 0;
int numd = 0;
int nume = 0;
int numf = 0;
int numg = 0;
int numh = 0;
int numi = 0;
int numj = 0;
int numk = 0;
int numl = 0;
int numm = 0;
int numn = 0;
int numo = 0;
int nump = 0;
int numq = 0;
int numr = 0;
int nums = 0;
int numt = 0;
int numu = 0;
int numv = 0;
int numw = 0;
int numx = 0;
int numy = 0;
int numz = 0;
for(int i = 0; i <= strslength; i++)
{
if (strs.substring(i, i) == "a")
{
numa = numa + 1;
}
if (strs.substring(i, i) == "b")
{
numb = numb + 1;
}
if (strs.substring(i, i) == "c")
{
numc = numc + 1;
}
if (strs.substring(i, i) == "d")
{
numd = numd + 1;
}
if (strs.substring(i, i) == "e")
{
nume = nume + 1;
}
if (strs.substring(i, i) == "f")
{
numf = numf + 1;
}
if (strs.substring(i, i) == "g")
{
numg = numg + 1;
}
if (strs.substring(i, i) == "h")
{
numh = numh + 1;
}
if (strs.substring(i, i) == "i")
{
numi = numi + 1;
}
if (strs.substring(i, i) == "j")
{
numj = numj + 1;
}
if (strs.substring(i, i) == "k")
{
numk = numk + 1;
}
if (strs.substring(i, i) == "l")
{
numl = numl + 1;
}
if (strs.substring(i, i) == "m")
{
numm = numm + 1;
}
if (strs.substring(i, i) == "n")
{
numn = numn + 1;
}
if (strs.substring(i, i) == "o")
{
numo = numo + 1;
}
if (strs.substring(i, i) == "p")
{
nump = nump + 1;
}
if (strs.substring(i, i) == "q")
{
numq = numq + 1;
}
if (strs.substring(i, i) == "r")
{
numr = numr + 1;
}
if (strs.substring(i, i) == "s")
{
nums = nums + 1;
}
if (strs.substring(i, i) == "t")
{
numt = numt + 1;
}
if (strs.substring(i, i) == "u")
{
numu = numu + 1;
}
if (strs.substring(i, i) == "v")
{
numv = numv + 1;
}
if (strs.substring(i, i) == "w")
{
numw = numw + 1;
}
if (strs.substring(i, i) == "x")
{
numx = numx + 1;
}
if (strs.substring(i, i) == "y")
{
numy = numy + 1;
}
if (strs.substring(i, i) == "z")
{
numz = numz + 1;
}
}
System.out.println("Number of a's: " + numa + "\n" + "Number of b's: " + numb + "\n" + "Number of c's: " + numc + "\n" + "Number of d's: " + numd + "\n" + "Number of e's: " + nume + "\n" + "Number of f's: " + numf + "\n" + "Number of g's: " + numg + "\n" + "Number of h's: " + numa + "\n" + "Number of i's: " + numi + "\n" + "Number of j's: " + numj + "\n" + "Number of k's: " + numk + "\n" + "Number of l's: " + numl + "\n" + "Number of m's: " + numm + "\n" + "Number of n's: " + numn + "\n" + "Number of o's: " + numo + "\n" + "Number of p's: " + nump + "\n" + "Number of q's: " + numq + "\n" + "Number of r's: " + numr + "\n" + "Number of s's: " + nums + "\n" + "Number of t's: " + numt + "\n" + "Number of u's: " + numu + "\n" + "Number of v's: " + numv + "\n" + "Number of w's: " + numw + "\n" + "Number of x's: " + numx + "\n" + "Number of y's: " + numy + "\n" + "Number of z's: " + numz);
}
public static void main(String[] args)
{
stringinputmethod();
}
}
Correct usage of the substring method:
strs.substring(i, i)
needs to be
strs.substring(i, i + 1)
because the char at lastIndex is not included in the output.
Correct comparison of Strings in Java
Also, as pointed out in the comments to this answer, you are comparing Strings with the == operator.
This will only works as long as both your Strings are the same object. For proper comparison you need to use strs.substring(..).equals()
Proper storing of data
Additionally, as already suggested in a comment to your question, you should start using arrays to save data like this.
Instead of
int numa = 0;
....
int numz = 0;
you should use arrays, or even better Map<Character,Integer>.
strs.substring(i, i) == "a" have two problems:
substring(i, i) creates string from i (inclusive), till i (exclusive) which means it creates empty string ""
this is not how we compare Strings. == may work sometimes if strings are pooled, but for dynamically created strings you need to use equals instead of == because Strings are objects, or even better use charAt(i) to get primitive char which you can be able to compare like strs.charAt(i) == 'a' (notice ' instead of ").
You can also use enhanced for loop on array of characters representing your string to avoid charAt. You should probably also be working on lower case characters as pointed in this comment. So your code can look more like
for (char ch : strs.toLowerCase().toCharArray()){
//do something based on value of `ch`
}
Try this:
It is a little bit shorter than your implementation (which is very good, but still a little bit verbose). Use Java 8 with this code, otherwise it won't compile.
What does it do?
If you understand that a string is nothing more but an array you can iterate over that array and see what kind of value is at the given index. The value at this index is put in a map (remember, a map is a key-value-store). So if you put the Integer 1 in the map where its key is "a", that means "a" occurs 1 time.
By reading the values at the appropriate indexii (very sophisticated plural form of index) with HashMap.get("a") and then incrementing the value by one, we have a nice little letter counter... without the need to predefine numa=0 and so forth. Give it a try and let me know if it werx.
package lettercounter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
/**
*
* #author edm
*/
public class LetterCounter {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a String");
String strs = scan.nextLine();
//this map will be populated with the occurrence of the letters in the string.
HashMap<String, Integer> countenLetters = new HashMap<>();
//the next line generates a key-value-store whose key is the letter in the string
//and the value is the accumulated occurrence of said letter.
Arrays.asList(strs.split("")).stream().forEach((String letter) -> {
Integer count = 0;
try {
count = countenLetters.get(letter).intValue();
} catch (Exception e) {
//tried to access a non existing value in the map
//this happens if there is a letter which was not set in the map until now.
//i.e. the first time the letter is encountered.
//this is no error. could have done it with an if also.
}
countenLetters.put(letter, ++count);
});
//do with this stuff what you want;
countenLetters.forEach((k,v) -> {
System.out.println("Letter "+k+" occurs "+v+" times in the string.");
});
}
}

How to write static method call without object instantiation

Doing some work, and I need to write the method using Object Oriented Programming, and to make the method without the object instantiation.
I do just not know how to do this. Ive been returned the following feedback:
Your main() method should go in the tester class, while all of the implementation methods and
constructor should go in the object class.
Here's some code, thank you!
public static void main(String[] args) throws IOException
{
// variables
Scanner in = new Scanner(System.in);
File fileRead = new File("/Users/jerome/Desktop/MorseCode.txt");
Scanner withinFile = new Scanner (fileRead);
String userInput = "";
String toMorse = "";
String[] file = new String[25];
String[] alp = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "o", "m", "n", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
for(int i = 0; i < 25; i ++)
{
file[i] = withinFile.nextLine();
}
System.out.print("Enter a word to translate: ");
userInput = in.nextLine();
// static methods
MorseCode2 morse = new MorseCode2();
morse.tooMorse(userInput, alp, file, toMorse);
// output
System.out.print("'"+ userInput+"'"+" translated into Morse Code is: " + tooMorse(userInput, alp, file, toMorse));
}
Annnd some more!
public static String tooMorse(String userInput, String[] alp, String[] file, String toMorse)
{
for(int i = 0; i < userInput.length(); i ++)
{
if(userInput.substring(i, i+1).equals(alp[i])) // a
{
toMorse += " " + file[i];
}
else if(userInput.substring(i, i+1).equals(alp[i+1])) // b
{
toMorse += " " + file[i+1];
}
else if(userInput.substring(i, i+1).equals(alp[i+2])) // c
{
toMorse += " " + file[i+2];
}
else if(userInput.substring(i, i+1).equals(alp[i+3])) // d
{
toMorse += " " + file[i+3];
}
else if(userInput.substring(i, i+1).equals(alp[i+4])) // e
{
toMorse += " " + file[i+4];
}
else if(userInput.substring(i, i+1).equals(alp[i+5])) // f
{
toMorse += " " + file[i+5];
}
else if(userInput.substring(i, i+1).equals(alp[i+6])) // g
{
toMorse += " " + file[i+6];
}
else if(userInput.substring(i, i+1).equals(alp[i+7])) //h
{
toMorse += " " + file[i+7];
}
else if(userInput.substring(i, i+1).equals(alp[i+8])) // i
{
toMorse += " " + file[i+8];
}
else if(userInput.substring(i, i+1).equals(alp[i+9])) // j
{
toMorse += " " + file[i+9];
}
else if(userInput.substring(i, i+1).equals(alp[i+10])) // k
{
toMorse += " " + file[i+10];
}
else if(userInput.substring(i, i+1).equals(alp[i+11])) // l
{
toMorse += " " + file[i+11];
}
else if(userInput.substring(i, i+1).equals(alp[i+12])) // m
{
toMorse += " " + file[i+12];
}
else if(userInput.substring(i, i+1).equals(alp[i+13])) // n
{
toMorse += " " + file[i+13];
}
else if(userInput.substring(i, i+1).equals(alp[i+14])) //o
{
toMorse += " " + file[i+14];
}
else if(userInput.substring(i, i+1).equals(alp[i+15])) // p
{
toMorse += " " + file[i+15];
}
else if(userInput.substring(i, i+1).equals(alp[i+16])) // q
{
toMorse += " " + file[i+16];
}
else if(userInput.substring(i, i+1).equals(alp[i+17])) // r
{
toMorse += " " + file[i+17];
}
else if(userInput.substring(i, i+1).equals(alp[i+18])) // s
{
toMorse += " " + file[i+18];
}
else if(userInput.substring(i, i+1).equals(alp[i+19])) // t
{
toMorse += " " + file[i+19];
}
else if(userInput.substring(i, i+1).equals(alp[i+20])) // u
{
toMorse += " " + file[i+20];
}
else if(userInput.substring(i, i+1).equals(alp[i+21])) // v
{
toMorse += " " + file[i+21];
}
else if(userInput.substring(i, i+1).equals(alp[i+22])) // w
{
toMorse += " " + file[i+22];
}
else if(userInput.substring(i, i+1).equals(alp[i+23])) // x
{
toMorse += " " + file[i+23];
}
else if(userInput.substring(i, i+1).equals(alp[i+24])) // y
{
toMorse += " " + file[i+24];
}
else if(userInput.substring(i, i+1).equals(alp[i+25])) // z
{
toMorse += " " + file[i+25];
}
else
{
return "no";
}
}
return toMorse;
MorseCode2 morse = new MorseCode2();
morse.tooMorse(userInput, alp, file, toMorse);
Change this to:
MorseCode2.tooMorse(userInput, alp, file, toMorse);
If you have other static methods like that, do the same thing.
Unlike normal methods, you don't call static methods on an instance of the class - only on the class itself. If you do write morse.tooMorse(...) the compiler will simply convert it to MorseCode2.tooMorse(...) for you, and emit a warning. So your original code is equivalent to this:
MorseCode2 morse = new MorseCode2();
MorseCode2.tooMorse(userInput, alp, file, toMorse);
which is slightly inefficient since morse isn't used anywhere.

I'm trying to use 2 user inputs to populate a 2d list array

I'm trying to populate a 2d list array using 2 user inputs.
Problem I'm having is that in the code below, the 1st for statement isn't producing the outcome I'm expecting, the 2nd for is doing what is needed. Also, with the code below I'm unable to close scanner.
public static void main(String[] args) {
ArrayList<String> listCon = new ArrayList<String>();
ArrayList<String> listCol = new ArrayList<String>();
Scanner txtInput = new Scanner(System.in);
char addTo = 'y';
do {
System.out.println("\nCurrent list is " + listCon + listCol + "\n");
System.out.println("Would you like to add a country to the list?\n\t"
+ "( y ) = YES\n\t( n ) = NO");
addTo = txtInput.next().toLowerCase().charAt(0);
if (addTo == 'y') {
System.out.println("Enter country name: ");
listCon.add(txtInput.next().toLowerCase());
System.out.println("Enter colour: ");
listCol.add(txtInput.next().toLowerCase());
} else if (addTo == 'n') {
int i = 1;
int countCon = listCon.size();
if(countCon == 0) {
System.out.println("No countries have been entered.");
} else {
String str = "country";
if(countCon > 1) {
str = "countries";
}
System.out.println("Thankyou for your input. We found " + countCon + " " +
str + " in the list.");
System.out.println("Listed " + str + ":\n");
for(String n : listCon) {
char[] conDigit = n.toCharArray();
conDigit[0] = Character.toUpperCase(conDigit[0]);
n = new String(conDigit);
for(String b : listCol) {
char[] colDigit = b.toCharArray();
colDigit[0] = Character.toUpperCase(colDigit[0]);
b = new String(colDigit);
System.out.println("Country " + i + " : " + n + " - \t" + b);
i = i + 1;
}
break;
}
break;
}
} else {
System.out.println("Incorrect input detected. please try again. \n");
}
} while (true);
}
}
You need to remove extra break from the first for loop to iterate. Otherwise, you break after first iteration.
for(String n : listCon) {
....
for(String b : listCol) {
...
}
break; //remove this!
}
break;
EDIT
The result im after is Country 1 : France - Blue Country 2 : UK -
White Country 3 : Ireland - Green
You need to iterate like this:
for (int i = 0; i < listCon.size() && i < listCol.size(); i++) {
String n = listCon.get(i);
char[] conDigit = n.toCharArray();
conDigit[0] = Character.toUpperCase(conDigit[0]);
n = new String(conDigit);
String b = listCol.get(i);
char[] colDigit = b.toCharArray();
colDigit[0] = Character.toUpperCase(colDigit[0]);
b = new String(colDigit);
System.out.println("Country " + i + " : " + n + " - \t" + b);
}

Categories