This should be a very basic program but I'm new to Java. I want to be able to input multiple strings into the console using Scanner to detect them. So far I've been able to get the input part right, I wanted the program to run in such a way that the results are displayed when an empty space is entered as opposed to a string. Strangely enough I've only been able to get results when i hit return twice, however, when there are more than 4 inputs hitting return once works. My counter should count the number of "Courses" entered and display them in the results but it gives inaccurate readings.
import java.util.Scanner;
public class Saturn
{
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("For each course in your schedule, enter its building");
System.out.println("code [One code per line ending with an empty line]");
String input;
int counter = 0;
while (!(userInput.nextLine()).isEmpty())
{
input = userInput.nextLine();
counter++;
}
System.out.println("Your schedule consits of " + counter + " courses");
}
}
You're calling Scanner#nextLine twice - once in the while loop expression and again in the body of the loop. You can just assign input from the while loop expression. In addition you can use Scanner#hasNextLine to defend against NoSuchElementException occurring:
while (userInput.hasNextLine() &&
!(input = userInput.nextLine()).isEmpty()) {
System.out.println("Course accepted: " + input);
counter++;
}
Related
The following program is to display the word with maximum number of vowels.But it does not work until i have given 10 variables as input even though it is supposed to end after giving a null input.How can I fix this problem ( I already tried using different inputs like "." and " ")
**
import java.util.*;
public class hw1{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
String w,temp="";
int c=0,max=0;
for(int i=0;i<10;i++)
{
w=sc.next();
w=w.toUpperCase();
if(w.equals(""))
break;
for(int j=0;j<w.length();j++)
{
if(w.charAt(j)=='A'||w.charAt(j)=='E'||w.charAt(j)=='I'||w.charAt(j)=='O'||w.charAt(j)=='U')
c++;
}
max=Math.max(max,c);
if(max==c)
temp=w;
c=0;
}
System.out.println(temp);
}
}
**
sc.next()
does not trigger if you give empty input (or press enter).
For allowing your exit condition to work you should use
w=sc.nextLine();
After that, if you hit enter, the for is broken and the app prints the result
all!
I'm a university freshman computer science major taking a programming course. While doing a homework question, I got stuck on a certain part of my code. Please be kind, as this is my first semester and we've only been doing Java for 3 weeks.
For context, my assignment is:
"Create a program that will ask the user to enter their name and to enter the number of steps they walked in a day. Then ask them if they want to continue. If the answer is "yes" ask them to enter another number of steps walked. Ask them again if they want to continue. If they type anything besides "yes" you should end the program by telling them "goodbye, [NAME]" and the sum of the number of steps that they have entered."
For the life of me, I can not get the while loop to end. It's ignoring the condition that I (probably in an incorrect way) set.
Can you please help me and tell me what I'm doing wrong?
import java.util.Scanner;
public class StepCounter
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
final String SENTINEL = "No";
String userName = "";
String moreNum = "";
int numStep = 0;
int totalStep = 0;
boolean done = false;
Scanner in = new Scanner(System.in);
Scanner in2 = new Scanner(System.in);
// Prompt for the user's name
System.out.print("Please enter your name: ");
userName = in.nextLine();
while(!done)
{
// Prompt for the number of steps taken
System.out.print("Please enter the number of steps you have taken: ");
// Read the value for the number of steps
numStep = in.nextInt();
// Prompt the user if they want to continue
System.out.print("Would you like to continue? Type Yes/No: ");
// Read if they want to continue
moreNum = in2.nextLine();
// Check for the Sentinel
if(moreNum != SENTINEL)
{
// add the running total of steps to the new value of steps
totalStep += numStep;
}
else
{
done = true;
// display results
System.out.println("Goodbye, " + userName + ". The total number of steps you entered is + " + totalStep + ".");
}
}
}
}
To compare the contents of String objects you should use compareTo function.
moreNum.compareTo(SENTINEL) return 0 if they are equal.
== operator is used to check whether they are referring to same object or not.
one more issue with addition of steps, addition should be done in case of "No" entered also
Use
if(!moreNum.equals(SENTINEL))
Instead of
if(moreNum != SENTINEL)
Also, make sure to add: totalStep += numStep; into your else statement so your program will actually add the steps together.
So I'm new to java programming, coming from Python, and there's a few concepts that I can't quite understand.
I'm writing a program which allows the user to enter as many numbers as they want and the program should output the average of all of the numbers. I used a while loop to loop through the inputs by the user as many times as they wanted, but I needed a way of exiting the loop so that the program could proceed with calculating the average of all of the inputs. I decided that if the user enters an "=" sign instead of a number, then the program would break out of the loop, but since the Scanner variable was looking for a double, and the "=" sign is not a number, I would have to make it a String. But because the Scanner is looking for a double, the program threw an error when it encountered the "=".
How can I get the program to exit the loop when the user types "="? I know I could just allow the user to enter a number that breaks the loop, but if it was a real world program and the user entered a number, it would count that number along with the previous ones when calculating the average. The code I have so far is as follows:
import java.util.Scanner;
// imports the Scanner class
public class Average{
public static void main(String[] args){
double num, total = 0, noOfInputs = 0, answer;
Scanner scanner = new Scanner(System.in);
while(true){
System.out.print("Enter number: ");
//Prompts the user to enter a number
num = scanner.nextDouble();
/*Adds the number inputted to the "num" variable. This is the
source of my problem*/
if(num.equals("=")){
break;}
/*The if statement breaks the loop if a certain character is
entered*/
total = total + num;
//Adds the number inputted to the sum of all previous inputs
noOfInputs++;
/*This will be divided by the sum of all of the numbers because
Number of inputs = Number of numbers*/
}
answer = total / noOfInputs;
System.out.print(answer);
}
}
Several ways to do this.
You could read every number as a string, and then if it is a number, parse it to get the value.
Integer.parseInt(String s)
Or you could check what comes next and read accordingly:
while (scanner.hasNext()) {
if (sc.hasNextInt()) {
int a = scanner.nextInt();
} else if (scanner.hasNextLong()) {
//...
}
}
Or you could just catch the InputMismatchException, and work from there.
try{
...
} catch(InputMismatchException e){
//check if '=' ...
}
Could someone please explain how to make the input end when I press . without having to press enter and calculate the length without too much advanced stuff since I am just a beginner.
class UserInput//defines class
{//class begins
public static void main (String[] args) throws IOException
{//main method begins
BufferedReader bf = new BufferedReader(newInputStreamReader(System.in));
//tells the user what the program does
System.out.println("This program will give you the total number of inputed characters.");
// tells the user how to end the program
System.out.println("To obtain your final number of characters, enter .");
System.out.println("");
//tells user to type in characters
System.out.println("Enter any characters you want:");
String input = bf.readLine(); //reads the user input and initializes input
//initialize and declares variables
int length = 0;
length = length + anything.length();
//outputs total number of characters
System.out.println("The total number of characters input is " + length);
}//main method ends
}//class ends
Try reading char by char using System.in.read(). If this doesn't work on your platform, see Why can't we read one character at a time from System.in?
It's not a convention to end commands with "." on command-line -programs. I would suggest you using enter or making a graphical user interface which counts the letters as you type them into textarea using document-listeners or equivalent. The GUI solution is already available at here: show character count in swing gui.
You can try something like this:
Scanner input = new Scanner(System.in);
int totalChars = 0;
// start an endless loop, constantly reading the next entered char from the user
while (true) {
String next = input.next();
if (".".equals(next)) {
// when the user enters ".", exit the loop and stop reading
input.close();
break;
} else {
// otherwise, just increment the total chars counter
totalChars++;
}
}
System.out.println("Total characters: " + totalChars);
The basic idea is to keep reading char by char, until the user chooses to terminate with the "." command. I suggest you swap the BufferedReader for a Scanner. The Scanner class is better suited for reading user input, exposes a more natural and easy to use interface and will help you achieve your goal to the fullest.
I have a college assignment where I need to print out items sold by a hardware store, take input from a user, perform some calculations on that input, and then print out an invoice.
I have been able to successfully print out the items sold by the hardware store, but am encountering problems with the while loop that takes the input.
The program asks the user to enter a CODE and then asks for the corresponding QUANTITY. This works fine on the first iteration of the loop, but on the second iteration the user prompts for "CODE:" and "QUANTITY:" appear on the same line, despite my use of println when prompting the user.
I would greatly appreciate a detailed response appropriate for someone new in programming.
Here's the code:
import java.util.Scanner;
class HardwareStore {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("WELCOME TO THE HARDWARE STORE!");
System.out.println("----------------------------------------------------------------------");
String sticky = "G22";
String keyring = "K13";
String screwy = "S21";
String padlock = "I30";
int stickyprice = 10989;
int keyringprice = 5655;
int screwyprice = 1099;
int padlockprice = 4005;
System.out.println("CODE\t\tDESCRIPTION\t\t\t\t\tPRICE");
System.out.println("----\t\t-----------\t\t\t\t\t-----");
System.out.println(sticky + "\t\tSTICKY Construction Glue, Heavy Duty, \n\t\t7oz, 12 Pack \t\t\t\t\t$" + stickyprice);
System.out.println(keyring + "\t\tCAR-LO Key Ring, Quick Release, \n\t\t1 Pack\t\t\t\t\t\t$ " + keyringprice);
System.out.println(screwy + "\t\t!GREAT DEAL! SCREW-DUP Screwy Screws, \n\t\tDry Wall Screws, 3 in. Long, 50 Pack\t\t$ " + screwyprice);
System.out.println(padlock + "\t\tLET-IT-RAIN, Weather Proof Padlock, \n\t\tPortable, One Push Functionality\t\t$ " + padlockprice);
System.out.println("----------------------------------------------------------------------");
int i = 10000;
String [] usercode = new String[i];
int [] userquantity = new int[i];
System.out.println("PLEASE ENTER YOUR ORDER:");
while (true) {
System.out.println("CODE: (X to terminate)");
usercode[i] = in.nextLine();
if (usercode[i].equalsIgnoreCase("x")) {
break;
}
System.out.println("QUANTITY: ");
userquantity[i] = in.nextInt();
}
}
}
when you enter the QUANTITY you're pressing enter. That newline character isn't used by in.nextInt();, it remains in the scanner buffer, until you roll around to in.nextLine() again.
At that point in.nextLine() reads until it finds a newline character, which just happens to be the next one in the buffer. So it skips straight to QUANTITY again.