I have the following code which returns an error.
The line:
return first;
says:
incompatible types, required: char[]
It seems like something simple, but I can't figure it out. I am trying to display the values from invoking methodB.
Also, you will notice I have commented an if statement as #4. Can someone further my understanding a bit.
Does this if statement update the value held by the variable first IF the value held in the current element in alphas comes before the current value of first?
Hope this makes sense and someone can help. Getting late and my brain isn't working any more. Java is going to make or break me!
package openuniversity;
public class Main
{
public static void main(String[] args)
{
Main m = new Main();
char [] alp = m.methodB();
for (char b: alp)
{
System.out.println(b);
}
}
public static char[] methodB()
{
char [] alphas = {'s','a','u','s','a','g','e'};
char first = alphas[0];
for (int i= 1; i < alphas.length; i++) //3
{
if (alphas[i] < first) //4
{
first = alphas[i];
}
}
return first;
}
}
package openuniversity;
public class Main
{
public static void main(String[] args)
{
Main m = new Main();
char alp = m.methodB();
System.out.println(alp);
}
public static char methodB()
{
char [] alphas = {'s','a','u','s','a','g','e'};
char first = alphas[0];
for (int i= 1; i < alphas.length; i++) //3
{
if (alphas[i] < first) //4
{
first = alphas[i];
}
}
return first;
}
}
Your function signature says you're returning a char[]:
public static char[] methodB()
But you actually return a char:
char first = alphas[0];
// ...
return first;
It's not entirely clear what you want to do, but you need to either change the signature to return a single char:
public static char methodB()
And change where it's used:
char alp = m.methodB();
Or make methodB actually return a char[]. The problem is I don't know what it's actually supposed to return. I'd suggest giving the function a better name. You may want to take a look at Lists.
Related
Given a string S and Q queries, each query contains a string T. The task is print “Yes” if T is subsequence of S, else print “No”.
I am trying to learn algorithms and implementing them.
I have written the below code in Java :
import java.util.Stack;
public class QueriesOnStringSubsequence {
public boolean subSequence(String original, String query) {
Stack<Character> s1 = new Stack<Character>();
Stack<Character> s2 = new Stack<Character>();
for (int i = 0; i < original.length(); i++) {
s1.push(original.charAt(i));
System.out.println(s1.peek());
}
for (int i = 0; i < query.length(); i++) {
s2.push(query.charAt(i));
System.out.println(s2.peek());
}
while (!s1.isEmpty() || !s2.isEmpty()) {
Character s1Top = s1.peek();
Character s2Top = s2.peek();
if (s1Top == s2Top) {
s1.pop();
//System.out.println(i);
s2.pop();
return true;
}
System.out.print("True");
}
System.out.print("False");
return false;
}
public static void main(String[] args) {
QueriesOnStringSubsequence ob = new QueriesOnStringSubsequence();
ob.subSequence("geeksforgeeks", "gg");
}
}
I tried to debug this and in Eclipse and it won't go into the if condition. Can someone please explain where I am going wrong.
Keep in mind that Stack are LIFO data structures.
This means when you run:
Character s1Top = s1.peek();
Character s2Top = s2.peek();
You are getting the last two characters added. In this case s and g.
This means that the if statement will not be met. The second time the software loops since you are using Stack.peek the element is looked at but not changed. Therefore your while loop is looking at s and g over and over. Since they are never equal your if will never be met and therefore your while loop will be infinite.
Also you are checking:
while(!s1.isEmpty() || !s2.isEmpty())
This means both need to be empty before exiting which can cause an issue. I believe you want to use:
while(!s1.isEmpty() && !s2.isEmpty())
As duncan pointed out, a stack may not be the best data structure for this. I assume you want to go in order which means that you should use a queue.
Here is an implementation. I used better variable naming conventions which help not only in readability, but also debugging.
import java.util.*;
public class QueriesOnStringSubsequence {
public static void subSequence(String original, String query) {
Queue<Character> originalQueue = stringToQueue(original);
Queue<Character> queryQueue = stringToQueue(query);
while (!originalQueue.isEmpty() && !queryQueue.isEmpty()) {
Character originalQueueHead = originalQueue.peek();
Character queryQueueHead = queryQueue.peek();
if (originalQueueHead.equals(queryQueueHead)) {
queryQueue.poll();
System.out.print("YES");
} else {
System.out.print("NO");
}
originalQueue.poll();
System.out.print("...");
}
}
private static Queue<Character> stringToQueue(String input) {
Queue<Character> queue = new LinkedList<Character>();
for (int i = 0; i < input.length(); i++) {
queue.add(input.charAt(i));
}
return queue;
}
public static void main(String[] args) {
QueriesOnStringSubsequence.subSequence("geeksforgeeks", "gg");
}
}
YES...NO...NO...NO...NO...NO...NO...NO...YES...
I was trying to perform sorting of integers in an array and it worked fine.
But when i try to modify the program by including a "pass by reference" concept via a method, it is throwing error "cannot find symbol".
I am new to JAVA and learning by my own, Please help me with what I am doing wrong here.
import java.util.*;
import java.io.*;
public class Sort {
public static void main(String[] args) {
Sort obj = new Sort();
Scanner in = new Scanner(System.in);
int i, p, k, arr[];
arr = new int[10];
System.out.println("Enter the numbers for sorting \n");
for (i = 0; i < 5; i++) {
arr[i] = in.nextInt();
}
for (i = 0; i < 5; i++) {
for (p = 0; p < 5; p++) {
if (arr[i] < arr[p]) {
/*
* moving the below block for swapping to a new method. k =
* arr[i]; arr[i]= arr[p]; arr[p]= k;
*/
obj.swap(obj);
}
}
}
System.out.println("\n");
for (i = 0; i < 5; i++)
System.out.println(arr[i]);
}
public void swap(Sort m) {
m.k = m.arr[i];
m.arr[i] = m.arr[p];
m.arr[p] = m.k;
}
}
The error I am getting is :
"Sort.java:44: error: cannot find symbol
m.k = m.arr[i];
^
"
Similarly 10 such errors for other variables as well.
You are trying to use index variables (i and p) that don't exist in the context you are trying to use them (inside swap() method body) as well as members of Sort (k and arr) which don't exist. The scope of all these, you have limited to the method body of main():-
public void swap(Sort m) {
m.k = m.arr[i]; //No 'i' in swap(). No 'k' or 'arr' in 'm'(an instance of 'Sort')
m.arr[i] = m.arr[p]; //No 'p' in swap()
m.arr[p] = m.k;
}
Short-term Solution
Change your swap() method to
//Now accepting in i and p
public void swap(Sort m, int i, int p) {
m.k = m.arr[i];
m.arr[i] = m.arr[p];
m.arr[p] = m.k;
}
then call it like this
obj.swap(obj, i, p); //pass in i and p
and move your Sort variables to be accessible members of Sort
public class Sort {
public static int k; //now accessible with m.k
public static int[] arr = new int[10]; //now accessible with m.arr
...
}
Lastly, is it intentional that your array is 10 long but you only fill it with 5 numbers?
Pass-by-Reference
There is no "pass-by-reference" in Java. Everything is passed by value. The confusing thing is that what is passed by value is technically a reference to the object, meaning you get strange effects like you can edit the object but not reassign it.
Solution: move the stuff back from the swap method to where it was.
Alternatively, provide the necessary values as parameters to swap.
I discovered what i think is a bug whilst using netbeans. When i call up my method to sort an array containing names(ob.sort) in alphabetical order it automatically sorts another array which contains the original names when it isn't supposed to as the original names is not assigned to anything after it has been populated with input at the beginning(ob.input).
I experienced this problem whilst writing larger programs(encountered more than once), but i made a simpler one to demonstrate this problem. It looks like much as i copied the class methods an pasted it below the main class making it easier for you to trace the variables in the program.
public static void main(String args[]){
ObjectTest ob = new ObjectTest();
ob.input();
String x[] = ob.getNames();
System.out.println(x[0]);
ob = new ObjectTest(x);
System.out.println(x[0]);
ob.sort();
System.out.println(x[0]);
String y[] = ob.getNamesrt();
System.out.println(x[0]);
}
}
/*import java.io.*;
import javax.swing.*;
public class ObjectTest {
String name[];
String namesrt[];
public ObjectTest(){
name = new String[3];
namesrt = new String[3];
}
public ObjectTest(String j[]){
namesrt = j;
}
public void input(){
for(int i = 0; i < name.length; i++){
name[i] = JOptionPane.showInputDialog("Enter name");
}
}
public void sort(){
if(!(namesrt == null)){
for(int i = 0; i < namesrt.length; i++){
for(int c = i + 1; c < namesrt.length; c++){
if(namesrt[i].compareToIgnoreCase(namesrt[c]) > 0){
String n = namesrt[i];
namesrt[i] = namesrt[c];
namesrt[c] = n;
}
}
}
}
else{JOptionPane.showMessageDialog(null,"Names not received");}
}
public String[] getNames(){
return name;
}
public String[] getNamesrt(){
return namesrt;
}
public void setNames(String j[]){
name = j;
}
public void setNamesrt(String j[]){
namesrt = j;
}
}*/
I discovered what i think is a bug whilst using netbeans.
Well, it may be a bug in your code. It's not a bug in Java or in Netbeans. It's just demonstrating the fact that arrays are reference types in Java, and the way that objects work.
Here's a short but complete program demonstrating the same effect:
public class Test {
public static void main(String[] args) {
String[] x = { "hello" };
// Copy the *reference*
String[] y = x;
System.out.println(y[0]); // Prints "hello"
x[0] = "new value";
System.out.println(y[0]); // Prints "new value"
}
}
The values of x and y here are references to the same array object... so if the array is changed "through" x, that change is still visible as y[0].
If you want to make your code create independent objects, you'll want to change this:
public ObjectTest(String j[]){
namesrt = j;
}
to:
public ObjectTest(String j[]){
namesrt = j.clone();
}
(Ideally change it to declare the parameter as String[] j, or better yet fix all your variable names to be more meaningful, but that's a different matter.)
I am a beginner in java and i will like to seek some help.
Write a method called vertical that accepts a String as its parameter and prints each letter of the string on separate lines. For example, a call of vertical("hey now") should produce the following output:
h
e
y
n
o
w
This is what i have done.
public void vertical(String x){
char OneByOne='x';
for(int i=0;i<=x.length()-1;i++){
OneByOne=x.charAt(i);
}
System.out.print(OneByOne);
}
It gives me w when i call for it.
But i am confused.i create a char container and call out position 0.And loop through it.Shouldn't position 0
starts from h.Instead of giving me a w?
Also,should i use public void vertical(String x){ or public static void vertical(String x){?They give me the same output.I go research on static and they tell me static means single.What does that means?
public void vertical(String x){
int count = x.length();
for(int i=0;i<count;i++){
System.out.println(x.charAt(i));
}
}
You're not printing inside the loop. Also, use println.
you need to print char in each iteration.
public void vertical(String x){
char OneByOne='x';
for(int i=0;i<=x.length()-1;i++){
System.out.println(x.charAt(i));
}
}
In addition to the other answers: You can also use a for each loop:
public static void vertical(String x) {
for (char OneByOne : x.toCharArray()) {
System.out.println(OneByOne);
}
}
I used a more conventional style here:
public void vertical(String x){
for(int i = 0; i < x.length(); i++){
char oneByOne = x.charAt(i);
System.out.println(oneByOne);
}
}
Less than length, i.o. less-equals length - 1.
Local declaration. Vars starting with small letter.
The rest is fine. charAt(i) gives the i'th char, just as conceived.
You should use prinln instead of print
System.out.println(OneByOne);
static keyword means you're able to call this method without having an instance of your class.
package abcde;
public class Abcde{
public static void main(String[] args){
System.out.println(recursion(97));
}
public static int recursion (int n) {
for ( int i = n; i< 123; i++)
{
String achar = new Character((char)i).toString();
System.out.print(achar);
}
return -1;
}
}
The desired output has to be abcdefghijklmnopqrstuvwxyz while the output is abcdefghijklmnopqrstuvwxyz-1
I dont want the -1 at the end.
When i change the input type to void, the method does not work.
What can we do about it?
The final -1 gets printed outside the recursion method: main() prints what recursion returns, which happens to be -1.
If you change the return type of recursion to void, you need to call it as a method, not as an expression. In other words, you can no longer call println(recursion(97)) because println expects a value to print.
As a side note, in order to be recursive a method needs to have a code path that calls the same method, directly or indirectly. Since the "calling itself" feature is missing from your recursion method, consider renaming it to iteration.
rewrite it to:
public static void main(String[] args){
noRecursion(97);
}
public static void noRecursion (int n) {
//^^^^
for (int i = n; i< 123; i++) {
System.out.print((char)i);
}
}
Actually, your recursion function doesn't return anything but -1, but It does print all of the other characters before it returns.
if you change it to
public static void notRecursion (int n) {
for ( int i = n; i< 123; i++)
{
String achar = new Character((char)i).toString();
System.out.print(achar);
}
}
and then just call it from your main like
notRecursion(97);
It will print what you want it to print
Or
public static String recursion (int n)
{
if(n >97 +1)
{
System.out.print(recursion(n-1));
}
String achar = new Character((char)n).toString();
return(achar)
}
and then call it with
System.out.println(recursion(123));
Choose pure functions over side effects:
public static String iteration (int n) {
final StringBuilder b = new StringBuilder();
for (char c = (char)n; c < 123; c++)
b.append(c);
return b.toString();
}
Now you can call this method as you are calling it now, and print its result.