I have a program where I want to continue adding in an integer and string in a linked list. However when I print out the linked list it only prints out the last entered values and not the previous ones. So If I entered 3 Sally and then entered 6 Bob the linked list only prints out 6 bob. I want to be able to print out everything in the linkedlist no just the last entered.
public class Texteditor {
/**
* #param args the command line arguments
*/
static int myInt;
static String myString;
public Texteditor(int a, String s){
myInt = a;
myString = s;
}
public String toString(){
return myInt + " " + myString;
}
public static void main(String[] args) {
LinkedList<Texteditor> myLL = new LinkedList<Texteditor>();
int isExit = 0;
System.out.println("Hello Welcome to Your Personal Texteditor! ");
System.out.println("There are many options you can do with this text editor");
System.out.println("1. If you enter a line number with no text, the line number will be deleted.");
System.out.println("2. If you enter LIST alone the editor will print everything in the list with line number.");
System.out.println("3. If you enter RESEQUENCE the line numbers will be resequenced to start at 10.");
while(isExit ==0) {
// myLL = new LinkedList<Texteditor>();
System.out.println("");
System.out.println("Please enter the line number: ");
Scanner kb = new Scanner(System.in);
myInt = kb.nextInt();
System.out.println("Plese enter text as a string: ");
Scanner kb1 = new Scanner(System.in);
myString = kb1.nextLine();
Texteditor a1 = new Texteditor(myInt, myString);
myLL.add(a1);
System.out.println("Would you like to keep going? Enter yes or no: " );
Scanner kb2 = new Scanner(System.in);
if (kb2.next().equals("no")){
isExit = 1;
}
}
for (Texteditor element : myLL){
System.out.println(element + "\n");
}
}
}
Your myInt and myString are static, which means they're shared by instances. Make them non-static and the code should work correctly.
Also, don't recreate the Scanner every time in the loop. Once is enough.
The problem is that you are making the myInt and myString variables static. Remove the static modifier and then in your while loop, instead of referencing the class's myInt and myString variables, create local int and String variables instead.
public class Texteditor {
/**
* #param args the command line arguments
*/
int myInt;
String myString;
public Texteditor(int a, String s){
myInt = a;
myString = s;
}
public String toString(){
return myInt + " " + myString;
}
public static void main(String[] args) {
LinkedList<Texteditor> myLL = new LinkedList<Texteditor>();
int isExit = 0;
System.out.println("Hello Welcome to Your Personal Texteditor! ");
System.out.println("There are many options you can do with this text editor");
System.out.println("1. If you enter a line number with no text, the line number will be deleted.");
System.out.println("2. If you enter LIST alone the editor will print everything in the list with line number.");
System.out.println("3. If you enter RESEQUENCE the line numbers will be resequenced to start at 10.");
while(isExit ==0) {
// myLL = new LinkedList<Texteditor>();
System.out.println("");
System.out.println("Please enter the line number: ");
Scanner kb = new Scanner(System.in);
int myInt = kb.nextInt();
System.out.println("Plese enter text as a string: ");
Scanner kb1 = new Scanner(System.in);
String myString = kb1.nextLine();
Texteditor a1 = new Texteditor(myInt, myString);
myLL.add(a1);
System.out.println("Would you like to keep going? Enter yes or no: " );
Scanner kb2 = new Scanner(System.in);
if (kb2.next().equals("no")){
isExit = 1;
}
}
for (Texteditor element : myLL){
System.out.println(element + "\n");
}
}
}
The problem with your code is that the variables myInt and myString are static and hence they don't belong to each individual object (they belong to the class). Thus when you reference them here:
for (Texteditor2 element : myLL){
System.out.println(element + "\n");
}
You're calling the same values you set last n amount of times.
This should fix the problem:
Create a new TextEditorObject file:
public class TextEditorObject {
int myInt;
String myString;
public TextEditorObject(int a, String s){
myInt = a;
myString = s;
}
public String toString() {
return myInt + " " + myString;
}
}
Change Texteditor like so:
public class Texteditor {
public static void main(String[] args) {
int myInt;
String myString;
LinkedList<TextEditorObject> myLL = new LinkedList<TextEditorObject>();
int isExit = 0;
System.out.println("Hello Welcome to Your Personal Texteditor! ");
System.out.println("There are many options you can do with this text editor");
System.out.println("1. If you enter a line number with no text, the line number will be deleted.");
System.out.println("2. If you enter LIST alone the editor will print everything in the list with line number.");
System.out.println("3. If you enter RESEQUENCE the line numbers will be resequenced to start at 10.");
while(isExit ==0) {
// myLL = new LinkedList<Texteditor>();
System.out.println("");
System.out.println("Please enter the line number: ");
Scanner kb = new Scanner(System.in);
myInt = kb.nextInt();
System.out.println("Plese enter text as a string: ");
Scanner kb1 = new Scanner(System.in);
myString = kb1.nextLine();
TextEditorObject a1 = new TextEditorObject(myInt, myString);
myLL.add(a1);
System.out.println("Would you like to keep going? Enter yes or no: " );
Scanner kb2 = new Scanner(System.in);
if (kb2.next().equals("no")){
isExit = 1;
}
}
for (TextEditorObject element : myLL){
System.out.println(element + "\n");
}
}
}
Related
I want the user to input the choice of their fruit to catch depending on the number of fruits he inputs. But the problem is that after the input on nextInt() the compiler stops compiling and skips the for loop.
import java.util.*;
public class FruitBasket {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Stack<String> stack = new Stack<>();
String select;
System.out.println("Catch and eat any of these fruits: (Apple, Orange, Mango, Guava");
System.out.print("How many fruits would you like to catch? ");
int num = s.nextInt();
s.nextLine();
for (int i = 1; i >= num; i++) {
System.out.print("Choose a fruit to catch. Press A(apple), O(orange), M(mango), G(guava) ");
System.out.print("\nFruit " + i + " of " + num + ": ");
select = s.nextLine();
stack.push(select);
}
}
}
package stringvars;
import java.util.Scanner;
public class ConcertID {
public static void main(String[] args) {
try (Scanner userInput = new Scanner (System.in)) {
String yourName;
System.out.print ("enter the last letter of your second name: ");
yourName = userInput.next();
String yourDOB;
System.out.print ("enter your Year Of Birth: ");
yourDOB = userInput.next();
String ConcertID;
ConcertID = yourName + " " + yourDOB;
System.out.println("your concert ID is " + ConcertID);
}
}
}
I'm trying to get the code to take the user input, add a number between 1 and 10 at the end and print it as Y18867. Currently it prints as Y 1886.
(And I've yet to figure out the math.random part.)
Let me recommend you start using the StringBuilder class to create concatenated strings. It has a better performance regarding time consuming to concatenate strings.
The following code generates the random number as well as the concertId string that you are trying to get.
public class ConcertID
{
public static void main(String[] args)
{
try (Scanner userInput = new Scanner(System.in))
{
String yourName;
System.out.print("Enter the last letter of your second name: ");
yourName = userInput.nextLine();
String yearOfBirth;
System.out.print("Enter your Year of Birth: ");
yearOfBirth = userInput.nextLine();
StringBuilder concertId = new StringBuilder();
concertId.append(yourName);
concertId.append(yearOfBirth);
concertId.append(generateNumber());
System.out.println(concertId.toString());
}
}
public static int generateNumber()
{
int number = 0;
Random random = new Random();
number = random.nextInt(1, 10);
return number;
}
}
I am trying to write a program that takes a user's input and outputs the number of characters they typed in. I have to do this by creating a method that calculates the amount of characters, then call that method in main to output the results. I was encouraged to use a for loop, but I don't see how that would work. I can calculate the number of characters using length(), but I can't figure out how to make my method work. This is what I have so far:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
System.out.println("Enter a sentence: ");
System.out.print("You entered: ");
userInput = scnr.nextLine();
System.out.println(userInput);
return;
}
public static int GetNumOfCharacters(int userCount) {
int i = 0;
String userInput = "";
userCount = userInput.length();
return userCount;
}
}
My method is not returning the length of the string, it just gives me 0 or an error.
Right now, you are never calling your "GetNumOfCharacters" method in your main. The way Java programs work, is by calling the main method and executing line per line what lies there. So you need to call you method from inside the main method. On the other hand, it should get the Stirng as a parameter, so you can get its length. It would look something like this:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
System.out.println("Enter a sentence: ");
userInput = scnr.nextLine();
System.out.print("You entered: ");
System.out.println(userInput);
int lenInput = GetNumOfCharacters(userInput);
System.out.println("The length was: "+lenInput+" characters");
}
public static int GetNumOfCharacters(String userInput) {
int len = userInput.length();
return len;
}
A problem is that you are not actually calling the method
so try
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.println("Enter a sentence: ");
String userInput = scnr.nextLine();
System.out.print("You entered: ");
System.out.println(userInput);
System.out.println ("The length is " + GetNumOfCharacters (userInput))
}
// need to pass string into this method
public static int GetNumOfCharacters(String myString) {
int userCount = myString.length();
return userCount;
}
}
Your question included the line:
I was encouraged to use a for loop, but I don't see how that would
work.
There's no elegant way to do this in Java because you are assumed to use String.length() to get the length of strings. There is no 'end of string' marker as there is in, say, C. However you could mimic the same effect by catching the exception thrown when you access past the end of the string:
for (int len = 0; ; len++) {
try {
text.charAt(len);
} catch (StringIndexOutOfBoundsException ex) {
return len;
}
}
That's not a nice, efficient or useful piece of code but it does demonstrate how to get the length of a string using a for loop.
Problems with your code:
No Function call
Add function call in main() as int count=GetNumOfCharacters(userInput);
Parameter datatype mismatch
change the datatype in function definition from int to String as public static int GetNumOfCharacters(String userInput) {
Unwanted return statement in main()
remove the return from main()
Not displaying the value returned from GetNumOfCharacters
Add System.out.print("Number of characters: "+ count); inside main()
Code:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
System.out.println("Enter a sentence: ");
System.out.print("You entered: ");
userInput = scnr.nextLine();
System.out.println(userInput);
int count=GetNumOfCharacters(userInput);
System.out.print("Number of characters: "+ count);
}
public static int GetNumOfCharacters(String userInput) {
int userCount = userInput.length();
return userCount;
}
OR
Function is not really needed,you can remove the function and do it like this:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
System.out.println("Enter a sentence: ");
System.out.print("You entered: ");
userInput = scnr.nextLine();
System.out.println(userInput);
System.out.print("Number of characters: "+ userInput.length());
}
If you don't want to use predefined methods, you can do like this..
public static void main(String args[]){
Scanner scnr = new Scanner(System.in);
System.out.println("Enter a sentence: ");
String userInput = scnr.nextLine();
System.out.println("You entered: "+userInput);
char a[]=userInput.toCharArray();
int count=0;
for(char c : a){
count++;
}
System.out.println("length of the string is:"+count);
}
package contractmanager;
import java.util.*;
/**
*
* #author Tom McCloud
*/
public class ContractManager {
static Scanner keyb = new Scanner(System.in);
// global scanner
public static void main(String[] args) {
int option;
//variable declaration
String clientName;
String packageSize;
String dataBundle;
String reference;
int period;
boolean intlCalls;
//display menu to user
System.out.println("Welcome: \n");
System.out.println("1. Enter new contract ");
System.out.println("2. Display contract summary");
System.out.println("3. Display summary of contract for selected month");
System.out.println("4. Find and display contract");
System.out.println("0. Exit");
//take option off user
option = keyb.nextInt();
//WIP - only working on option 1 at the minute
switch(option) {
case 1:
clientName = clientName();
packageSize = packageSize();
dataBundle = dataBundle();
reference = reference();
break;
}
exit();
}
public static void exit()
{
System.out.println("Thank you for using the contract manager. Goodbye!");
}
public static String clientName()
{
String name = " ";
System.out.println("Please input your full name: ");
name = keyb.nextLine();
return name;
}
public static String packageSize()
{
String size;
System.out.println("Please input your package size: ");
System.out.println(" 1. Small \n 2. Medium \n 3. Large");
size = keyb.next();
return size;
}
public static String dataBundle()
{
String data;
System.out.println("Please input data bundle size: ");
System.out.println("1. Low \n 2. Medium \n 3. High \n 4. Unlimited");
data = keyb.next();
return data;
}
public static String reference()
{
String ref;
boolean isRefValid = false;
do {
System.out.println("Please input your reference code: ");
ref = keyb.next();
if(ref.length() > 6)
{
System.out.println("Reference number too long, re-enter!");
}
for(int i = 0; i < 2; i++)
{
if(Character.isDigit(ref.charAt(i)))
{
System.out.println("First two characters must be letters!");
}
}
} while(isRefValid = false);
return ref;
}
}
So, this is some code I have. If I press enter code hereone, it executes these, now technically shouldn't this be in order of one another once each method reaches completion and returns?
For example, on execution after pressing "1" I get the following output:
Please input your full name:
Please input your package size:
1. Small
2. Medium
3. Large
Whereas this should come one by one, after the full name has been inputted it should move onto the package size step. If I input it goes to the third step rather than repeating for the second step's input.
I think it's because in your clientName function you have just printed "Please input your full name: " without waiting for input. For example you have to do something like below here scan.nextLine() will wait until user have press enter:
Scanner scan = new Scanner();
System.out.println("Please input your full name:");
String name= scan.next();
System.out.println(name);
scan.nextLine();
Updated: Try by updating clientName function as below
public static String clientName() {
String name = " ";
System.out.println("Please input your full name: ");
name = keyb.next();
keyb.nextLine();
return name;
}
When I tried to run this code noOfSub() methods executed properly;
but GC() method faces the following problem:
Enter the number of subjects:
2
Enter Your Subject 1 Grade:
s
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at GPA.GC(GPA.java:21)
at GPA.main(GPA.java:35)
Java Result: 1
Here is my code:
import java.util.Scanner;
public class GPA {
public int noOfSubjects;
public int i=1;
Scanner gradeInput = new Scanner(System.in);
String[] grade = new String[noOfSubjects];
int[] credit = new int[noOfSubjects];
public void noOfSub() {
System.out.println("Enter the number of subjects:");
Scanner sub = new Scanner(System.in);
noOfSubjects = sub.nextInt();
}
public void GC() {
while(i<=noOfSubjects)
{
System.out.println("Enter Your Subject "+i+" Grade:" );
grade[i] = gradeInput.nextLine();
System.out.println("Enter the Subject "+i+" Credit:");
credit[i] = gradeInput.nextInt();
i++;
}
}
public static void main(String[] args) {
GPA obj = new GPA();
obj.noOfSub();
obj.GC();
}
}
When you do:
public int noOfSubjects;
noOfSubjects is set to 0 which is its default value
So when you have the following code:
String[] grade = new String[noOfSubjects];
it essentially means,
String[] grade = new String[0]; //create a new String array with size 0
which creates an empty array for you.
So when you do,
grade[i] = gradeInput.nextLine(); //where i is 1
you get:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at GPA.GC(GPA.java:21)
at GPA.main(GPA.java:35
because there is no index 1 in String[] grade.
Problem in your array initialization. You can initialize your array after take the input from user.
For example :
public void noOfSub() {
System.out.println("Enter the number of subjects:");
Scanner sub = new Scanner(System.in);
noOfSubjects = sub.nextInt();
grade = new String[noOfSubjects];
credit = new int[noOfSubjects];
}
And change your while condition. Instead of this you use
while(i < noOfSubjects)
and set i = 0
If you want to get the size for the array from the user, create the array after getting it from stdin. Otherwise it will create a array with the size of 0 which is the default value for int in java.
Separate your declaration and initalization
String[] grade = null;
int[] credit = null;
...
noOfSubjects = scan.nextInt();
grade = new String[noOfSubjects];
credit = new int[noOfSubjects];
Why don't you use ArrayList because the size of array isn't know for you
public class GPA {
public int noOfSubjects;
public int i=0;
Scanner gradeInput = new Scanner(System.in);
List<String> grade = new ArrayList<>();
List<Integer> credit = new ArrayList<>();
public void noOfSub(){
System.out.println("Enter the number of subjects:");
Scanner sub = new Scanner(System.in);
noOfSubjects = sub.nextInt();
}
public void GC(){
while(i<noOfSubjects)
{
System.out.println("Enter Your Subject "+(i+1)+" Grade:" );
grade.add(gradeInput.nextLine());
System.out.println("Enter the Subject "+(i+1)+" Credit:");
credit.add(gradeInput.nextInt());
gradeInput.nextLine();
i++;
}
}
public static void main(String[] args) {
GPA obj = new GPA();
obj.noOfSub();
obj.GC();
}
}
Note : i added gradeInput.nextLine() after i++ because the Scanner.nextInt() method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner.nextLine() so i fire a blank gradeInput.nextLine() call after gradeInput.nextInt() to consume rest of that line including newline
Since the noOfSubjects has run time value so the code should be:
import java.util.Scanner;
public class GPA {
public int noOfSubjects;
public int i = 0;
Scanner gradeInput = new Scanner(System.in);
String[] grade;
int[] credit;
public void noOfSub() {
System.out.println("Enter the number of subjects:");
Scanner sub = new Scanner(System.in);
noOfSubjects = sub.nextInt();
grade = new String[noOfSubjects];
credit = new int[noOfSubjects];
}
public void GC() {
while (i < noOfSubjects) {
System.out.println("Enter Your Subject " + (i + 1) + " Grade:");
grade[i] = gradeInput.next();
System.out.println("Enter the Subject " + (i + 1) + " Credit:");
credit[i] = gradeInput.nextInt();
i++;
}
for (int j = 0; j < grade.length; j++) {
System.out.println(grade[j] + " " + credit[j]);
}
}
public static void main(String[] args) {
GPA obj = new GPA();
obj.noOfSub();
obj.GC();
}
}