java extended class inheritance [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Sum s = new Sum();
Sum.SetToZero z = new Sum.SetToZero();
Scanner input = new Scanner(System.in);
String read = input.nextLine();
while (!read.equals("end")) {
if (read.equals("add")) {
s.add()
}
else if (read.equals("get")) {
System.out.println(s.returnTotal());
}
else if (read.equals("zero")) {
z.zero();
}
read = input.nextLine();
}
class:
public class Sum {
int total = 0;
public void add() {
total += 1;
}
public int returnTotal() {
return total;
}
public static class SetToZero extends Sum {
public void zero() {
total = 0;
}
}
}
input:
add
add
zero
add
get
add
get
end
output:
3
4
output wanted:
1
2
Shouldn't the subclass inherit the total and set it to zero? What am I doing wrong? I know I could just move the zero into the main class but I want it to be in a separate class. thx for your help.

By making your total variable static, you can get the desired output.
class Sum {
static int total = 0;
public void add() {
total += 1;
}
public int returnTotal() {
return total;
}
public static class SetToZero extends Sum {
public void zero() {
total = 0;
}
}
}

Apart from things pointed out in names like not using lowecase letters to start your class name; I think the reason why it's not working is because you're using two different variable instances for Sum and Sum.SetToZero. You don't need to create a new variables since SetToZero has all the attributes of Sum. I think you should change this:
Sum s = new Sum();
Sum.SetToZero z = new Sum.SetToZero();
Sum.SetToZero s = new Sum.SetToZero(); // use s for all operations
Here is how your modified main method would look:
public static void main(String[] args) {
Sum.SetToZero s = new Sum.SetToZero();
Scanner input = new Scanner(System.in);
String read = input.nextLine();
while (!read.equals("end")) {
if (read.equals("add")) {
s.add();
}
else if (read.equals("get")) {
System.out.println(s.get());
}
else if (read.equals("zero")) {
s.zero();
}
read = input.nextLine();
}
}
When I ran this, I saw expected output:
src : $ java Sum
add
add
zero
add
get
1
add
get
2
end

Related

How do I save an output from a method to use it in a different method?

Im sorry if this question has been asked a lot. Im still pretty new to programming and obviously have some issues in phrasing questions/searching for answers.
I want to do the following:
My algorithm includes 2 methods. One has the task to find out how many of the numbers between 0 to 30 are even and which one are not. I want those even numbers to be somehow stored and redirected to my second method to get added. How can I store those even numbers?
My code looks currently like this: (not even close to being finished)
public class Add
{
static long method(long end)
{
long number = even;
return;
}
static long even() {
if (i%2 == 0) { // even
}
else { // uneven
}
}
public static void main(String[ ] args)
{
int number = method(30);
System.out.println("");
}
}
edit:Im having formating problems... Im sorry the code looks even harder to understand. Im trying to fix it this instant.
Like it was said in the comments, add them to a list, then iterate the list while updating a variable that will be the sum of the even numbers.
public class Add {
private static ArrayList<Integer> evenNums = new ArrayList<>();
private static void evenNumbers(int max) {
for (int i = 0; i < max; i++) {
if (i % 2 == 0) {
evenNums.add(i);
}
}
}
private static int sum(ArrayList<Integer> array){
int sum = 0;
for(int i = 0; i < array.size(); i++){
sum = sum + i;
}
return sum;
}
public static void main (String[]args){
evenNumbers(30);
int sum = sum(evenNums);
System.out.println(sum);
}
}

Create an array checking previous items in another array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm trying to create an array of numbers, starting from a big number, which is a string, and then splited to create an array.
This array has numbers from 1 to 6.
I want to create a new array of 29 items, checking the last 3 items. For instance, if the current item to add is number 4, it will check for item 3, 2, and 1. I want it to check if any of the other 3 items are the same as the current, and if is the same, it will skip to next number.
The idea, is not to have repeated numbers in a "range" of 4 items.
I also want to do another thing, and is that if the current item is number 1, it would check the last 6 items, instead of just the last 3. Only when the item is number 1. I just haven't found a way to do it.
I hope someone could help me.
Here's the current code:
import java.io.*;
import java.util.*;
public class Randomizer {
public static String numbers = "1632544362511653244213652164535316243164251654235231465312645164233462153465124361522316545326412354165412633214654531626513246124351423565431623162453625412564325134634562136145256142342365161423542563151426325146335241613645225431656324164351215263453642123416561345264215321536436451243156263542125631415624314536235124662145152436352164436512645312264315432651216345624315421563516423465213614352621543342516352614";
public static void main(String[] args) {
show("\n");
String[] nums = numbers.split("(?!^)"), finalNums = new String[29];
for (int i = 0; i < finalNums.length; i++) {
finalNums[i] = newnumber(nums, i);
}
for (String num : finalNums) {
show(num + "-");
}
}
public static String newnumber(String[] array, int start) {
String num = "x";
String act = array[start];
for (int i = start; i < array.length; i++) {
int a = start - 1, b = start - 2, c = start - 3, d = start - 4;
if (a >= 0 && b >= 0 && c >= 0 && d >= 0) {
String na = array[a], nb = array[b], nc = array[c], nd = array[d];
if (act != na && act != nb && act != nc && act != nd) {
num = act;
} else {
}
} else {
num = act;
}
}
return num;
}
public static void show(String s) {
System.out.print(s);
}
public static void show(int s) {
System.out.print(s);
}
public static void show(float s) {
System.out.print(s);
}
public static void show(double s) {
System.out.print(s);
}
}
The output is:
1-6-3-2-5-4-4-3-6-2-5-1-1-6-5-3-2-4-4-2-1-3-6-5-2-1-6-4-5
What I expect to get is something like:
1-6-3-2-5-4-6-1-2-5-3-4-6-5-1-2-5-4-6-3-2-1-2-4-5-6-3-2-1

Assigning Values to Class Variables From an Input String [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
How to take input string line from a user and assign it to the class variables?
This is my class:
public class MyClass {
String name;
int age;
int ph_no;
}
Suppose the user inputs something like Adrian 23 98765432, my program should assign Adrian to name, and so on. Is there any way to do this?
Please note that the user may also provide something like this:
23 Adrianne 98765432 and I have to make sure the String provided is mapped to the respective variables.
You can try out with this, but its just for sample. There could be many tweaks to break the code. So you have to put in some more stuffs to make it unbreakable.
BufferedReader text = new BufferedReader(new InputStreamReader(
System.in));
String text2 = text.readLine();
String[] arr = text2.split(" ");
for (String string : arr) {
try {
if (string.length() < 3) {
age = Integer.parseInt(string);
} else
ph_no = Integer.parseInt(string); // supposing phno is below integer range
} catch (Exception e) {
name = string;
}
}
System.out.println("NAME ->" + name);
System.out.println("AGE ->" + age);
System.out.println("PHNO ->" + ph_no);
Try this... where split is the input String:
public class MyClass
{
String name;
int age;
int ph_no;
public static void main(String[] args)
{
//Get string input equal to the variable "str"
String[] pieces = str.split("\\s+");
Boolean[] isNumber = new Boolean[pieces.length];
for(int i=0; i<isNumber.length; i++)
{
boolean[i] = isInteger(pieces[i]);
}
for(int i=0; i<pieces.length; i++)
{
if(boolean[i] && pieces[i] > 200)
ph_no = pieces[i];
else if(boolean[i] && pieces[i] < 200)
age = pieces[i];
else
name = pieces[i];
}
}
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
}
return true;
}
This code works under the assumption that your age is less than 200 and the phone number is greater than 200 or more likely more than 3 digits.

java generics: defining objects [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to learn Java and having trouble understanding generics. I'm attempting to define an object of Integer data type, then use the object to to call a generic method.
Guided by the API and some web resources, I've been trying all sorts of things but I don't know if i'm on the right track in terms of simply defining the object.
SearchSortAlgorithms.java:
public class SearchSortAlgorithms<T> implements SearchSortADT<T>
{
public void quickSort(T[] list, int length)
{
recQuickSort(list, 0, length - 1);
}
}
TestQuickSort.java
public class TestQuickSort
{
static void main(String [] args)
{
// define an Integer array of 50000 elements
Integer[] anArray = new Integer[5000];
// load the array with random numbers using
// a for loop and Math.random() method - (int)(Math.random()*50000)
for (int i = 0; i < anArray.length; i++) {
anArray[i] = (int)(Math.random() * i);
}
// define an object of SearchSortAlgorithm with Integer data type
// use this object to call the quickSort method with parameters: your array name and size-50000
Integer aSortedArray = new Integer(5000);
public void quickSort(anArray, 5000) {
TestQuickSort<Integer> aSortedArray = new TestQuickSort<Integer>();
return aSortedArray.quickSort(anArray, 5000);
}
// print out the first 50 array elements with a for loop
// they have to be sorted now
for (int k = 0; k <= 50; k++) {
System.out.print(aSortedArray[k] + " ");
}
}
}
Errors on these lines:
public int TestQuickSort () {
TestQuickSort<Integer> aSortedArray = new TestQuickSort<Integer>();
aSortedArray = quickSort(anArray, 5000);
}
-Illegal start of expression: I wonder if my attempt at creating the constructor is right
-; expected
Ignoring any other potential errors in your code (or due to its presentation to us here), you are attempting to declare another method in main.
public int SearchSortAlgorithm () {
TestQuickSort<Integer> aSortedArray = new TestQuickSort<Integer>();
aSortedArray = quickSort(anArray, 5000);
}
This needs to be moved out of main. And also fixed to actually return an int. And main's signature should be public static void main(String[] args).
Although, it should really be returning an int[] instead...
public static int[] searchSortAlgorithm (final int[] anArray) {
TestQuickSort<Integer> aSortedArray = new TestQuickSort<Integer>();
return quickSort(anArray, 5000);
}
...and called in your main method like this...
int[] aSortedArray = searchSortAlgorithm(anArray);
for (int k = 0; k <= 50; k++) { // would be better to use aSortedArray.length
System.out.print(aSortedArray[k] + " ");
}

Binary to Decimal Conversion in Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am trying to write a program in java which takes decimal number as an int parameter and prints to the screen the binary equivalent of that decimal number ...
In short decimal to binary conversion using only int parameters ...
Solution will be much appreciated ... i have tried some steps but i am not successful ..
Thanks
Integer.toString(input, 2);
OR
Integer.toBinaryString(input);
You might also want checkout:
Integer.toHexString
Integer.toOctalString
INPUT : 10 (decimal)
RESULT: 1010 (binary)
Hope this helps :)
Or you can write program like this (modify it):
import java.util.Scanner;
public class DecToBinary {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int broj;
System.out.print("Enter number that you want to conver to binary: ");
broj = input.nextInt();
convert(broj);
}
public static void convert(int a) {
String obrnuti = "";
while (a > 0) {
int x = a % 2;
obrnuti += x;
a /= 2;
}
System.out.println(reverse(obrnuti));
}
public static String reverse(String a) {
String novi = "";
for (int i = a.length() - 1; i >= 0; i--) {
char c = a.charAt(i);
novi += c;
}
return novi;
}
}
conversion from decimal to binary :
Integer.toBinaryString(Int_variable)
conversion from binary to decimal:
Integer.parseInt(string_binary_variable,2)
public class DecimalToBinary
{
// 5 = 101
public static void main(String[] args)
{
int d2b = dec2Bin(5);
System.out.println(d2b);
}
public static int dec2Bin(int num){
int a = num;
int binary=0;
int i=1;
while(a != 0){
binary = binary+i*(a%2);
a = a/2;
i=i*10;
}
return binary;
}
}
public class BinaryToDecimal {
public static void main(String[] args) {
String binary = "110";
System.out.println(binToDec(binary));
}
public static int binToDec(String binary){
int decimal=0;
for(int i=0;i<binary.length();i++){
decimal = 2*decimal + Integer.parseInt("" + binary.charAt(i));
}
return decimal;
}
}

Categories

Resources