entering multiple values in link list in java - java

Using LinkedList I want to access the data members of the class StudData. StudData should have an array of object. This code doesn't show errors but doesn't execute successfully either.
import java.util.LinkedList;
import java.util.Scanner;
public class StudData {
public int roll_no;
public String name;
private Scanner sc;
void enter() {
sc = new Scanner(System.in);
System.out.println("enter:");
sc.nextInt(roll_no);
sc.next(name);
}
public static void main(String[] args) {
StudData p= new StudData();
LinkedList <StudData> ll=new LinkedList<StudData>();
for (int i=0; i<20; i++) {
p.enter();
ll.add(p);
}
}
}

The code shared should compile ideally. But there would be a possible exception at:
sc.nextInt(roll_no); // roll_no is 0 by default
Hence this would throw an java.lang.IllegalArgumentException: radix:0. In case you want to take roll_no as an input from user, you can change the code to:
roll_no = sc.nextInt();

It looks to me like you made a mistake (although I am on the train working with my phone)
sc.nextInt(roll_no);
sc.next(name);
Should be:
roll_no = sc.nextInt();
name = sc.next();
The variables can't be set by passing them as arguments, because a String is immutable and an int is a primitive.

Related

How to write a method that stores words backward in an arraylist received from user input until "done" is entered?

Write a method that continuously reads words from a user until the word entered is “done” and stores each word spelled backwards in an ArrayList in the order they were entered.
This is the code I have so far but whenever I try to call it in my main class it keeps failing. Can someone please help me? I have included both the class in which I am creating my method and the main class in which it is called. I cannot combine these two classes so I need to be able to call the object from todo in my main class. Thanks in advance!
Sample input: banana racecar puppy done
Resulting ArrayList: ananab racecar yppup
import java.util.Scanner;
import java.util.ArrayList;
public class todo extends main{
public ArrayList <String>storeBackwards (Scanner keyboard) {
ArrayList<String> words=new ArrayList ();
ArrayList<String> backwards=new ArrayList();
String input=keyboard.next();
while(!input.equalsIgnoreCase("done")) {
words.add(input);
String get="";
String back="";
for(int i=0; i<words.size();++i) {
get=words.get(i);
for(i=get.length()-1; i>=0; i--) {
back=back+get.charAt(i); }
backwards.add(back);
}
}
return backwards;
}
}
This is the main class
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner keyboard=new Scanner(System.in);
todo x=new todo();
x.storeBackwards(keyboard);
}
}
Here in your code String input=keyboard.next(); you are calling the keyboard.next() only once. So the value of the String variable input is unchanged after the first token is read.
So it results in the Infinite Loop and thats the reason you are getting the Exception
And the loop variable used in both of the for loops is int i, Use the different variable like int j for the nested for loop
for(int j=get.length()-1; j>=0; j--) {
back=back+get.charAt(j);
}
After modification of Your code as below, your test case got cleared
public List<String> storeBackwards (Scanner keyboard) {
ArrayList<String> backwards=new ArrayList<String>();
String input=keyboard.next();
while(!input.equalsIgnoreCase("done")) {
String back="";
for(int j=input.length()-1; j>=0; j--) {
back=back+input.charAt(j);
}
backwards.add(back);
back="";
input=keyboard.next();
}
return backwards;
}
You can also use StringBuffer's predefined reverse() function as shown below code snippet:
ArrayList<String> backwards = new ArrayList();
Scanner keyboard = new Scanner(System.in);
String input = keyboard.next();
StringBuffer a = new StringBuffer(input);
while (!input.equalsIgnoreCase("done")) {
a = new StringBuffer(input);
backwards.add(a.reverse().toString());
input = keyboard.next();
}

Checking for errors from Scanner?

So I decided to make a program that makes Orc objects that each have a name.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
for (int x = 0; x < 10; x++){
System.out.println("Input the name of your Orc here:");
String name = input.nextLine(); //THIS is where the inputed name is registerd.
Orcmaker Orc = new Orcmaker(name);
System.out.println(Orc);
input.close();
}
System.out.println("Fire");
//Find a way to run validation code while not obstructing the for loop to make multiple orc objects.
}
}
So I made that for loop to go through the code so that I can make a name for each orc until eventually I make 10 orcs. The problem is that I'm having issues now injecting input validation that won't make certain lines of code go blank because the loop swallowing up vital code.
Also I just don't know how to make it so that my if statement can see a number or special character to invalidate. Because these are NAMES I only want a String.
Just for completeness' sake here is my constructor. This is the only other class in this mini-project I have made myself.
public class Orcmaker {
private String name;
private int age;
private String weapon;
public Orcmaker(String OrcName){
this.name = OrcName;
}
#Override
public String toString() {
return String.valueOf(name);
}
}

Why is the null error showing in my program; Stringtokenizer to array

This essentially is a small code I'm writting for practice that requires me to use StringTokenizer. I've done the same kind of programs before , but now when I store the strings in an array and try to print them it show's a null pointer exception. Any help?
import java.util.*;
public class board1
{
String key;
String m[];
//function to accept the sentence
void getsent()
{
Scanner in=new Scanner(System.in);
System.out.println("Enter a sentence terminated by'.' or '?'");
String take=in.nextLine();
StringTokenizer taken=new StringTokenizer(take);
int numtokens=taken.countTokens();
String m[]=new String[numtokens];
for(int i=0;i<m.length;i++)
{
m[i]=taken.nextToken();
}
for(int i=0;i<m.length;i++)
{
System.out.print(m[i]);
}
}
// function to display
void display()
{
System.out.println("The words seperately right now are:");
for(int i=0;i<m.length;i++)
{
System.out.print(m[i]+"\t");
System.out.println();
}
}
// main to get functions
public static void main(String args[])
{
board1 ob= new board1();
ob.getsent();
ob.display();
}
}
You're shadowing the variable m. Replace
String m[] = new String[numtokens];
with
m = new String[numTokens];
I think because you are shading properties. You have an array called m into which you are putting tokens in getSent, but display is using the m array defined in the class to which you haven't added anything.
Print out the size of m in display, this will show you that you are not adding anything to the property called m.

Why can't I print a variable that is provided by user inside a loop?

I apologize if the answer to this question is so obvious I shouldn't even be posting this here but I've already looked up the error compiling the following code results in and found no explanation capable of penetrating my thick, uneducated skull.
What this program is meant to do is get 2 integers from the user and print them, but I have somehow managed to mess up doing just that.
import java.util.Scanner;
public class Exercise2
{
int integerone, integertwo; //putting ''static'' here doesn't solve the problem
static int number=1;
static Scanner kbinput = new Scanner(System.in);
public static void main(String [] args)
{
while (number<3){
System.out.println("Type in integer "+number+":");
if (number<2)
{
int integerone = kbinput.nextInt(); //the integer I can't access
}
number++;
}
int integertwo = kbinput.nextInt();
System.out.println(integerone); //how do I fix this line?
System.out.println(integertwo);
}
}
Explanation or a link to the right literature would be greatly appreciated.
EDIT: I want to use a loop here for the sake of exploring multiple ways of doing what this is meant to do.
Remove the int keyword when using the same variable for the second time. Because when you do that, it is essentially declaring another variable with the same name.
static int integerone, integertwo; // make them static to access in a static context
... // other code
while (number<3){
System.out.println("Type in integer "+number+":");
if (number<2)
{
integerone = kbinput.nextInt(); //no int keyword
}
number++;
}
integertwo = kbinput.nextInt(); // no int keyword
And it needs to be static as well since you're trying to access it in a static context (i.e) the main method.
The other option would be to declare it inside the main() method but before your loop starts so that it'll be accessible throughout the main method(as suggested by "Patricia Shanahan").
public static void main(String [] args) {
int integerone, integertwo; // declare them here without the static
... // rest of the code
}
How about:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kbinput = new Scanner(System.in);
System.out.println("Type in an integer: ");
int integerone = kbinput.nextInt();
System.out.println("Type another: ");
int integertwo = kbinput.nextInt();
System.out.println(integerone);
System.out.println(integertwo);
}
}

OOP Inventory program

The error I'm receiving is an Array index out of bounds exception, but I don't know why it's happening where it is.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Inventory
{
//Maximum amount of objects
private static int MAX_ITEMS = 100;
//Iteration from item to item
private int d_nextItem = 0;
//Array for the different objects
private Stock[] d_list = new Stock[MAX_ITEMS];
public static void main(String[] args) throws FileNotFoundException
{
Inventory inventory = new Inventory();
inventory.loadList(args[0]);
//Costs printing out,rough draft, toString not made
System.out.println("COSTS");
inventory.getTotalCost();
//Total Selling price printing out
System.out.println("SELLINGP");
inventory.getTotalSellingPrice();
System.out.println("SAMOUNT");
}
The specific error is Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at Inventory.main(Inventory.java:27) which points towards the inventory.loadList method in main. The error only comes up when run the program, and I don't know why its happening.
This is the loadList method, and the iteration doesn't look wrong, so how is an Array exception happening when the array is storing a reference to the objects information, not all the different strings, int and doubles.
public void loadList(String fileName) throws FileNotFoundException
{
fileName = "stock1.txt";
Scanner input = new Scanner(new File(fileName));
String newLine = null;
String name = null;
String identifier = null;
int quantity = 0;
double cost = 0.0;
double price = 0.0;
while (input.hasNextLine() && d_nextItem < MAX_ITEMS)
{
if(input.hasNext())
{
name = input.next();
}
if(input.hasNext())
{
identifier = input.next();
}
if(input.hasNextInt())
{
quantity = input.nextInt();
}
if(input.hasNextDouble())
{
cost = input.nextDouble();
}
if(input.hasNextDouble())
{
price = input.nextDouble();
}
d_list[d_nextItem]= new Stock(name,identifier,quantity,cost,price);
newLine = input.nextLine();
d_nextItem += 1;
}
}
That error means that you're not passing a parameter to the program.
args is an array containing the parameters passed to the program, the fact that index 0 is out of bounds means there are no parameters.
How exactly to do this would depend on how you're running the program.
The args[] array is special in that, when you're using it, you're invoking your program with more info, typically from the command line.
The appropriate way to populate args[] would be as follows:
java Inventory classname.txt
This way, Java will pull classname.txt into args[0].
From what I see, the code you have pasted here looks fine. So the problem might be elsewhere.
However a couple of quick changes may fix your problem.
use lists instead of an array for stock:
List stocklist = new ArrayList();
stocklist.add(...);
and make d_nextItem a local variable and initialize it before the while loop.

Categories