I just tried to get an integer value from the user for a variable in another a method that created differently from main but it gives an error message like this:
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:941)
at java.base/java.util.Scanner.next(Scanner.java:1598)
at java.base/java.util.Scanner.nextInt(Scanner.java:2263)
at java.base/java.util.Scanner.nextInt(Scanner.java:2217)
at StoreUsingArrays_20210808043.menu(StoreUsingArrays_20210808043.java:14)
at StoreUsingArrays_20210808043.storeRun(StoreUsingArrays_20210808043.java:57)
at StoreUsingArrays_20210808043.main(StoreUsingArrays_20210808043.java:90)
Code:
import java.util.Arrays;
import java.util.Scanner;
public class StoreUsingArrays_20210808043 {
public static int menu(String[] items,double[] prices,int answer) {
Scanner input = new Scanner(System.in);
for (int i = 1;i <= items.length;i++) {
System.out.println(i+" - for "+items[i-1]+" ("+prices[i-1]+")");
}
System.out.println("0 - to checkout");
System.out.print("Please enter what would you like : ");
answer = input.nextInt();
System.out.println("Your choice was : "+answer);
input.close();
return answer;
}
public static void returnedAmounts(double amount) {
double bill200,bill100,bill50,bill20,bill10,bill5,bill1,coin50,coin25,coin10,coin1;
bill200 = (amount - (amount%200)) / 200;
amount = amount%200;
bill100 = (amount - (amount%100)) / 100;
amount = amount%100;
bill50 = (amount - (amount%50)) / 50;
amount = amount%50;
bill20 = (amount - (amount%20)) / 20;
amount = amount%20;
bill10 = (amount - (amount%10)) / 10;
amount = amount%10;
bill5 = (amount -(amount%5)) / 5;
amount = amount%5;
bill1 = (amount - (amount%1)) / 1;
amount = amount%1;
coin50 = (amount - (amount%0.50)) / 0.50;
amount = amount%0.50;
coin25 = (amount - (amount%0.25)) / 0.25;
amount = amount%0.25;
coin10 = (amount - (amount%0.10)) / 0.10;
amount = amount%0.10;
coin1 = (amount - (amount%0.01)) / 0.01;
double[] returnedNumbers = {bill200,bill100,bill50,bill20,bill10,bill5,bill1,coin50,coin25,coin10,coin1};
double[] returnedValues = {200,100,50,20,10,5,1,0.50,0.25,0.10,0.01};
for (int i = 0;i < returnedNumbers.length;i++) {
if ((returnedNumbers[i] > 0) && (returnedValues[i] > 0)) {
System.out.println((int)returnedNumbers[i]+" - "+returnedValues[i]);
}
}
}
public static void storeRun(String[] item,int[] quantity,double[] price) {
Scanner input = new Scanner(System.in);
capitalizeArray(item);
int choice,req = 0;
while (true) {
choice = menu(item, price, 0);
if (choice == 0) break;
else if (choice > item.length && choice < 0) {
System.out.println("ERROR:Invalid choice");
break;
}
else {
System.out.println("How many "+item[choice-1]+" would you like? ");
if (input.hasNextInt()) req = input.nextInt();
System.out.println(req);
}
}
input.close();
}
public static String capitalizeString(String text) {
return text.substring(0, 1).toUpperCase() + text.substring(1).toLowerCase();
}
public static String[] capitalizeArray(String[] name) {
for (int i = 0;i < name.length;i++) {
name[i] = capitalizeString(name[i]);
}
return name;
}
public static void main(String[] args) {
String[] item = {"bRead","cOLA","ROLL","BaKe"};
double[] price = {4,2,6,5};
int[] quantity = {10,25,17,22};
//capitalizeArray(item);
//System.out.println(Arrays.toString(item));
//menu(item, price, 0);
storeRun(item, quantity, price);
//returnedAmounts(167.5);
}
}
I expected to get a value for the req variable from user and use it for another purposes but I tried a lot of things like that:
Initializing the variable at the begin.
Removing the input.close() line.
(etc.)
But all of them didn't work.
Replace all input.close() by input.reset()
In method menu, replace answer = input.nextInt(); by if (input.hasNextInt()) answer = input.nextInt();
and it should work
Related
I was making an Armstrong number checker not for only 3 digits numbers for which I used Math.pow() method but after using it the if else statement is not working also when the condition is true.
Here is the code:
import java.util.Scanner;
import java.lang.Math;
class Main {
////////////////////////////////////////////
////////////////////////////////////////////
public static void main(String args[])
{
System.out.println("Hello world!");
Scanner sc = new
Scanner(System.in);
int num = sc.nextInt();
int numc = num ;
double rem = 0;
double cu = 0;
int val = 0;
int val2 = 0;
while(num != 0){
rem = num%10;
while(numc != 0){
numc /=10;
int i = 0;
i++;
val2 += i;
}
cu = Math.pow(rem,val2 );
val += cu;
num /= 10;
}
if(val == numc){
System.out.println("Yes its a "+val2+" Armstrong number because its returning " + val+"after Calculations ");
}
else{
System.out.println("No its not a "+val2+" digit Armstrong number because its returning " + val +" after Calculations ");
}
}
}
///////////////////////////////////////////
And this is the Compilation of my code:
if(val == numc){ - This if part is the root cause of your problem . you are dividing numc by 10 for calculations . So at the end it will become 0 . so you will be checking if val == 0 which goes to the else loop.
So I would suggest to assign the input from the user to another variable which you can use for checking the final if - else part.
Like int input = num and at the end if(val==input){ . This would resolve your issue.
The num and numc become zero due to "/= 10" operation. Hence the if condition fails.
Also you need not compute the length of integer every time.
Don't have the reputation to comment hence giving a full fledged solution.
Following is my solution to your problem.
All the best!
import java.util.Scanner;
import java.lang.Math;
class Main {
////////////////////////////////////////////
////////////////////////////////////////////
public static void main(String args[]) {
System.out.println("Hello world!\n");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int numc = num;
double rem = 0;
double cu = 0;
int val = 0;
int val2 = countNumOfDigits(num);
while (num != 0) {
rem = num % 10;
cu = Math.pow(rem, val2);
val += cu;
num /= 10;
}
if (val == numc) {
System.out.println("Yes its a " + val2 + " digit Armstrong number because its returning " + val
+ "after Calculations ");
} else {
System.out.println("No its not a " + val2 + " digit Armstrong number because its returning " + val
+ " after Calculations ");
}
}
private static int countNumOfDigits(int number) {
if (number < 100000) {
if (number < 100) {
if (number < 10) {
return 1;
} else {
return 2;
}
} else {
if (number < 1000) {
return 3;
} else {
if (number < 10000) {
return 4;
} else {
return 5;
}
}
}
} else {
if (number < 10000000) {
if (number < 1000000) {
return 6;
} else {
return 7;
}
} else {
if (number < 100000000) {
return 8;
} else {
if (number < 1000000000) {
return 9;
} else {
return 10;
}
}
}
}
}
}
I think a code is missing or not working because there should be a discount if the number is more than 5. For example a novel is borrowed for 6 days and so the rental charge should 8250. But isn't working as the rental charge is 9000.
Here is my program code:
**import java.util.Scanner;
class BookRentalShop
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of data you want to see: ");
int inputnum = sc.nextInt();
sc.nextLine();
System.out.println("");
String[] Name = new String[inputnum];
String[] Bookname = new String[inputnum];
String[] AuthorName = new String[inputnum];
String[] Booktype = new String[inputnum];
int[] NumbersofDaysBorrowed = new int[inputnum];
int[] RentalCharges = new int[inputnum];
String[] Types = {"Cartoon","Magazine", "Short story", "Long story", "Journal", "Novel", "Encyclopedia"};
int[] count = new int[7];
for (int d = 0; d < inputnum; d = d + 1)
{
System.out.println("Enter the name of the person:");
Name[d] = sc.nextLine();
System.out.println("Enter the bookname:");
Bookname[d] = sc.nextLine();
System.out.println("Enter the author's name:");
AuthorName[d] = sc.nextLine();
System.out.println("Enter the book type:");
Booktype[d] = sc.nextLine();
for (int k = 0; k < 7; k++)
{
if (Booktype[d].equals(Types[k]))
{
count[k]++;
}
}
System.out.println("Enter the number of days that the book had been borrowed:");
NumbersofDaysBorrowed[d] = sc.nextInt();
sc.nextLine();
if (Booktype[d].equalsIgnoreCase("Cartoon"))
{
RentalCharges[d] = NumbersofDaysBorrowed[d] * 500;
} else if (Booktype[d].equalsIgnoreCase("Magazine"))
{
RentalCharges[d] = NumbersofDaysBorrowed[d] * 1000;
} else if (Booktype[d].equalsIgnoreCase("Short story"))
{
RentalCharges[d] = NumbersofDaysBorrowed[d] * 500;
} else if (Booktype[d].equalsIgnoreCase("Long story"))
{
RentalCharges[d] = NumbersofDaysBorrowed[d] * 1500;
} else if (Booktype[d].equalsIgnoreCase("Journal"))
{
RentalCharges[d] = NumbersofDaysBorrowed[d] * 350;
} else if (Booktype[d].equalsIgnoreCase("Novel"))
{
RentalCharges[d] = NumbersofDaysBorrowed[d] * 1500;
} else {
RentalCharges[d] = NumbersofDaysBorrowed[d] * 2500;
}
}
System.out.printf("%s %20s %20s %20s %20s %20s %20s\n", "No", "Name", "Bookname", "AuthorName", "Booktype", "Numbers of Days Borrowed", "Rental Charges");
for (int d = 0; d < inputnum; d = d + 1)
{
int num = d + 1;
System.out.printf("%s %20s %20s %20s %20s %20d %20d\n", num, Name[d], Bookname[d], AuthorName[d], Booktype[d], NumbersofDaysBorrowed[d], RentalCharges[d]);
}
String again = "Yes";
String exist = "No";
while (again.equals("Yes")) {
exist = "No";
System.out.println("enter search name");
String searchname = sc.nextLine();
for (int d = 0; d < inputnum; d = d + 1) {
if (searchname.equals(Name[d])) {
System.out.println("Name : " + Name[d]);
System.out.println("Bookname : " + Bookname[d]);
System.out.println("Number of Days : " + NumbersofDaysBorrowed[d]);
exist = "Yes";
}
}
if (exist.equals("No")) {
System.out.println("The search name is not found");
}
System.out.println("Do you want to search again? (Yes,No) ");
again = sc.nextLine();
}
int max = count[0];
for (int d = 0; d < 7; d = d + 1)
{
for (int k = d + 1; k < 7; k = k + 1)
{
if (count[k] > count[d])
{
max = count[k];
}
else {
max = count[d];
}
}
}
System.out.println("");
System.out.println("The most rented book is: " + max);
System.out.println("");
}
}
Outcome of the program:
No Name Bookname AuthorName Booktype Numbers of Days Borrowed Rental Charges
1 ghjghj hjghjgh hfghg Journal 3 1050
2 hghjhgjhgj uyiuyjghjg ghytghghjg Novel 6 9000
3 bcvnvn dasdasd weqwew Cartoon 5 2500*
I would appreciate it if anyone can help me find this problem.
I suggest solution like below:
This is the fragment of your code:
System.out.println("Enter the number of days that the book had been borrowed:");
NumbersofDaysBorrowed[d] = sc.nextInt();
sc.nextLine();
if (Booktype[d].equalsIgnoreCase("Cartoon")) {
RentalCharges[d] = NumbersofDaysBorrowed[d] * 500;
} else if (Booktype[d].equalsIgnoreCase("Magazine")) {
RentalCharges[d] = NumbersofDaysBorrowed[d] * 1000;
} else if (Booktype[d].equalsIgnoreCase("Short story")) {
RentalCharges[d] = NumbersofDaysBorrowed[d] * 500;
} else if (Booktype[d].equalsIgnoreCase("Long story")) {
RentalCharges[d] = NumbersofDaysBorrowed[d] * 1500;
} else if (Booktype[d].equalsIgnoreCase("Journal")) {
RentalCharges[d] = NumbersofDaysBorrowed[d] * 350;
} else if (Booktype[d].equalsIgnoreCase("Novel")) {
RentalCharges[d] = NumbersofDaysBorrowed[d] * 1500;
} else {
RentalCharges[d] = NumbersofDaysBorrowed[d] * 2500;
}
And under this code try to add this. It replace in array calculated cost of book reduced by discount which is e.g 750 when number of days is more than 5. You can change it like you want
if(NumbersofDaysBorrowed[d] > 5)
{
int bookCost = RentalCharges[d] / NumbersofDaysBorrowed[d];
RentalCharges[d] = (5 * bookCost) + ((NumbersofDaysBorrowed[d] - 5) * (bookCost / 2)); // DISCOUNT
}
My professor told me that I have to Design a class "SharePattern" that has the following two fields: "numberOfDaysInPeriod" and
"SharePointsOnFirstDay".
The class should have a constructor to set the values of these two fields.
In a separate class he said to get user input in the main of my other class. So what goes into the constructor?
First class:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner more = new Scanner(System.in);
System.out.print("Number of days in the period: ");
int input1 = more.nextInt();
while(input1 < 10 || input1 > 20)
{
System.out.println("The number of days that is entered must not be less than 10 and more than 20. The number of days doesn't meet the required criteria, enter it again");
System.out.print("Number of days in the period: ");
input1 = more.nextInt();
}
System.out.print("Share points on the first day: ");
int input2 = more.nextInt();
int half = input1 / 2;
more.close();
SharePattern sp = new SharePattern(input1, input2, half);
sp.findFinalDaySharePoints(input1, input2, half);
}
}
2nd class:
package hw4Question2;
public class SharePattern {
public SharePattern(int input1, int input2, int half)//constructor
{
}
public void findFinalDaySharePoints(int input1, int input2, int half)
{
System.out.println(input2);
if(input1%2 == 0) {
for(int i = 1; i <= input1 ; ++i)
{
if(i<half)
{
input2 = input2 + 50;
System.out.println(input2);
}
else if(i>half)
{
input2 = input2 - 25;
System.out.println(input2);
}
}
}
else
{
for(int i = 1; i <= input1 ; ++i)
{
if(i<=half)
{
input2 = input2 + 50;
System.out.println(input2);
}
else if(i>half)
{
input2 = input2 - 25;
System.out.println(input2);
}
}
System.out.println("The final share value is "+input2);
}
}
}
First class
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner more = new Scanner(System.in);
System.out.print("Number of days in the period: ");
int input1 = more.nextInt();
while(input1 < 10 || input1 > 20)
{
System.out.println("The number of days that is entered must not be less than 10 and more than 20. The number of days doesn't meet the required criteria, enter it again");
System.out.print("Number of days in the period: ");
input1 = more.nextInt();
}
System.out.print("Share points on the first day: ");
int input2 = more.nextInt();
int half = input1 / 2;
more.close();
SharePattern sp = new SharePattern(input1, input2);
sp.findFinalDaySharePoints(half);
}
SharePattern.class
int numberOfDaysInPeriod;
int sharePointsOnFirstDay;
public SharePattern(int input1, int input2) {
this.numberOfDaysInPeriod = input1;
this.sharePointsOnFirstDay = input2;
}
public void findFinalDaySharePoints(int half)
{
System.out.println(sharePointsOnFirstDay);
if(numberOfDaysInPeriod %2 == 0) {
for(int i = 1; i <= numberOfDaysInPeriod; ++i)
{
if(i<half)
{
sharePointsOnFirstDay = sharePointsOnFirstDay + 50;
System.out.println(sharePointsOnFirstDay);
}
else if(i>half)
{
sharePointsOnFirstDay = sharePointsOnFirstDay - 25;
System.out.println(sharePointsOnFirstDay);
}
}
}
else
{
for(int i = 1; i <= numberOfDaysInPeriod; ++i)
{
if(i<=half)
{
sharePointsOnFirstDay = sharePointsOnFirstDay + 50;
System.out.println(sharePointsOnFirstDay);
}
else if(i>half)
{
sharePointsOnFirstDay = sharePointsOnFirstDay - 25;
System.out.println(sharePointsOnFirstDay);
}
}
System.out.println("The final share value is "+ sharePointsOnFirstDay);
}
}
I want to overwrite the first element of my transaction array when it gets full. So when I print the array, it is always showing the latest transactions.
I think the problem is in the moveTrans method or the findNr method but I'm not sure and I can't figure out what is wrong.
Code:
import java.util.Scanner;
import java.util.*;
public class BankoTest {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int amount = 0;
int choice = 0;
int [] trans = new int[4];
int sum;
int balance = 0;
while (choice != 4)
{
choice = menu();
switch(choice)
{
case 1://
System.out.print("Deposit. Amount? :");
amount = scan.nextInt();
balance = balance + amount;
makeTransactions(trans, amount);
break;
case 2://
System.out.print("Withdra. Amount?");
amount = scan.nextInt();
balance = balance - amount;
makeTransactions(trans, -amount);
break;
case 3:
showTransactions(trans, balance);
break;
case 4:
System.out.println("Thank you. ");
break;
}
}
}
public static int menu()
{
Scanner scan = new Scanner(System.in);
int choice = 0;
System.out.println("1. Deposit ");
System.out.println("2. Withdraw ");
System.out.println("3. Saldo ");
System.out.println("4. End ");
System.out.println();
System.out.println("Choice: ");
choice = scan.nextInt();
return choice;
}
public static void showTransactions(int [] trans, int balance)
{
System.out.println();
System.out.println("Transactions summary :");
System.out.println();
for(int i = 0; i < trans.length-1; i++)
{
if(trans[i] == 0)
{
System.out.print("");
}
else
{
System.out.print(trans[i] + "\n");
balance = balance + trans[i];
}
}
// Printing saldo.
System.out.println();
System.out.println("Current balance: " + balance + " kr" + "\n" );
System.out.println();
}
//Puts amount last among the transactions that are stored in the array. Using the findNr method to find the first available spot
//in the array. moveTrans is used to make room for the new transaction when the array is full.
public static void makeTransactions(int [] trans, int amount )
{
int position = findNr(trans);
if(position == -1)
{
moveTrans(trans);
position = findNr(trans);
trans[position] = amount;
}
else
{
trans[position] = amount;
}
}
public static int findNr(int [] trans)
{
int position = -1;
for(int i = 0; i <= trans.length-1; i++)
{
if(trans[i] == 0)
{
position = i;
break;
}
}
return position;
}
public static void moveTrans(int [] trans)
{
for(int i = 0; i < trans.length-1; i++)
trans[0] = trans[i + 1] ;
}
}
just modify the following method alone
public static void makeTransactions(int[] trans, int amount) {
int position = findNr(trans);
if (position == -1) {
moveTrans(trans);
position = findNr(trans);
trans[position] = amount;
} else {
if (position != 0 && position == trans.length - 1) {
// shift the elements back
for (int i = 0; i < position; i++)
trans[i] = trans[i] + 1;
trans[position - 1] = amount;
}else
trans[position] = amount;
}
}
Please check this it may help some thing to you
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int amount = 0;
int choice = 0;
int[] trans = new int[4];
int sum;
int balance = 0;
while (choice != 4) {
choice = menu();
switch (choice) {
case 1://
System.out.print("Deposit. Amount? :");
amount = scan.nextInt();
balance = balance + amount;
makeTransactions(trans, amount);
break;
case 2://
System.out.print("Withdra. Amount?");
amount = scan.nextInt();
balance = balance - amount;
makeTransactions(trans, -amount);
break;
case 3:
showTransactions(trans, balance);
break;
case 4:
System.out.println("Thank you. ");
break;
}
}
}
public static int menu() {
Scanner scan = new Scanner(System.in);
int choice = 0;
System.out.println("1. Deposit ");
System.out.println("2. Withdraw ");
System.out.println("3. Saldo ");
System.out.println("4. End ");
System.out.println();
System.out.println("Choice: ");
choice = scan.nextInt();
return choice;
}
public static void showTransactions(int[] trans, int balance) {
System.out.println();
System.out.println("Transactions summary :");
System.out.println();
for (int i = 0; i < trans.length - 1; i++) {
if (trans[i] == 0) {
System.out.print("");
}
else {
System.out.print(trans[i] + "\n");
// balance = trans[i];
}
}
// Printing saldo.
System.out.println();
System.out.println("Current balance: " + balance + " INR" + "\n");
System.out.println();
}
// Puts amount last among the transactions that are stored in the array.
// Using the findNr method to find the first available spot
// in the array. moveTrans is used to make room for the new transaction when
// the array is full.
public static void makeTransactions(int[] trans, int amount) {
int position = findNr(trans);
if (position == -1) {
moveTrans(trans);
System.out.println("Your transaction limit is over.");
// position = findNr(trans);
// System.out.println("Position -------> "+position);
// trans[position] = amount;
} else {
trans[position] = amount;
}
}
public static int findNr(int[] trans) {
int position = -1;
for (int i = 0; i <= trans.length - 1; i++) {
if (trans[i] == 0) {
position = i;
break;
}
}
return position;
}
public static void moveTrans(int[] trans) {
System.out.println("------Your Transaction Details----------");
for (int i = 0; i < trans.length; i++) {
System.out.println("Transation " + (i + 1) + " :: " + trans[i]);
trans[0] = trans[i];
}
System.out.println("----------------------------------------");
}
I'm trying to make a class where you input any number of grades (A-F) and calculates the GPA and returns the GPA and eligibility to extracurricular activities. It seems like the scanner only allows one input, then prints the GPA and eligibility.
So far this is what I have:
import java.util.Scanner;
public class Grades
{
public static void main(String[] args)
{
double myGPA;
int myNumClasses;
double myValue;
Scanner sc = new Scanner(System.in);
System.out.println("Press any other lettter to calculate.");
System.out.print("Enter grades: ");
String input = sc.nextLine();
myValue = 0;
myNumClasses = 0;
myGPA = 0;
for (String next = sc.next(); input.equalsIgnoreCase("a") || input.equalsIgnoreCase("b") ||
input.equalsIgnoreCase("c")|| input.equalsIgnoreCase("d") || input.equalsIgnoreCase("f"); next = sc.next())
{
if (input.equalsIgnoreCase("a"))
{
myValue += 4.0;
myNumClasses += 1;
}
else if (input.equalsIgnoreCase("b"))
{
myValue += 3.0;
myNumClasses += 1;
}
else if (input.equalsIgnoreCase("c"))
{
myValue += 2.0;
myNumClasses += 1;
}
else if (input.equalsIgnoreCase("d"))
{
myValue += 1.0;
myNumClasses += 1;
}
else if (input.equalsIgnoreCase("f"))
{
myNumClasses += 1;
}
myGPA = myValue / myNumClasses;
if (myGPA >= 2.0 && myNumClasses >= 4)
{
System.out.println("Eligible");
}
else if (myNumClasses < 4)
{
System.out.println("Ineligible, taking less than 4 classes");
}
else if (myGPA >= 2.0 && input.equalsIgnoreCase("f"))
{
System.out.println("Ineligible, gpa above 2.0 but has F grade");
}
else if (myGPA <= 2.0 && input.equalsIgnoreCase("f"))
{
System.out.println("Ineligible, gpa below 2.0 and has F grade");
}
else if (myGPA < 2.0)
{
System.out.println("Inelligible, gpa below 2.0");
}
System.out.println("Your GPA = " + myGPA);
}
}
}
// It looks like your missing a for loop. I just copied some of your
//code and ran it through a for loop. The rest of the code is kind of unclear.
System.out.println("Enter the number of grades you will enter: ");
int userAns = sc.nextInt();
for (int index = 0; index <= userAns; index++)
{
System.out.println("Press any other letter to calculate.");
System.out.print("Enter grades: ");
String input = sc.nextLine();
}