Statements after the nextInt Line is not working - java

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);
}
}
}

Related

Pizza toppings with array

I'm suppose to write a program, Pizza.java, that lets the user enter up to 15 toppings for a pizza, then prints out the toppings in alphabetical order. Also, the toppings should be listed with numbers.
A sample output would be like this
The code I wrote is as follows:
import java.util.*;
public class Pizza {
public static final int numbers=15;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String []toppings;
System.out.println("Enter a toping (or type quit): ");
String a= input.nextLine();
// how do I add String a to the array toppings?
int count=1;
while (!a.equals("quit")&&count<numbers){
System.out.println("Enter a topping (or type quit): ");
a= input.nextLine();
if(!a.equals("quit"))
// how do I add String a to the array toppings?
count++;
}
if(count==numbers)
System.out.println("No more toppings allowed.");
int i=1;
Arrays.sort(toppings); //sorts the array in alphabetical order
while (int i<=count){
System.out.println(i+". "+Arrays.toString(toppings));
}
if(a.equals("quit")){
Arrays.sort(toppings); //sorts the array in alphabetical order
while (int j<=count){
System.out.println(j+". "+Arrays.toString(toppings));
}
}
}
}
How do I complete this code?
Any help would be appreciated
You can make it simpler using List instead of arrays:
import java.util.*;
public class Pizza {
public static final int numbers = 15;
public static void main(String[] args) {
List<String> toppings = new ArrayList<>();
Scanner input = new Scanner(System.in);
int attempt;
for (attempt = 0; attempt < numbers; attempt++) {
System.out.print("Enter topping topping (or type quit): ");
String topping = input.nextLine();
if (topping.equals("quit")) {
break;
}
toppings.add(topping);
}
if (attempt == numbers) {
System.out.println("No more toppings allowed.");
}
Collections.sort(toppings);
for (int position = 0; position < toppings.size(); position++) {
System.out.println((position + 1) + ". " + element);
}
}
}
or using arrays:
import java.util.*;
public class Pizza {
public static final int numbers = 15;
public static void main(String[] args) {
String[] toppings = new String[numbers];
Scanner input = new Scanner(System.in);
int attempt;
for (attempt = 0; attempt < numbers; attempt++) {
System.out.print("Enter topping topping (or type quit): ");
String topping = input.nextLine();
if (topping.equals("quit")) {
break;
}
toppings[attempt] = topping;
}
if (attempt == numbers - 1) {
System.out.println("No more toppings allowed.");
} else {
// Remove "null" elements from "toppings" array
String[] temp = new String[attempt];
for (int position = 0; position < attempt; position++) {
temp[position] = toppings[position];
}
toppings = temp;
}
Arrays.sort(toppings);
for (int position = 0; position < toppings.length; position++) {
String element = toppings[position];
System.out.println((position + 1) + ". " + element);
}
}
}
As you said, you are not allowed to use an ArrayList. Here is my approach on how to do it using a String array. The most interesting part for you should be the Arrays.copyOfRange method, which you could also substitute with a System.arraycopy(...) call.
import java.util.*;
public class Pizza {
private static final int MAX_TOPINGS = 15;
private final String QUIT_KEYWORD = "quit";
public static void main(String[] args) {
new Pizza().printToppings(MAX_TOPINGS);
}
public void printToppings(int maxTopings){
Scanner input = new Scanner(System.in);
String[] toppings = new String[maxTopings];
int count;
for (count = 0; count < maxTopings; count++) {
System.out.printf("Enter topping topping (or type %s): ", QUIT_KEYWORD);
String topping = input.nextLine();
if (topping.toLowerCase().equals(QUIT_KEYWORD)) {
break;
}
toppings[count] = topping;
}
if (count+1 == maxTopings) {
System.out.println("No more toppings allowed.");
} else {
toppings = Arrays.copyOfRange(toppings, 0, count);
}
Arrays.sort(toppings);
for (int i = 0; i < count; i++) {
System.out.println(i+1 + ". " + toppings[i]);
}
}
}
For the following input:
Enter topping topping (or type quit): Cheese
Enter topping topping (or type quit): Onions
Enter topping topping (or type quit): Tuna
Enter topping topping (or type quit): quit
You would receive this output:
1. Cheese
2. Onions
3. Tuna
Don't bother with while loops. If you are dealing with arrays, you should use a for loop.
As far adding a string to the array is concerned, you should really learn about arrays before trying to use them. You did not even initialize your array before using it.
You can use a break statement to exit the loop when the user enters "quit".
import java.util.Arrays;
import java.util.Scanner;
public class Pizza {
//If actually want the user to be able to enter 15 toppings, then set numbers to 16.
public static final int numbers = 16;
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
//Initialize the array
String[] toppings = new String[numbers];
int count;
//Use a for loop
for (count = 0; count < numbers; count++) {
System.out.println("Enter a toping (or type quit):");
toppings[count] = input.nextLine();
if (toppings[count].equalsIgnoreCase("quit")) {
//If they enter quit, break from the loop
break;
}
}
if (count == numbers)
System.out.println("No more toppings allowed.");
//If they do not fill all 15 indices of the array, trim out the empty indices.
if (count < numbers)
toppings = Arrays.copyOfRange(toppings, 0, count);
Arrays.sort(toppings);
//Use another for to print them
for (int i = 0; i < count; i++) {
System.out.println(i + ". " + toppings[i]);
}
}
}

How to add more variables inside of loops java

Have each department's number of computers stored in variables. Have the program store the values in variables, calculate the total and average computers and display them.
example output:
Chemistry: 4
Physics: 8
Music: 2
Math lab: 12
Total: 26
Average: 6.5
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("What is the name of your first class?");
String class1 = sc.nextLine();
System.out.print("What is the name of your second class?");
String class2 = sc.nextLine();
System.out.print("What is the name of your third class?");
String class3 = sc.nextLine();
System.out.print("What is the name of your fourth class?");
String class4 = sc.nextLine();
System.out.print(" \n\n");
System.out.println("How many computers are in each class?");
System.out.print(class1 + ": \t");
int class1comp = sc.nextInt();
System.out.print(class2 + ": \t");
int class2comp = sc.nextInt();
System.out.print(class3 + ": \t");
int class3comp = sc.nextInt();
System.out.print(class4 + ": \t");
int class4comp = sc.nextInt();
int sum = class1comp + class2comp + class3comp + class4comp;
double avg = sum / 4.0;
System.out.print(" \n\n");
System.out.println("\n\n" + class1 + ":\t" + class1comp);
System.out.println(class2 + ":\t" + class2comp);
System.out.println(class3 + ":\t" + class3comp);
System.out.println(class4 + ":\t" + class4comp);
System.out.println("\n");
System.out.println("Total:\t\t" + sum);
System.out.println("Average:\t" + avg);
}
}
After unit 2: Allow the user to add more departments.
I want the user to be able to add more classes until they say stop. Then later ask how many computers each class needs. Then display them, add them to the sum and average.
This should work for your purposes , it uses an ArrayList for the class names and an array of integers for the grades. It uses the AddOrdinal method taken from this answer.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<String> stringList = new ArrayList<>();
String capture;
int count =1;
System.out.println("Please enter your "+AddOrdinal(count) +" class:");
while (!((capture = scan.nextLine()).toLowerCase().equals("stop"))) {
count++;
stringList.add(capture);
System.out.println("Please enter your "+AddOrdinal(count) +" class:");
}
System.out.println("How many computers are in each class?");
int[] intList = new int[stringList.size()];
for (int i = 0; i < stringList.size(); i++) {
String className = stringList.get(i);
System.out.println(className + "\t:");
intList[i] = (scan.nextInt());
}
scan.close();
Arrays.stream(intList).sum();
int sum = Arrays.stream(intList).sum();
double average = (double)sum/intList.length;
/*
Output goes here
*/
}

How to repeatedly store data in linked lists?

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");
}
}
}

How to get array of strings or integers from users inside looping statement?

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();
}
}

Printing out elements at certain indexes in vectors in Java

This is probably very basic stuff, but I am not too sure how I should ask questions because I am very new to this, so here goes.
I am practicing vectors and what we can do to them. I have prompted the user for the elements of the vectors (per my directions) among other things successfully. For my next step, I have to "print out the element at index i in each of the two vectors." I was given the methods which I am supposed to use, but the explanations I saw of them were very unclear. Here they are:
Object get (int which)
Object remove (int which)
set (int index, object element)
How would I get the system output to be the element at the index i?
package vectorusage;
import java.util.*;
public class VectorUsage {
public static void main(String[] args) {
Vector a = new Vector ();
Vector b = new Vector ();
System.out.println (a);
System.out.println (b);
Scanner input = new Scanner(System.in);
String first;
System.out.print("Please enter 4 strings.");
first = input.next();
a.add (first);
String second;
second = input.next();
a.add (second);
String third;
third = input.next();
a.add (third);
String fourth;
fourth = input.next();
a.add (fourth);
String fifth;
System.out.print("Please enter 4 more strings.");
fifth = input.next();
b.add (fifth);
String sixth;
sixth = input.next();
b.add (sixth);
String seventh;
seventh = input.next();
b.add (seventh);
String eighth;
eighth = input.next();
b.add (eighth);
System.out.println("Vector a is size " + (a.size()) + " and contains: " + (a));
System.out.println("Vector b is size " + (b.size()) + " and contains: " + (b));
int i;
System.out.println("Please enter an integer.");
i = input.nextInt();
System.out.println("Element at index " + i + " in Vector a is: " + ;
Avoid using vectors, they are deprishiated. Use ArrayList instead.
Using a for loop you can simplify your code like below,
(Please note, this code does not validate user input or do error handling)
import java.util.ArrayList;
import java.util.Scanner;
public class Test {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<Integer>();
System.out.println("Please enter 8 strings.");
for(int i = 1; i <= 8; i++) {
System.out.print("Please enter strings #" + i + ": ");
numbers.add(input.nextInt());
}
for(int j = 0; j < numbers.size(); j++) {
System.out.println("Number at index " + j + " is " + numbers.get(j));
}
}
}
I usually use a mix of while and for loop. The while loop is used to add the user input into the vector. The for loop prints out the elements of the vector using index i. I've set it to print all the elements of the vector but you can modify it by using if conditions. Here's my code, hope it helps!
import java.util.*;
import java.io.*;
public class VectorUsage {
public static void main(String[]args) {
Scanner input=new Scanner(System.in);
Vector a=new Vector();
int count =0;
while(count<4)
{
System.out.print("Enter a string: ");
a.addElement(input.nextLine());
count++;
}
for(int i=0;i<a.size();i++)
{
System.out.println(a.elementAt(i));
}
Vector b=new Vector();
int count1=0;
while(count1<4)
{
System.out.print("Enter a string: ");
b.addElement(input.nextLine());
count1++;
}
for(int i=0;i<b.size();i++)
{
System.out.println(b.elementAt(i));
}
}
}

Categories