Begining Java student [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am writing a program where i have to use methods to count my string, .upper and lower using a switch statement. My code is not showing any errors can someone help.
import java.util.*;
public class Strings
{
public static void main(String[] args)
{
String selection;
Scanner keyboard = new Scanner(System.in);
System.out.println("*********** EXAM 3 ENTER A STRING *************");
System.out.println("Enter 1 to display the number of words in the string");
System.out.println("Enter 2 to display the string in all capital letters");
System.out.println("Enter 3 to display the string in all lower case letters");
System.out.println("Enter 4 to display the string in reverse order");
System.out.println("Enter -1 to exit");
selection = keyboard.nextLine();
switch(selection.charAt(0))
{
case 1:
numberOfWords(selection);
break;
case 2:
allCapitals(selection);
break;
case 3:
allLowers(selection);
break;
case 4:
reverseOrder(selection);
break;
}//ends switch
}
/*public static void menuMethod(String [] args)
{
Scanner input = new Scanner(System.in);
System.out.println("*********** EXAM 3 ENTER A STRING *************");
System.out.println("Enter 1 to display the number of words in the string");
System.out.println("Enter 2 to display the string in all capital letters");
System.out.println("Enter 3 to display the string in all lower case letters");
System.out.println("Enter 4 to display the string in reverse order");
System.out.println("Enter -1 to exit");
}
*/
public static void numberOfWords(String selection)
{
String input; // To hold input
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a string: ");
input = keyboard.nextLine();
// Display the number of words.
System.out.println("That string has " + wordCount(input) + " words in it.");
}
public static int wordCount(String str)
{
StringTokenizer strTok = new StringTokenizer(str);
return strTok.countTokens();
}
public static void allCapitals (String str)
{
String input;
String capInput;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a string. ");
input = keyboard.nextLine();//You must use nextLine here next will not work.
capInput = input.toUpperCase();
System.out.println("Your capital case string = \n" + capInput);
}
public static void allLowers (String str)
{
String input;
String lowerInput;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a string. ");
input = keyboard.nextLine();//You must use nextLine here next will not work.
lowerInput = input.toUpperCase();
System.out.println("Your lower case string = \n" + lowerInput);
}
public static void reverseOrder (String str)
{
String input; // To hold input
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter something: ");
input = keyboard.nextLine();
// Display it backwards.
backward(input);
}
public static void backward(String str)
{
for (int i = str.length() - 1; i >= 0; i--)
System.out.print(str.charAt(i));
System.out.println();
}
}

Please use this code for switch
switch(selection.charAt(0))
{
case '1':
numberOfWords(selection);
break;
case '2':
allCapitals(selection);
break;
case '3':
allLowers(selection);
break;
case '4':
reverseOrder(selection);
break;
}//ends switch

replace your switch condition to
switch(Integer.parseInt(selection))
{
//your code
}
instead of
switch(selection.charAt(0))
{
//your code
}
if you use charAt(0) your checking condition must be like that because that method returns a char value
case '1':
numberOfWords(selection);
break;
case '2':
allCapitals(selection);
break;
case '3':
allLowers(selection);
break;
case '4':
reverseOrder(selection);
break;

You haven't said what is wrong with the program output. Explaining your problem as thoroughly as possible will help you get a good answer quickly.
As for possible problems:
Your allLowers() method is using toUpperCase(). As a good design practice, try to copy paste code as little as possible, since copy/pasting code implies that there could be a function that does the same thing.
You are never actually checking for an input of -1. All you would do in your current method (if you were to check for the exit condition) is check for the - sign as that is the first character, rather that the entire -1 string, which could easily lead to bugs if you expand the program.

Related

How to re-write an input loop to not contain code repetition?

I have the following code, which continues to ask the user to enter a letter as long as the letter is either "a" or "b":
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String letter;
System.out.print("Enter a letter: ");
letter = scan.nextLine();
while(letter.equals("a") || letter.equals("b"))
{
System.out.println("You entered: " + letter);
System.out.print("Enter a letter: ");
letter = scan.nextLine();
}
}
}
But the following code is repeated twice:
System.out.print("Enter a letter: ");
letter = scan.nextLine();
Is there a way to make the above code only appear one time?
while (true) {
System.out.print("Enter a letter: ");
String letter = scan.nextLine();
if (!letter.equals("a") && !letter.equals("b"))
break;
System.out.println("You entered: " + letter);
}
This is the classic example of a loop that is neither naturally while-do nor do-while — it needs to exit from the middle, if you want the same behavior and also to reduce code duplication.
(Notice also that the variable declaration letter has been moved to an inner scope since it is no longer needed in the outer scope.  This is a small positive indication.)
As an alternative to while (true) some languages allow degenerate for-loop as in for(;;).
The below reverses the logic of the conditional loop exit test, at the expense of more control flow logic.
while (true) {
System.out.print("Enter a letter: ");
String letter = scan.nextLine();
if (letter.equals("a") || letter.equals("b")) {
System.out.println("You entered: " + letter);
continue;
}
break;
}
(There is no difference between these in efficiency terms — these are equivalent at the level of machine code.)
do while loop
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String letter;
do{
System.out.print("Enter a letter: ");
letter = scan.nextLine();
System.out.println("You entered: " + letter);
}while(letter.equals("a") || letter.equals("b"));
}
}
It will loop once first, and then continue again if the statment is true.
You need to perform three sequential actions in a loop:
read the input entered by the user;
validate the input;
print the input, but only if it is valid.
That means that conditional logic must reside inside the loop before the statement that prints the input. And that makes the condition of the loop redundant. Instead, we can create an infinite loop with a break statement wrapped by a condition, that validates the input.
While loop
That's how it can be done using a while loop:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String letter;
while (true) {
System.out.print("Enter a letter: ");
letter = scan.nextLine();
if (!letter.matches("[ab]")) break;
System.out.println("You entered: " + letter);
}
}
Method matches() that expects a regular expression as argument is used in the code above to simplify the termination condition.
For more information on regular expressions, take a look at this tutorial
For loop
Regarding the advice of utilizing a for loop - that's doable, but by its nature the task of reading the user input fits better in the concept of while loop because we don't know the amount of data in advance, and the iteration can terminate at any point in time.
Also note syntax of the for statement consists of three parts separated with a semicolon:
initialization expression - allow to define and initialize variables that would be used in the loop;
termination expression - condition which terminates the execution of the loop;
increment expression - defines how variables would change at each iteration step.
All these parts are optional, but the two semicolons ; inside the parentheses always have to be present.
Because as I've said earlier, the input needs to be validated inside the loop, we can't take advantage from the termination expression and increment expression.
For the sake of completeness, below I've provided the version of how it can be achieved using a for loop:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
for (String letter = "a"; ;) {
System.out.print("Enter a letter: ");
letter = scan.nextLine();
if (!letter.matches("[ab]")) break;
System.out.println("You entered: " + letter);
}
}
The only advantage is that the scope of the variable letter was reduced. But approach of utilizing while loop is more readable and expressive.
Alternative approach
Another option is to preserve your initial structure of the code:
initialize the variable letter before the loop, at the same line where it is defined;
enter the loop if letter holds a valid input;
print the input and reassign the variable.
But in order to avoid duplication of the code line responsible for printing the prompt and reading the input will be extracted into a separate method.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String letter = readInput(scan);
while (letter.matches("[ab]")) {
System.out.println("You entered: " + letter);
letter = readInput(scan);
}
}
public static String readInput(Scanner scan) {
System.out.print("Enter a letter: ");
return scan.nextLine();
}
As Bobulous mentioned, a do-while loop is another simple solution. If duplicating the conditional is still a deal-breaker for you, though, you can also create a function that returns a boolean, and, when true, prints the extra text.
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String letter;
do
{
System.out.print("Enter a letter: ");
letter = scan.nextLine();
} while(inputIsAOrB(letter));
}
public static boolean inputIsAOrB(String input) {
if (input.equals("a") || input.equals("b"))
{
System.out.println("You entered: " + input);
return true;
}
else
{
return false;
}
}
A while loop with a break after executing your second print command will limit the code to only asking for a single input.
Scanner ct = new Scanner(System.in);
String input;
System.out.print("Please enter either 'a' or 'b': ");
input = ct.nextLine();
while(input.equals("a") || input.equals("b")){
System.out.println("You entered: " + input);
break;
}
You can also view the problem as generating and processing a stream of strings. The side effects in the generator may trigger some philosophical discussions, otherwise I think it is quite clean:
Stream.generate(() -> {
System.out.print("Enter a letter: ");
return scan.nextLine();
})
.takeWhile(str -> str.equals("a") || str.equals("b"))
.forEach(str -> System.out.println("You entered: " + str));
... which will run like this:
Enter a letter: a
You entered: a
Enter a letter: b
You entered: b
Enter a letter: c
Process finished with exit code 0
Simply
List<Character> expectedChars = new ArrayList<>();
expectedChars.add('a');
expectedChars.add('b');
while(!expectedChars.contains(line = scan.nextLine())) {
System.out.println("Not expected");
}
// Now has a expected char. Proceed.
I without using any break or if-else externally (I am using ternary operator though) within control loop, you can also use below :
Scanner scanner = new Scanner(System.in);
boolean flag=true;
while (flag) {
System.out.println("enter letter");
String bv = scanner.nextLine();
flag=bv.matches("a|b");
System.out.println(flag?"you entered"+bv:' ');
}
with for loop, it can be even simpler :
Scanner scanner = new Scanner(System.in);
for (boolean flag = true; flag;) {
System.out.println("enter letter");
String bv = scanner.nextLine();
flag = bv.matches("a|b");
System.out.println(flag ? "you entered" + bv : ' ');
}
Or if you ok for having whitspace for first run:
Scanner scanner = new Scanner(System.in);
String aa=" ";
String bv=null;
for (boolean flag = true; flag;aa=(flag?"you entered: "+bv:" ")) {
System.out.println(aa);
System.out.println("enter letter");
bv = scanner.nextLine();
flag = bv.matches("a|b");
}
You can easily run a while loop until letter = "a" or letter = "b". Code will start the while loop with intial "" value of the letter and get the new value by scanner. Then it check the new value of the letter before starting the next round of the loop.
package com.company;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String letter = "";
while(!(letter.equals("a") || letter.equals("b")))
{
System.out.print("Enter a letter: ");
letter = scan.nextLine();
System.out.println("You entered: " + letter);
}
}
}
Similar as previous answer, but from a code readability perspective i would create an array of valid characters instead and use in condition. That results in the more "text like" condition below reading "if not validCharacters contains letter":
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
List<String> validCharacters = List.of("a", "b");
while (true) {
System.out.print("Enter a letter: ");
String letter = scan.nextLine();
if (!validCharacters.contains(letter)) {
break;
}
System.out.println("You entered: " + letter);
}
}
Your code just needed a little tweak to make it work, although you can use many more efficient approaches but here it is:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String letter = "a";
while(letter.equals("a") || letter.equals("b"))
{
System.out.print("Enter a letter: ");
letter = scan.nextLine();
System.out.println("You entered: " + letter);
}
}
}

Calculator Java Input [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I'm trying to make a calculator in java that can multiply subtract and add depending if the user wants that they can choose what they want. For some reason its giving me a weird output
Code
import java.util.Scanner; // Import the Scanner class
public class calculator {
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
//System.in is a standard input stream
System.out.print("Enter first number- ");
int a = sc.nextInt();
System.out.print("Enter second number- ");
int b = sc.nextInt();
System.out.print("Do you want to multiply, add, divide, or subtract? ");
String c = sc.nextLine();
switch(c) {
case "multiply":
System.out.print(a * b);
break;
case "add":
System.out.print(a * b);
break;
default:
System.out.print("Invalid input!");
}
}
}
Output
Enter first number- 2
Enter second number- 2
Do you want to multiply, add, divide, or subtract? Invalid input!
Like I didnt even type Invalid input it just does it by itself for some reason
There can be input left in the scanner before you request a value. In this case, the line break marks the end of the integer, but is not consumed as part of the integer. The call to nextLine() sees there is already an unused line break at the end of the buffer and returns that result. In this case, an empty string is returned. One way to fix this is to consume that unused line break first before requesting the next line or requesting a full line then parsing an integer from it.
Scanner scan = new Scanner(System.in);
// Always request a full line
int firstInt = Integer.parse(scan.nextLine());
int secondInt = Integer.parse(scan.nextLine());
String option = scan.nextLine();
// Use an extra call to nextLine() to remove the line break causing the issues
int firstInt = scan.nextInt();
int secondInt = scan.nextInt();
scan.nextLine(); // Consume the unused line break
String option = scan.nextLine();
sc.nextInt() does not read the enter key that you entered, so sc.nextLine() will read that new line and return it. Use sc.next() instead of sc.nextLine() to avoid this issue. Your code also multiplies the numbers when the user inputs add, so I changed that as well.
import java.util.Scanner; // Import the Scanner class
public class calculator {
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
//System.in is a standard input stream
System.out.print("Enter first number- ");
int a = sc.nextInt();
System.out.print("Enter second number- ");
int b = sc.nextInt();
System.out.print("Do you want to multiply, add, divide, or subtract? ");
String c = sc.next();
switch(c) {
case "multiply":
System.out.print(a * b);
break;
case "add":
System.out.print(a + b);
break;
default:
System.out.print("Invalid input!");
}
}
}

How to correct the scope of a variable that is created within a do-while loop?

I am struggling to get the correct scope for my variable "input".
I am making a calculator for a university task, and I've got everything working apart from when I tried to make it loop by wrapping my main code in a do-while loop. Because the variable "input" is declared in the "do" part of the loop, it didn't know what it was when I was trying to use it in the "while" condition. To fix this I then declared "input" as a string before my do-while loop to make it a global. However, now the scanner that takes the value of input will not work.
AM I doing something stupid or am I missing something?
import java.util.Scanner;
public class Calculator {
public static void main(String [] args) {
String input;
do {
System.out.println("Welcome to the calculator. Please enter an operator (+, -, /, *) below:");
Scanner myScanner = new Scanner(System.in);
String oper = myScanner.nextLine();
System.out.println("Now please enter two numbers:");
double a = myScanner.nextDouble();
double b = myScanner.nextDouble();
switch (oper) {
case "+" :
System.out.println(CalculatorUtils.add(a, b));
break;
case "-" :
System.out.println(CalculatorUtils.subtract(a, b));
break;
case "/" :
System.out.println(CalculatorUtils.divide(a, b));
break;
case "*" :
System.out.println(CalculatorUtils.multiply(a, b));
break;
}
System.out.println("Do you want to complete another calculation? (y/n)");
input = myScanner.nextLine();
}
while (input.contentEquals("y"));
}
}
I expect this to be the output:
Welcome to the calculator. Please enter an operator (+, -, /, *) below:
+
Now please enter two numbers:
32.5
12.5
45.0
Do you want to complete another calculation? (y/n)
y
(This is where the code would start again)
However I'm not being able to enter my input when being asked if I would like to do another calculation.
Here is the fix.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
String input;
do {
System.out.println("Welcome to the calculator. Please enter an operator (+, -, /, *) below:");
Scanner myScanner = new Scanner(System.in);
String oper = myScanner.nextLine();
System.out.println("Now please enter two numbers:");
double a = myScanner.nextDouble();
double b = myScanner.nextDouble();
switch (oper) {
case "+":
System.out.println(CalculatorUtils.add(a, b));
break;
case "-":
System.out.println(CalculatorUtils.subtract(a, b));
break;
case "/":
System.out.println(CalculatorUtils.divide(a, b));
break;
case "*":
System.out.println(CalculatorUtils.multiply(a, b));
break;
}
myScanner.nextLine();
System.out.println("Do you want to complete another calculation? (y/n)");
input = myScanner.nextLine();
myScanner.nextLine();
}
while (input.contentEquals("y"));
}
}
It happens because second time you call myScanner.nextLine() it just scans enter from before. It will happen after myScanner.nextDouble() but not after myScanner.nextLine() because myScanner.nextLine() reads/scans until including next newLine character (\n) whereas myScanner.nextDouble() will just scan a double and leave.
Here is similar thread
What you do not want to do is create a Scanner on every trip around the loop. Move the definition and initialization of your Scanner variable outside the loop:
String input;
Scanner myScanner = new Scanner(System.in);
do {
System.out.println("Welcome to the calculator. Please enter an operator (+, -, /, *) below:");
String oper = myScanner.nextLine();
// rest of loop...
} while (input.contentEquals("y"));
This may or may not solve you're immediate problem, but it's still the right thing to do in general.

Is there anyway to match answers and questions in String array

I am trying to code a word game. There are questions which is shown randomly and user try to answer right.
I matched questions and answers with switch case but I can't check if it is right or not because I can't figure out how can I find words in String array. Also, there is an error in the switch-case because of the method.
import java.util.Scanner;
import java.util.Random;
public class Odev {
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
System.out.println("Enter the 1 for answer or 2 for requesting a letter.");
int first= input.nextInt();
String[] question = new String[9];
String [] answer=new String[9];
question=array(question);
answer=array2(answer);
Random b= new Random();
int randomNumber=b.nextInt(question.length);
if(first==1) {
System.out.println(question[randomNumber]);
System.out.println(randomNumber);
String a1=input.next();
switch (randomNumber) {
case 0: equalM(a1, answer[0]);
break;
case 1: equalM(a1, answer[1]);
break;
case 2:equalM(a1, answer[2]);
break;
case 3:equalM(a1, answer[3]);
break;
case 4:equalM(a1, answer[4]);
break;
case 5:equalM(a1, answer[5]);
break;
case 6:equalM(a1, answer[6]);
break;
case 7:equalM(a1, answer[7]);
break;
case 8:equalM(a1, answer[8]);
break;
}
}
}
public static String [] array(String [] question) {
question[0]="A beverage which is white and generally consumed in mornings";
question[1]="The natural satellite of earth";
question[2]="An adjective which describes people who have not adequate money";
question[3]="A furniture sit around for eating or studying";
question[4]="A group that consists a lot of soldier";
question[5]="A fruit which can be red, yellow and green";
question[6]="A tool for writing which consists graphite";
question[7]="A beverage which is consumed by people who need caffeine ";
question[8]="A term which is stand for the smallest group of the society ";
return question;
}
public static String [] array2(String [] answer) {
answer[0]="milk";
answer[1]="moon";
answer[2]="poor";
answer[3]="table";
answer[4]="army";
answer[5]="apple";
answer[6]="pencil";
answer[7]="coffee";
answer[8]="family";
return answer;
}
public static String[] equalM(String a1, String[] answer) {
for (int i=0; i<answer.length; i++) {
if(a1.equals(answer[i])) {
System.out.println("Correct you gained 500 points");
} else
System.out.println("Wrong.You lost 500 points");
}
return answer;
}
}
You could use a hashmap to do this easily, but if you want to stick with arrays, you could print out all the answer choices along with their index number, and then read in the number the user types in for the correct answer. You then just have to check if that number is equal to the random number used to generate the question.

Same code but different output

First i want user to input somethings(name,contact,idnumber),and i will show 2 different file but code are same.The first code problem is "name" input place disappear,and the second but doesn't disappear.Can anyone tell me the problem?Im new in java.
public class Admin {
static Scanner scan= new Scanner(System.in);
static Client client = new Client();
public void admin(){
newClient []nc = new newClient[10];
\\login();
while(true){
System.out.println("Select 1:add Client\n 2:add Account\n 3:login as Client");
try{
int selection = scan.nextInt();
switch(selection)
{
case 1: addClient(nc);
break;
case 2: \\addAccount(nc);
break;
case 3: ;
break;
default: System.out.println("INvalid selection");
}
}
catch(InputMismatchException ex){
System.out.println("Invalid input");
scan.nextLine();
}
}
}
public void addClient(newClient []nc){
for(int i=0;i<nc.length;i++){
System.out.println("Enter name");
String name = scan.nextLine();
System.out.println("Enter contact");
String contact = scan.nextLine();
System.out.println("Enter id number");
String idNumber = scan.nextLine();
nc[i]=new newClient(name,contact,idNumber);
System.out.println(nc[i]);
}
}
Output of the first code is
Enter name
Enter contact
Why the name input place is missing?
There are the second code
public static void main(String[]args){
Scanner scan =new Scanner(System.in);
for(int i=0;i<nc.length;i++){
System.out.println("Enter name");
String name = scan.nextLine();
System.out.println("Enter contact");
String contact = scan.nextLine();
System.out.println("Enter id number");
String idNumber = scan.nextLine();
nc[i]=new newClient(name,contact,idNumber);
System.out.println(nc[i]);
}
}
The second code is working correctly.
Enter name
Enter contact
Enter idNumber
The two pieces of code are in fact different.
In the second code, the scan object is a brand new one. And the only method you call is nextLine(). In the first code, the scan object is created an class level, and has been used before addClient is called.
"Has been used" here is very important. By that I mean you called nextInt on scan and then nextLine:
int selection = scan.nextInt(); <-- You called nextInt here!
switch(selection)
{
case 1: addClient(nc);
break;
case 2: \\addAccount(nc);
break;
case 3: ;
break;
default: System.out.println("INvalid selection");
}
}
catch(InputMismatchException ex){
System.out.println("Invalid input");
scan.nextLine();
}
}
}
public void addClient(newClient []nc){
for(int i=0;i<nc.length;i++){
System.out.println("Enter name");
String name = scan.nextLine(); <-- then you called nextLine here!
System.out.println("Enter contact");
String contact = scan.nextLine();
System.out.println("Enter id number");
String idNumber = scan.nextLine();
nc[i]=new newClient(name,contact,idNumber);
System.out.println(nc[i]);
}
}
This makes the nextLine method return an empty string.
Why?
Let's look at the documentation for both nextInt and nextLine:
nextInt()
Scans the next token of the input as an int.
nextLine()
Advances this scanner past the current line and returns the input that was skipped.
I have created a simpler code that reproduces this situation to explain why calling nextLine immediately after nextInt can cause problems:
Scanner s = new Scanner(System.in);
s.nextInt();
System.out.println(s.nextLine());
I will use a | character to denote where the scanner's current position is.
When the program starts,
|
Then I enter the number 20:
|20
Now the scanner reads the 20, according the documetation, the scanner should be at this position:
20|
Here comes the interesting part, nextLine "Advances this scanner past the current line and returns the input that was skipped."
20
|
So what input has the scanner skipped? Nothing! As a result, an empty string is returned.
as ΦXocę 웃 Пepeúpa ツ says scan.nextInt wouldnt read the enter.
so an alternative solution is before read name contact id information, employ scan.nextLine() to read the enter like this:
public void addClient(newClient []nc){
scan.nextLine();
for(int i=0;i<nc.length;i++){
....// your origin code
}

Categories