ArrayList java program without using generics - java

I had been given an assignment to implement ArrayList and LinkedList without using generics. The problem is with the insertnode() method. Though I try to read from commandline using a scanner, the method returns without waiting.
import static java.lang.System.out;
import java.util.Scanner;
class Arraylist
{
public static final int LIST_SIZE=30;
static Scanner input = new Scanner(System.in);
static Object list[];
static int top = -1;
static int typeoflist;
public static void displaymenu()
{
int choice;
do{
out.print("\n Basic operations on a linked list:");
out.print("\n 1. Create list \n 2. Insert node \n 3. Delete node \n 4. Modify node \n 5. Search value \n 6. Print list\n Else. Exit \n Choice:");
choice = input.nextInt();
switch(choice)
{
case 1:
list = createlist();
break;
case 2:
insertnode();
break;
case 3:
//deletenode();
break;
case 4:
//modifynode();
break;
case 5:
//searchnode();
break;
case 6:
printlist();
break;
default:
return;
}
}while(true);
}
public static Object[] createlist()
{
int typeoflist;
out.println("Enter your choice of list datatype: \n 1. int \n 2. float \n 3. char \n 4. String \n 5. UserDefined \n Choice:");
typeoflist = input.nextInt();
switch(typeoflist)
{
case 1:
list = new Integer[LIST_SIZE];
break;
case 2:
list = new Float[LIST_SIZE];
break;
case 3:
list = new Character[LIST_SIZE];
break;
case 4:
list = new String[LIST_SIZE];
break;
}
return (Object[])list;
}
public static void insertnode()
{
Object o;
top++;
out.println("Enter the value to insert:");
switch(typeoflist)
{
case 1:
o = (Integer)input.nextInt();
list[top] = o;
break;
case 2:
o = (Float)input.nextFloat();
list[top] = o;
break;
case 3:
//o = (Character)input.next(); //
//list[top] = o;
break;
case 4:
o = (String)input.next();
list[top] = o;
break;
}
}
public static void printlist()
{
for(int i =0; i<top; i++)
{
out.println(list[i]);
}
}
public static void main(String[] args)
{
displaymenu();
}
}

Hint: typeoflist in createList() is hiding the static member variable.

Related

How do I go back to my previous menu?

I've looked at everything mentioned about this and if I make a do/while loop it will just repeat the selection. If I make them conditionals instead of a switch it gives me "NoSuchElementException: No line found". Now its also giving me a "NoSuchElementException: No line found" even though I am back to a switch. I just want to know what I'm missing in this code that will let the user back out their first selection (while loop) to make a different one. Here is the code:
public class Zoo {
static FileRead fr = new FileRead();
private static final Scanner scnr = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException {
while (true) {
int userChoice = menu();
while (userChoice == 1) {
// Select Animal
int animal = animalSelect();
String Name = null;
switch (animal) {
case 1:
Name = "Animal - Lion";
break;
case 2:
Name = "Animal - Tiger";
break;
case 3:
Name = "Animal - Bear";
break;
case 4:
Name = "Animal - Giraffe";
break;
default:
userChoice = menu();
break;
} FileRead.readAnimal(Name);
}
while (userChoice == 2) {
// Select Habitat
int animal = habitatSelect();
String Name = null;
switch (animal) {
case 1:
Name = "Habitat - Penguin";
break;
case 2:
Name = "Habitat - Bird";
break;
case 3:
Name = "Habitat - Aquarium";
break;
default:
userChoice = menu();
break;
}
FileRead.readHabitat(Name);
}
// Exit Program
if (userChoice == 3) {
System.out.println("Thank you!");
System.exit(0);
}
// Error for invalid option
else {
System.out.println("ERROR: Invalid Selection");
}
}
}
private static int habitatSelect() {
// Habitat Menu
System.out.println("Which habitat would you like to monitor?");
System.out.println("1. Penguin Habitat");
System.out.println("2. Bird Habitat");
System.out.println("3. Aquarium");
System.out.println("4. Exit");
int userChoice = Integer.parseInt(scnr.nextLine());
return userChoice;
}
private static int animalSelect() {
// Animal Menu
System.out.println("Which animal would you like to monitor?");
System.out.println("1. Lion");
System.out.println("2. Tiger");
System.out.println("3. Bear");
System.out.println("4. Giraffe");
System.out.println("5. Exit");
int userChoice = Integer.parseInt(scnr.nextLine());
return userChoice;
}
private static int menu() {
// Main Menu
System.out.println("WELCOME! Plese choose from the following");
System.out.println("1. Monitor Animal");
System.out.println("2. Monitor Habitat");
System.out.println("3. Exit");
int userChoice = Integer.parseInt(scnr.nextLine());
return userChoice;
}
}
This all reads a from another file in the package. If that code is needed I will also post it.
Tweak your main method as below
public static void main(String[] args) throws FileNotFoundException {
while (true) {
int userChoice = menu();
switch (userChoice) {
case 1: // only for animals
int animal = animalSelect();
String Name = null;
switch (animal) {
case 1:
Name = "Animal - Lion";
break;
case 2:
Name = "Animal - Tiger";
break;
case 3:
Name = "Animal - Bear";
break;
case 4:
Name = "Animal - Giraffe";
break;
default:
System.out.println("ERROR: Invalid Selection");
break;
}
if (Name != null) // read file only if selection is correct
FileReader.readAnimal(Name);
break;
case 2: // only for habitat
int habitat = habitatSelect();
String habitatName = null;
switch (habitat) {
case 1:
habitatName = "Habitat - Penguin";
break;
case 2:
habitatName = "Habitat - Bird";
break;
case 3:
habitatName = "Habitat - Aquarium";
break;
default:
System.out.println("ERROR: Invalid Selection");
break;
}
if (habitatName != null) // read file only if selection is correct
FileRead.readHabitat(habitatName);
break;
case 3 : // only for exit
System.out.println("Thank you!");
System.exit(0);
default:
System.out.println("ERROR: Invalid Selection");
}
}
}
Thus after each sub-menu, the user is returned to the main menu. As for your exception, for now I have added a null check so that the file is read only if the selection is correct.
Also, note that the above code doesn't contain nested loop which increases the performance and also excludes (the slightly messy) recursive call.

Storing value into another class after a switch statement and reuse the variable in another switch statement

So basically in the case 1 of main function, I am trying to store the two values the user input into another class. Then if I go to case 2 immediately, the output will be the sum of the two values that were input earlier. My question is how to change my code such that case 2 and 3 are able to use the values that I have stored in case 1 earlier? Thank you.
Code for main function:
import java.util.Scanner;
public class calculatorfinal
{
public static void main(String args[])
{
int number1,number2,choice,sum,product;
while(true)
{
Scanner scan = new Scanner(System.in);
operations myoperations=new operations();
System.out.println("\n1. Get numbers");
System.out.println("\n2. Addition");
System.out.println("\n3. Multiplication");
System.out.println("\n4. Exit");
choice = scan.nextInt();
switch(choice)
{
case 1:
System.out.println("enter the two numbers:");
number1=scan.nextInt();
number2=scan.nextInt();
myoperations.getnumbers(number1,number2);
break;
case 2:
myoperations.addnumbers();
break;
case 3:
myoperations.multiplynumbers();
break;
case 4:
System.exit(0);
break;
}
}
}
}
Code for another class(the operations)
public class operations
{
int a,b;
public void addnumbers()
{
int sum = a+b;
System.out.println("ans is "+sum);
}
public void multiplynumbers()
{
int product = a*b;
System.out.println("ans is "+product);
}
public void getnumbers(int number1,int number2)
{
a=number1;
b=number2;
System.out.println("the first number is "+number1);
System.out.println("the second number is "+number2);
}
}
The problem is that you discard your variable myoperations every time the while-loop ends and creating a new myoperations. Your variable has to stay outside the loop like your ints do. Also the Scanner should stay outside, as long as you do not want to let the garbage collector work unnecessarily.
public static void main(String args[]) {
int number1, number2, choice, sum, product;
operations myoperations = new operations();
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("\n1. Get numbers");
System.out.println("\n2. Addition");
System.out.println("\n3. Multiplication");
System.out.println("\n4. Exit");
choice = scan.nextInt();
switch (choice) {
case 1:
System.out.println("enter the two numbers:");
number1 = scan.nextInt();
number2 = scan.nextInt();
myoperations.getnumbers(number1, number2);
break;
case 2:
myoperations.addnumbers();
break;
case 3:
myoperations.multiplynumbers();
break;
case 4:
System.exit(0);
break;
}
}
}
You just have to use the initialisation operations myoperations=new operations(); outside of the while loop. Otherwise you override the instance of the class each time. And so your stored values get lost each time you choose a case.
1.Make your instance variable static to avoid reinitialization
import java.util.Scanner;
class operations
{
static int a,b; //Add static KeyWord
public void addnumbers()
{
int sum = a+b;
System.out.println("ans is "+sum);
}
public void multiplynumbers()
{
int product = a*b;
System.out.println("ans is "+product);
}
public void getnumbers(int number1,int number2)
{
a=number1;
b=number2;
System.out.println("the first number is "+number1);
System.out.println("the second number is "+number2);
}
}
2.Write operations myoperations=new operations(); line out of while loop
class Main {
public static void main(String args[])
{
int number1,number2,choice,sum,product;
Scanner scan = new Scanner(System.in);
operations myoperations=new operations();
while(true)
{
//Scanner scan = new Scanner(System.in);
//operations myoperations=new operations();
System.out.println("\n1. Get numbers");
System.out.println("\n2. Addition");
System.out.println("\n3. Multiplication");
System.out.println("\n4. Exit");
choice = scan.nextInt();
switch(choice)
{
case 1:
System.out.println("enter the two numbers:");
number1=scan.nextInt();
number2=scan.nextInt();
myoperations.getnumbers(number1,number2);
break;
case 2:
myoperations.addnumbers();
break;
case 3:
myoperations.multiplynumbers();
break;
case 4:
System.exit(0);
break;
}
}
}
}

Keep getting error: '.class' expected line 40 [duplicate]

This question already has an answer here:
What does "error: '.class' expected" mean and how do I fix it
(1 answer)
Closed 4 years ago.
import java.util.*;
public class Lab04B {
public static String toMeters (int unitNumber) {
String value;
switch (unitNumber) {
case 1:
value = "Meter";
break;
case 2:
value = "Nautical mile";
break;
case 3:
value = "Furlong";
break;
case 4:
value = "Mil";
break;
case 5:
value = "Rod";
break;
case 6:
value = "Vershok";
break;
case 7:
value = "Sheppey";
break;
case 8:
return 1.702;
default:
return -1;
}
{
public static double fromMeters (int unitNumber)
{
switch (unitNumber)
{
case 1:
return 1;
case 2:
return 1/1852.0;
case 3:
return 1/201.168;
case 4:
return 1/0.0254;
case 5:
return 1/5.029;
case 6:
return 1/0.04445;
case 7:
return 1/1408.0;
case 8:
return 1/1.702;
default:
return -1;
}
{
public static String getUnitName (int unitNumber)
{
String value;
switch (unitNumber)
{
case 1:
value = "Meter";
case 2:
value = "Nautical mile";
case 3:
value = "Furlong";
case 4:
value = "Mil";
case 5:
value = "Rod";
case 6:
value = "Vershok";
case 7:
value = "Sheppey";
case 8:
value = "Smoot";
default:
value = "faulty input";
}
{
public static void main (String[] args)
Scanner input = new Scanner (System.in);
System.out.println("Converting Measurements");
System.out.println("By: Ashleigh Pacewicz");
System.out.println("1.\tMeter");
System.out.println("2.\tNautical Mile");
System.out.println("3.\tFurlong");
System.out.println("4.\tMil");
System.out.println("5.\tRod");
System.out.println("6.\tVershok");
System.out.println("7.\tSheppey");
System.out.println("8.\tSmoot");
System.out.println("From what unit would you like to convert? ");
int = input.nextInt();
System.out.println("To what unit would you like to convert? ");
int = input.nextInt();
System.out.print("What measurement would you like to convert? ");
double = input.nextDouble();
}
}
}
I am just learning how to code. I'm trying to write a program to convert meters but I keep receiving error on line 40 and line 63 and line 96. Error:
'.class' expected.
What am I doing wrong?
First of all
int = input.nextInt();
System.out.println("To what unit would you like to convert? ");
int = input.nextInt();
You didn't give them a name
and look at your braces
}
{
public static String getUnitName (int unitNumber)
{
It's the same at every method
it should be like this
public void methodName() {
}
but you're doing this
{
public void methodName()
{
and you forgot breaks;
1 more thing you should really use an IDE
I want to be honest. I do not know why you are getting this error...
I've just copied your code and compiled. After removing 2 to 3 braces and adding one, your code compiled without errors. I'm sure you are getting the error, you pasted into your question, from somewhere else.
You have to apply some fixes:
System.out.println("To what unit would you like to convert? ");
int NAME_YOUR_VARS = input.nextInt();
And in a few places you are placing open braces infront of method headers:
{
public static double fromMeters(int unitNumber){
Or you forgot to close method bodys:
public static String toMeters (int unitNumber) {
switch(unitNumber) {
/* case statements were cut out here*/
}
//<- Here you forgot a brace!
Keeping track of code blocks and brace placing is very important!

Stuck in Vector in Java

I created a string vector and I want to store the selected type of coffee in the vector, for example if I choose number 3,4,5 and 1, store them in Vector1 the variables ("LATTE", "AMERICAN", "CAPUCCINO" and "MOKA") and print those stored names, but the problem is that it just prints, number 6 "BLACK", always.
import java.io.*;
class Exercise{
public static void main (String[] args) throws java.io.IOException {
DataInputStream receivedata= new DataInputStream(System.in);
String keyboard;
int seleccafe,n=0,contvector=0;
String []Vector1=new String[200];
do{
System.out.println("\n1. MOKA");
System.out.println("2. EXPRESO");
System.out.println("3. LATTE");
System.out.println("4. AMERICAN");
System.out.println("5. CAPUCCINO");
System.out.println("6. BLACK");
System.out.println("0. OUT");
System.out.print("\nTYPE THE NUMBER: ");
seleccafe=Read_Da("");
SelectCo(Vector1,seleccafe,n);
contvector++;
n++;
if(seleccafe==0) break;
}while(true);
for(int i=0; i<contvector-1; i++){
System.out.println(Vector1[i]);
}
}
public static int Read_Da (String TxtMsg) throws java.io.IOException{
int X=0;
String keyboard;
DataInputStream reveivedata= new DataInputStream(System.in);
do{
System.out.print("");
keyboard=reveivedata.readLine();
try{
X=Integer.parseInt(keyboard);
if(X<0){
System.out.println("SELECT JUST 0+");
continue;
}
return X;
}catch(NumberFormatException e){
System.out.println("JUST NUMBERS");
}
}while(true);
}
public static void SelectCo(String xVector[], int xseleccafe, int xi){
switch(xseleccafe){
case 1:
xVector[xi]= "MOKA";
case 2:
xVector[xi]="EXPRESSO";
case 3:
xVector[xi]="LATE";
case 4:
xVector[xi]="AMERICAN ";
case 5:
xVector[xi]="CAPUCCINO";
case 6:
xVector[xi]="BLACK";
}
}
}
Any help? Thanks!
Your problem is that you are missing the word break; after each case clause in SelectCo, so each case is "falling through" to the one below, and finishing with case 6:.
It should look like this.
switch(xseleccafe){
case 1:
xVector[xi]= "MOKA";
break;
case 2:
xVector[xi]="EXPRESSO";
break;
case 3:
xVector[xi]="LATE";
break;
case 4:
xVector[xi]="AMERICAN ";
break;
case 5:
xVector[xi]="CAPUCCINO";
break;
case 6:
xVector[xi]="BLACK";
break;
default:
xVector[xi]="UNKNOWN";
}
More detail here

Java calculator switch dont work

I can enter 2 numbers but when I enter an integer for "wahl" (the switch) the result is wrong.
import java.util.Scanner;
public class taschenrechner {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Bitte erste Zahl eingeben:");
int a = s.nextInt();
System.out.println("Bitte zweite Zahl eingeben:");
int b = s.nextInt();
System.out.println("1.+ \n 2.- \n 3.* \n 4. /");
int wahl = s.nextInt();
switch(wahl){
case 1:
addieren(a,b);
break;
case 2:
subtrahieren(a,b);
break;
case 3:
multiplizieren(a,b);
break;
case 4:
dividieren(a,b);
break;
}
System.out.println("Bye Bye World");
}
private static int addieren(int a, int b){
int c = a + b;
return c;
}
private static int subtrahieren(int a, int b){
int c = a - b;
return c;
}
private static int multiplizieren(int a, int b){
int c = a * b;
return c;
}
private static int dividieren(int a , int b){
int c = a / b;
return c;
}
}
Maybe some method leaks?
I wanted to do this with methods and the return function to practice a bit java.
Your methods return int, but you don't seem to use the result and call them as void instead.
Try testing in your switch cases with something like:
System.out.println(multiplizieren(a,b));
It will print the result to sdtout.
Also note that as per both Java and SO convention, code should all be in English (although it's quite clear in this case).
If you want to see the result, use the returned value from the methods in a new variable in main (say, result) or print out the result inside the methods using System.out.println() or something of the sort. For example like this:
int result = 0;
case 1:
result = addieren(a,b);
break;
case 2:
result = subtrahieren(a,b);
break;
case 3:
result = multiplizieren(a,b);
break;
case 4:
result = dividieren(a,b);
break;
}
System.out.println("Result = " + result);
you just return the result...
you have to print the result, too
int result = 0
switch(wahl){
case 1:
result = addieren(a,b);
break;
case 2:
result = subtrahieren(a,b);
break;
case 3:
result = multiplizieren(a,b);
break;
case 4:
result = dividieren(a,b);
break;
}
System.out.println(result)
If you are returning the result then you should put it in some valriable or can directly display by s.o.println
like...
switch(wahl){
case 1:
system.out.println(addieren(a,b));
or
int result = addieren(a,b)
system.out.println(result);
int result = 0
switch(wahl){
case 1:
result = addieren(a,b);
break;
case 2:
result = subtrahieren(a,b);
break;
case 3:
result = multiplizieren(a,b);
break;
case 4:
result = dividieren(a,b);
break;
}
//Print the result using a syso
System.out.println(result)
OK here are a couple of pointers that might be useful:
import java.util.Scanner;
// Class names typically start with a capital letter, good practice to get accustomed to
public class Taschenrechner {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Bitte erste Zahl eingeben:");
int a = s.nextInt();
System.out.println("Bitte zweite Zahl eingeben:");
int b = s.nextInt();
System.out.println("1.+ \n 2.- \n 3.* \n 4. /");
int wahl = s.nextInt();
switch(wahl){
case 1:
addieren(a,b); // <- nothing happens to the result!!
break;
case 2:
subtrahieren(a,b); // <- nothing happens to the result!!
break;
case 3:
multiplizieren(a,b); // <- nothing happens to the result!!
break;
case 4:
dividieren(a,b); // <- nothing happens to the result!!
break;
default: // <- always good to have a default in a switch
// warn user that invalid option is entered
}
System.out.println("Bye Bye World");
}
// dont need the integer "c" as you never use it locally.
private static int addieren(int a, int b){
retrun a + b;
}
private static int subtrahieren(int a, int b){
return a - b;
}
private static int multiplizieren(int a, int b){
return a * b;
}
private static int dividieren(int a , int b){
return a / b;
}
}
I suppose you made the 4 operation methods static, since you call it in main, and the compiler complains about static reference? If so, read a bit about what static means; and consider creating an instance of your calculator by:
supplying a constructor method, and
creating an instance of it in your main something like:
Taschenrechner t = new Taschenrechner();
t.addieren(a,b); //the methods don't need to be static anymore :)
Hope it helps
You can use this example
package com.alindal.calc;
import java.util.Scanner;
public class Calc {
public static void main(String[] args) {
System.out.println("Select an option : \n 1:Addition 2:Subtraction 3:Multiplication 4: Division");
// TODO Auto-generated method stub
Scanner read=new Scanner(System.in);
int x=read.nextInt();
switch(x)
{
case 1:
add();
break;
case 2:
sub();
break;
case 3:
multi();
break;
case 4:
div();
break;
default:
System.out.println("Invalid choice");
}
}
public static void add()
{
Scanner read=new Scanner(System.in);
System.out.println("Enter the values a and b");
int a=read.nextInt();
int b=read.nextInt();
int c=a+b;
System.out.println("The sum is "+c);
}
public static void sub()
{
System.out.println("Enter the values a and b");
Scanner read=new Scanner(System.in);
int a=read.nextInt();
int b=read.nextInt();
int c=a-b;
System.out.println("The difference is "+c);
}
public static void multi()
{
System.out.println("Enter the values a and b");
Scanner read=new Scanner(System.in);
int a=read.nextInt();
int b=read.nextInt();
int c=a*b;
System.out.println("The product is "+c);
}
public static void div()
{
System.out.println("Enter the values a and b");
Scanner read=new Scanner(System.in);
int a=read.nextInt();
int b=read.nextInt();
int c=a/b;
System.out.println("The division is "+c);
}
}

Categories