This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm trying to create a simple binary to decimal converter for my CS class to get a little extra credit. We only use Java in my class, so I'm making it on the Java platform. I've set up a homepage to call my class methods from to make it easier for me when I have multiple classes for the lessons I learn in the CS class. I'm calling my first method, stringSplit, which takes the binary value given as the argument, converts it to a String, then uses .substring to slice it up into each bit. It sets each bit to a variable to be later analyzed. Next, it runs through my bi2decFunctions method. This is what I have here:
public static void bi2decFunctions(String num128, String num64, String num32, String num16, String num8, String num4, String num2, String num1){
int num128Return;
int num64Return;
int num32Return;
int num16Return;
int num8Return;
int num4Return;
int num2Return;
int num1Return;
System.out.println(" " + num128 + " " + num64 + " " + num32 + " " + num16 + " " + num8 + " " + num4 + " " + num2 + " " + num1);
//128
if(num128 == "1"){
num128Return = 128;
} else {
num128Return = 0;
}
//64
if(num64 == "1"){
num64Return = 64;
} else {
num64Return = 0;
}
//32
if(num32 == "1"){
num32Return = 32;
} else {
num32Return = 0;
}
//16
if(num16 == "1"){
num16Return = 16;
} else {
num16Return = 0;
}
//8
if(num8 == "1"){
num8Return = 8;
} else {
num8Return = 0;
}
//4
if(num4 == "1"){
num4Return = 4;
} else {
num4Return = 0;
}
//2
if(num2 == "1"){
num2Return = 2;
} else {
num2Return = 0;
}
//1
if(num1 == "1"){
num1Return = 1;
} else {
num1Return = 0;
}
System.out.println(" " + num128Return + " " + num64Return + " " + num32Return + " " + num16Return + " " + num8Return + " " + num4Return + " " + num2Return + " " + num1Return);
bi2decDisplay(num128, num64, num32, num16, num8, num4, num2, num1, num128Return, num64Return, num32Return, num16Return,
num8Return, num4Return, num2Return, num1Return);
}
Each time I run this, the correct values for my 8-bit input shows up, but the num(1-128) return variables all equal 0. The 'if' statements aren't even affecting the outcome of them. Anyone have any idea?
I'd also like to present this to my CS class, so I'd like a 1-10 scale on the neatness and quality of my code.
Do not compare strings with ==, say equals:
str1.equals(str2)
Related
This question already has answers here:
Cannot make a static reference to the non-static method
(8 answers)
Closed 2 years ago.
I'm trying to make a Math Quiz but I started learning Java recently and I'm having some trouble. I already read about accessing methods and stuff, but I don't see how all of this is supposed to help me there.
import java.util.Scanner;
public class MatQui{
Scanner scan = new Scanner(System.in);
int correct = 0;
public static void main(String[] args) {
System.out.println("Enter your name: ");
String name = scan.nextLine();
System.out.println("Hello " + name + "! Answer the questions.");
firstQuiz();
}
public void firstQuiz() {
int randomNum1 = (int)(Math.random() * 101 +1);
int randomNum2 = (int)(Math.random() * 101 +1);
int RandomAddSolution = scan.nextInt();
int CorrectAddSolution = randomNum1 + randomNum2;
System.out.println(randomNum1 + " + " + randomNum2 + " = ?");
if (RandomAddSolution == CorrectAddSolution) {
System.out.println("Correct!");
correct++;
}
else if (RandomAddSolution != CorrectAddSolution) {
System.out.println("Wrong! The correct answer is: " + CorrectAddSolution);
}
secondQuiz();
}
public void secondQuiz() {
int randomNum1 = (int)(Math.random() * 101 +1);
int randomNum2 = (int)(Math.random() * 101 +1);
int RandomMinusSolution = scan.nextInt();
int CorrectMinusSolution = randomNum1 - randomNum2;
System.out.println(randomNum1 + " - " + randomNum2 + " = ?");
if (RandomMinusSolution == CorrectMinusSolution) {
System.out.println("Correct!");
correct++; //Ly Huong Van
}
else if (RandomMinusSolution != CorrectMinusSolution) {
System.out.println("Wrong! The correct answer is: " + CorrectMinusSolution);
}
thirdQuiz();
}
public void thirdQuiz() {
int randomNum1 = (int)(Math.random() * 11 +1);
int randomNum2 = (int)(Math.random() * 11 +1);
int RandomMulSolution = scan.nextInt();
int CorrectMulSolution = randomNum1 * randomNum2;
System.out.println(randomNum1 + " + " + randomNum2 + " = ?");
if (RandomMulSolution == CorrectMulSolution) {
System.out.println("Correct!");
correct++;
}
else if (RandomMulSolution != CorrectMulSolution) {
System.out.println("Wrong! The correct answer is: " + CorrectMulSolution);
}
fourthQuiz();
}
public void fourthQuiz() {
int randomNum1 = (int)(Math.random() * 101 +1);
int randomNum2 = (int)(Math.random() * 11 +1);
int RandomDivSolution = scan.nextInt();
int CorrectDivSolution = randomNum1 / randomNum2;
System.out.println(randomNum1 + " / " + randomNum2 + " = ?");
if (RandomDivSolution == CorrectDivSolution) {
System.out.println("Correct!");
correct++;
endingScreen();
}
else if (RandomDivSolution != CorrectDivSolution) {
System.out.println("Wrong! The correct answer is: " + CorrectDivSolution);
endingScreen();
}
}
public void endingScreen() {
int percentageCorrect = correct * 25;
System.out.println("You answered " + correct + " questions correctly.!\n"
+ "That's " + percentageCorrect + "%!");
if (correct == 0) {
System.out.println(":(");
}
else if (correct != 0) {
System.out.println(":)");
}
}
I want to access 'firstQuiz()' method from main, but I get the error, that I can't access non static element form static main. How do I work with it?
Non Static methods can be accessed by creating objects of the class in which the method is present.
In this example, you will have to create the object of the class in the main method and call the method firstQuiz() using this object.
As tieburach answered... you can not access non static method from static one. You can not change main method signature, which means you can non make main non static. Main will always be static.
Solution would be to make your method static, but if it is not what you want, you can also create another class and instance of it in main method, and then call method on that class.
You can make the method static or you create a new instance of the class and access to it like that:
Test test = new Test();
test.yourMethod();
As you probably noticed, the error says that you can't access non static method from static one. The easiest solution for you is to make the methods you are invoking static as well.
You need create a new MatQui matqui = new MatQui(); and after call the method with new object created matqui.firstQuiz();
I am wondering how I could make this code loop whenever the user gives a number outside of what the operator variable is asking. I am open to different suggestions. I have tried and failed many times using the do while loop. I want the code to say "Choose a number between 1-4" if the user gives the wrong number and then I want the loop back to the operator variable until the user gives a correct number and after the correct answer is given I want the program to go though the rest of the code and close.
import static java.lang.System.*;
import static javax.swing.JOptionPane.*;
import static java.lang.Integer.*;
public class SimpleCalc {
public static void main(String[] args) {
do {
String operator = showInputDialog("Choose operation: " + "\n" +
"[1] = Plus" + "\n" +
"[2] = Minus" + "\n" +
"[3] = Multiply" + "\n" +
"[4] = Divide" + "\n");
int c = parseInt(operator);
if (c>4 || c<1) {
showMessageDialog(null, "Choose a number between 1 - 4.");
}
else{
String textA = showInputDialog("Enter first number: ");
String textB = showInputDialog("Enter second number: ");
int a = parseInt(textA);
int b = parseInt(textB);
switch(c) {
case 1:
showMessageDialog(null, a + " + " + b + " = " + (a+b));
break;
case 2:
showMessageDialog(null, a + " - " + b + " = " + (a-b));
break;
case 3:
showMessageDialog(null, a + " * " + b + " = " + (a*b));
break;
case 4:
showMessageDialog(null, a + " / " + b + " = " + (a/b));
break;
}
}
} while (c>4 || c<1);
}
}
Move the declaration of c out of do block, otherwise it is not accessible in while
int c;
do {
...
c = parseInt(operator);
...
} while (c > 4 || c < 1);
You are on the right track by using do while loop. However the value c is not seen as its within the do while block. if you add int c above the do block and make int c = parseInt(operator); to c = parseInt(operator); it will work
Maybe I'm just stupid (probably) but I have been struggling with this for LITERALLY the past five hours and I really can't figure it out. Nothing on this site / google seems to help me; everyone wants to know how to call a method that's defined in the main method in another method, but I am trying to do it the other way around. I am new to java, but I am aware that you can't directly call a variable from a method into another method. However, I have tried so many different iterations of trying to get the values and NOTHING is compiling and I get the same errors over and over again: "error: cannot find symbol" for all of my variables.
All I am trying to do is read a text file and print out what percentage of the words are of x length up to 13 and say how many of those words are in the document so like "Proportion of 1- letter words: .7% (2 words)" is printed out all the way to "Proportion of 13- letter words: 80.7% (7000 words)" (this is how the output is supposed to look, I know it's not pretty).
Anyway please help me because I am stuck and tearing my hair out.
import java.util.*;
import java.io.*;
public class FileReader
{
public static void main (String [] args)throws FileNotFoundException
{
WordCount();
WordLengthCount();
File file = new File("RomeoAndJuliet.txt");
Scanner keyboard = new Scanner(new FileInputStream(file));
System.out.println("Proportion of 1-letter words: " + count1/count + "% (" + count1 + " words)");
System.out.println("Proportion of 2-letter words: " + count2/count + "% (" + count2 + " words)");
System.out.println("Proportion of 3-letter words: " + count3/count + "% (" + count3 + " words)");
System.out.println("Proportion of 4-letter words: " + count4/count + "% (" + count4 + " words)");
System.out.println("Proportion of 5-letter words: " + count5/count + "% (" + count5 + " words)");
System.out.println("Proportion of 6-letter words: " + count6/count + "% (" + count6 + " words)");
System.out.println("Proportion of 7-letter words: " + count7/count + "% (" + count7 + " words)");
System.out.println("Proportion of 8-letter words: " + count8/count + "% (" + count8 + " words)");
System.out.println("Proportion of 9-letter words: " + count9/count + "% (" + count9 + " words)");
System.out.println("Proportion of 10-letter words: " + count10/count + "% (" + count10 + " words)");
System.out.println("Proportion of 11-letter words: " + count11/count + "% (" + count11 + " words)");
System.out.println("Proportion of 12-letter words: " + count12/count + "% (" + count12 + " words)");
System.out.println("Proportion of 13-letter words: " + count13/count + "% (" + count13 + " words)");
}
public static int WordCount(int n)throws FileNotFoundException
{
File file = new File("RomeoAndJuliet.txt");
Scanner keyboard = new Scanner(new FileInputStream(file));
int countABC=0;
while(keyboard.hasNext())
{
keyboard.next();
countABC++;
}
return countABC;
}
public static int WordLengthCount(int n) throws FileNotFoundException
{
File file = new File("RomeoAndJuliet.txt");
Scanner keyboard = new Scanner(new FileInputStream(file));
int count1 = 0;
int count2 = 0;
int count3 = 0;
int count4 = 0;
int count5 = 0;
int count6 = 0;
int count7 = 0;
int count8 = 0;
int count9 = 0;
int count10 = 0;
int count11 = 0;
int count12 = 0;
int count13 = 0;
int blob = 0; // so that if statement runs
while(keyboard.hasNext())
{
if (keyboard.next().length() == 1)
{
count1++;
keyboard.next();
return count1;
}
else if (keyboard.next().length() == 2)
{
count2++;
keyboard.next();
return count2;
}
else if (keyboard.next().length() == 3)
{
count3++;
keyboard.next();
return count3;
}
else if (keyboard.next().length() == 4)
{
count4++;
keyboard.next();
return count4;
}
else if (keyboard.next().length() == 5)
{
count5++;
keyboard.next();
return count5;
}
else if (keyboard.next().length() == 6)
{
count6++;
keyboard.next();
return count6;
}
else if (keyboard.next().length() == 7)
{
count7++;
keyboard.next();
return count7;
}
else if (keyboard.next().length() == 8)
{
count8++;
keyboard.next();
return count8;
}
else if (keyboard.next().length() == 9)
{
count9++;
keyboard.next();
return count9;
}
else if (keyboard.next().length() == 10)
{
count10++;
keyboard.next();
return count10;
}
else if (keyboard.next().length() == 11)
{
count11++;
keyboard.next();
return count11;
}
else if (keyboard.next().length() == 12)
{
count12++;
keyboard.next();
return count12;
}
else if (keyboard.next().length() == 13)
{
count13++;
keyboard.next();
return count13;
}
} return blob;
}
}
thanks!
Make the variable static and call it from the main method
There are a couple of things wrong in your code, but the biggest one is that you are returning the count when you find a word that has a specific Length.
You may want to create a class (say Document) that has the attributes you listed as variables in WordLengthCount (int count1, int count2, etc). Since attributes should most often be private, I would suggest doing an increment count method.
Finally, your WordLengthCount, can call the increment count method for the right word type, and return the object that you have created.
Moreover, instead of creating 13 variables, I would recommend using an array instead
int[] wordCount= new int[13];
You're trying to access local variables of one function in some other function. This is not possible. As the name suggests, local variables are local to the block or function in which they are declared. If you want to globally access these variables, make them class-level variables, i.e. declare them inside the class body but outside of any other function. Also, if you want to access them from static methods without creating object of the class, make these variables static.
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);
}
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.");
});
}
}