Current If statement involving String - java

Essentially my assignment is supposed to take 2 words, calculate the smallest of the two which I have done, but now I need to reference the smallest word itself instead of the number. Which I believe requires an If statement, but I cannot get my String to initialize and the console gets picky when I end the program with the system.out.println command.
Scanner scan = new Scanner(system.In);
System.out.println(" Input first password ");
String pass1 = scan.nextLine();
Int pass1l = pass1.length();
System.out.println(" input second password ");
String pass2 = scan.nextLine();
Int pass2l = pass2.length();
Int spassl = Math.min(pass1l,pass2l);
// problematic part here.
String spass;
If (pass1l > pass2l){ spass = pass2}
else if (pass1l < pass2l) {spass = pass1}
else if (pass1l == pass2l) {spass = null;};
Also the Else if statements come up as not statements and the first is an illegal start of an expression.
Then if I fix those I call spass with system.out and it says it's not initialized. I just started learning basic Java, I've used processing before but not for String related if statements, only integers.

You are almost there. the variable spass needs to be initialized as you are using if blocks without final else. Either you give spass="" or change final else if to else as below.
Scanner scan = new Scanner(System.in);
System.out.println(" Input first password ");
String pass1 = scan.nextLine();
System.out.println(" input second password ");
String pass2 = scan.nextLine();
// problematic part here.
String spass;
if (pass1.length() > pass2.length()) {
spass = pass2;
} else if (pass1.length() < pass2.length()) {
spass = pass1;
} else {
spass = null;
}
System.out.println("result: " + spass);

your problem is just a formating problem, if statements are formatet like this:
if(condition){
do_something;
}else if( second_condition ){
do_something_else;
}else{
alternative;
}
In your case it seems that you dont know where to set semicolons ;
You have to set semicolons inside the if block like this:
String spass;
If (pass1l > pass2l){
//Here semicolon
spass = pass2;
} else if (pass1l < pass2l) {
//Here semicolon
spass = pass1;
}else if (pass1l == pass2l) {
//Here semicolon
spass = null;
}
//No semicolon at the end of the if-else-statement

Related

How to resolve the following program with a for loop into producing an appropriate output?

The following Java program is supposed to manipulate a string input by the user in such a way that the user will decide which character needs to be replaced with another and just the last character from the string should be replaced. Example if the user enters the string "OYOVESTER" and decides to replace "O" with "L", the program should output the following result: "OYLVESTER" (notice that only the last "O" was replaced with "L")
NOTE: YOU CANNOT USE BREAK COMMAND TO STOP THE LOOP. IT IS PROHIBITED.
import java.util.Scanner;
public class StringFun {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
String inString = keyboard.nextLine();
String outString = "";
//Replace Last
System.out.println("Enter the character to replace");
char oldCharF = keyboard.next().charAt(0);
System.out.println("Enter the new character");
char newCharF = keyboard.next().charAt(0);
int count = 0; // variable that tracks number of letter occurrences
for(int index = inString.length() - 1;index >= 0;index--) {
if(inString.charAt(index) == oldCharF && count < 1){
outString = newCharF + outString;
outString = outString + inString.substring(0,index);
count++;
}
if (count < 1) {
outString = outString + inString.charAt(index);
}
}
System.out.print("The new sentence is: "+outString);
}
}
I keep getting the following output which is incorrect:
Enter the string to be manipulated
OYOVESTER
Enter the character to replace
O
Enter the new character
L
The new sentence is: LRETSEVOY
There are many simpler ways to achieve your requirement but I hope you have to demonstrate this with loops (without breaks)
Then you can use some thing like this :
boolean skip = false;
for (int index = inString.length() - 1; index >= 0; index--) {
if (!skip && inString.charAt(index) == oldCharF) {
outString = newCharF + outString;
skip = true;
}
else {
outString = inString.charAt(index) + outString;
}
}
PS : Using String concatenation inside loops is not recommended since
every String concatenation copies the whole String, usually it is preferable to
replace it with explicit calls to StringBuilder.append() or StringBuffer.append()
No break command seems like a weird condition. You could just a boolean value, and other methods, to break the loop when you need. Why not do something like this?
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
String word = keyboard.nextLine();
//Replace Last
System.out.println("Enter the character to replace");
char oldCharF = keyboard.next().charAt(0);
System.out.println("Enter the new character");
char newCharF = keyboard.next().charAt(0);
int index = word.lastIndexOf(oldCharF);
if(index > 1){
word = word.substring(0,index) + newCharF + word.substring(index+1);
}
System.out.println("The new sentence is: " + word);
}

Using || in while loop makes it take too many input values

public class MetricConversion {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
String masses = "null";
String volumes = "null";
String temps = "null";
String lengths = "null";
int answer1 = 0;
String[] options = {"Mass = 1","Temperature = 2","Length = 3","Volume = 4"};
System.out.println("What would you like to convert?");
for(int i = 0;i<options.length;i++)
System.out.println(options[i]);
while(!input.hasNextInt() || input.nextInt() > options.length)
{
String garbage = input.nextLine();
System.out.println("That input is not valid, try again");
}
answer1 = input.nextInt();
input.nextLine();
The problem I am having is that the
while(!input.hasNextInt() || input.nextInt() > options.length)
is taking 2 valid inputs instead of 1 in order to make
answer1 = input.nextInt();
For example, when entering an invalid input it correctly prints my error message, but when entering a valid input I have to enter it twice in order to break the loop. However if I use the while loop without the || it only takes one value like it's supposed to.
You're consuming the value without assigning it to a variable. You can assign it within the loop condition like this:
while(!input.hasNextInt() || (answer1 = input.nextInt()) > options.length)
You are consuming scanner argument in while loop:
while(!input.hasNextInt()){
int argument = input.nextInt();
if(argument > options.length){
System.out.println("That input is not valid, try again");
continue; // get back to the start
}
// correctly handle your argument
}

Java: How do I ensure, or make a user, input a comma in a string?

First off, I am brand new to both Java and to this website. I am going to ask my question as thoroughly as I can. However, please let me know if you think I left something out.
I am working on a school assignment, and I am stuck on the second portion of it. I am able to prompt the user, but can not for the life of me, figure out how to ensure that the input string contains a comma. I did try searching this site, as well as Googling it, and haven't been able to find anything. Perhaps I am not wording the question appropriately.
(1) Prompt the user for a string that contains two strings separated by a comma.
(2) Report an error if the input string does not contain a comma. Continue to prompt until a valid string is entered. Note: If the input contains a comma, then assume that the input also contains two strings.
So far I have this:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // Input stream for standard input
Scanner inSS = null; // Input string stream
String lineString = ""; // Holds line of text
String firstWord = ""; // First name
String secondWord = ""; // Last name
boolean inputDone = false; // Flag to indicate next iteration
// Prompt user for input
System.out.println("Enter string seperated by a comma: ");
// Grab data as long as "Exit" is not entered
while (!inputDone) {
// Entire line into lineString
lineString = scnr.nextLine();
// Create new input string stream
inSS = new Scanner(lineString);
// Now process the line
firstWord = inSS.next();
// Output parsed values
if (firstWord.equals("q")) {
System.out.println("Exiting.");
inputDone = true;
if else (lineString != ",") { // This is where I am stuck!
System.out.print("No comma in string");
}
} else {
secondWord = inSS.next();
System.out.println("First word: " + firstWord);
System.out.println("Second word: " + secondWord);
System.out.println();
}
}
return;
}
}
I know my "if else" is probably not correct. I just don't know where to begin for this particular command. Unfortunately my eBook chapter did not cover this specifically. Any thoughts would be greatly appreciated. Thank you so much!
I suspect you want to assert if the input contains a comma, and at least one letter either side. For this you need regex:
if (!input.matches("[a-zA-Z]+,[a-zA-Z]+")) {
System.out.print("Input not two comma separated words");
}
Since you are looking for a string with a comma in it and you want to get the string “Before” the comma and the string “After” the comma, then string.split(‘,’) is what you want. Asking if the string “Contains” a comma gives you no information about the string before or after the comma. That’s where string.split() helps. Since you don’t care “Where” the comma is you simply want the string before the comma and the string after the comma. The string.split(‘,’) method will return a string array containing the strings that are separated by commas (in your case) or any character.
Example:
string myString = “firstpart,secondpart”;
… then
string[] splitStringArray = myString.Split(‘,’)
This will return a string array of size 2 where
splitStringArray[0] = “firstpart”
splitStringArray[1] = “secondpart"
with this info you can also tell if the user entered the proper input… i.e…
if the splitStringArray.Length (or Size) = 0, then the user did not input anything, if the splitStringArray.Length (or Size) = 1 then the user input 1 string with no commas… might check for exit here. If the splitStringArray.Length (or Size) = 2 then the user input the string properly. if the splitStringArray.Length (Size) > 2 then the user input a string with more than 1 comma.
I hope that helps in describing how string.split works.
Your code however needs some work… without going into much detail below is a c# console while loop as an example:
inputDone = false;
while (!inputDone)
{
Console.Clear();
Console.WriteLine("Enter string seperated by a comma: ");
lineString = Console.ReadLine();
string[] splitStringArray = lineString.Split(',');
// check for user to quit
if (splitStringArray.Length == 1)
{
if (splitStringArray[0] == "q")
{
inputDone = true;
Console.Clear();
}
else
{
// 1 string that is not "q" with no commas
}
}
if (splitStringArray.Length == 2)
{
// then there are exactly two strings with a comma seperating them
// or you may have ",string" or "string,"
Console.WriteLine("First word: " + splitStringArray[0]);
Console.WriteLine("Second word: " + splitStringArray[1]);
Console.ReadKey();
}
else
{
Console.WriteLine("Input string empty or input string has more than two strings seperated by commas");
Console.ReadKey();
}
}
Hope that helps.
This worked for me:
import java.util.Scanner;
import java.io.IOException;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
Scanner inSS = null;
String lineString = "";
String firstWord = "";
String nextWord = "";
System.out.println("Enter input string: ");
while (lineString.matches("q") == false) {
lineString = scnr.nextLine();
lineString = lineString.replaceAll(",",", ");
inSS = new Scanner(lineString);
int delimComma = lineString.indexOf(",");
if ((delimComma <= -1) && (lineString.matches("q") == false)) {
System.out.println("Error: No comma in string");
System.out.println("Enter input string: ");
}
else if ((delimComma <= -1) && (lineString == null || lineString.length() == 0 || lineString.split("\\s+").length < 2) && (lineString.matches("q") == false)) {
System.out.println("Error: Two words");
System.out.println("Enter input string: ");
}
else if (lineString.matches("q") == false) {
firstWord = inSS.next();
nextWord = inSS.nextLine();
System.out.println("First word: " + firstWord.replaceAll("\\s","").replaceAll("\\W","").replaceAll("\\n",""));
System.out.println("Second word: " + nextWord.replaceAll("\\s","").replaceAll("\\W","").replaceAll("\\n",""));
System.out.println("\n");
System.out.println("Enter input string: ");
}
continue;
}
return;
}
}

Java Initializing Variable Error

I have an error that says I haven't initialized my firstline, secondLine, and thirdLine variables in the buffer.write(variable); lines with variable being firstLine, secondLine & thirdLine. This error didn't appear until I added while(number == null || number.equals("")) around the variable == JOptionPane.showInputDialog("Enter name"); lines in my code. Is there any way to handle this error while keeping my added code in?
import java.awt.Graphics;
import javax.swing.JOptionPane;
import java.io.*;
import java.io.FileWriter;
public class CreateData {
public static void main(String[] args)
{
JOptionPane.showMessageDialog(null,
"this program writes payroll data",
"Welcome", JOptionPane.PLAIN_MESSAGE);
Write();
}
static void Write()
{
try {
String firstLine, secondLine, thirdLine, number = " ";
File check = new File("payroll.txt");
FileWriter file;
if(check.exists())
file = new FileWriter("payroll.txt", true);
else
file = new FileWriter("payroll.txt");
BufferedWriter buffer = new BufferedWriter(file);
int size, count = 1;
while(number == null || number.equals(""))
{
number = JOptionPane.showInputDialog("how many records?");
}
size = Integer.parseInt(number);
do {
while(number == null || number.equals(""))
{
firstLine = JOptionPane.showInputDialog("Enter name");// prompts for input and displays "Enter Name"
}
while(number == null || number.equals(""))
{
secondLine = JOptionPane.showInputDialog("Enter hours");
}
while(number == null || number.equals(""))
{
thirdLine = JOptionPane.showInputDialog("Enter wage");
}
buffer.write(firstLine);//write firstLine variable to payroll.txt file
buffer.newLine();
buffer.write(secondLine);
buffer.newLine();
buffer.write(thirdLine);
buffer.newLine();
count++;
}while(count <= size);
buffer.close();//closes the data writing stream to payroll.txt file
JOptionPane.showMessageDialog(null, "data processed",
"Result", JOptionPane.PLAIN_MESSAGE );//display message "data processed"
System.exit(1);
}
catch (IOException e) { System.out.println(e); }
}
}
This line
String firstLine, secondLine, thirdLine, number = " ";
equals to
String firstLine;
String secondLine;
String thirdLine;
String number = " ";
So you need to initialize your firstLine, secondLine, thirdLine:
String firstLine = "";
String secondLine = "";
String thirdLine = "";
String number = " ";
Adding the while loop around the place where you set the variable means that if the condition is never met, the variables will not receive a value.
But those while loops are wrong as they are. In general, while loops should not have a condition that waits for something that is not changed inside them. Since number is a local variable, there is no other thread that will change it, and it doesn't change inside the loop itself:
while(number == null || number.equals(""))
{
firstLine = JOptionPane.showInputDialog("Enter name");// prompts for input and displays "Enter Name"
}
I'm pretty sure you wanted to actually make this condition:
while(firstLine == null || firstLine.equals(""))
{
firstLine = JOptionPane.showInputDialog("Enter name");// prompts for input and displays "Enter Name"
}
So you should correct that. Nevertheless, the compiler may still not be happy with that, so you should, indeed, supply a default value when you declare the variable, and as the other answer told you, the declaration:
String firstLine, secondLine, thirdLine, number = " ";
Does not set all the variables to " " - only the number variable. You need to assign to each of them separately.
The value that you set should not be " " (a space). Because that doesn't meet either of the conditions (it's not null and it's not empty) so it will not go inside the loops, and you'll wonder why you're just getting spaces. You should set it to either null or an empty string.
Let me answer your question with a similar problem:
int x;
while(false) {
x = 10;
}
System.out.println(x);
Because there is no guarantee that you enter the while loop, there is therefore no guarantee that x is initialized.
The same problem occurs in your code. Even if you are logically convinced that you will enter the while loop, the compiler needs to be certain.
As such, please initialize your variables. This doesn't initialize them the way you think it does. It, infact, only initializes the last variable.
String firstLine, secondLine, thirdLine, number = " ";
Try this:
String firstLine, secondLine, thirdLine, number;
number = " ";
firstLine = null;
secondLine = null;
thirdLine = null;
You can also do this:
String firstLine, secondLine, thirdLine, number;
number = " ";
firstLine = secondLine = thirdLine = null;
Note that you don't have to initialize your variables to null: you could initialize them to any other String as well.
Just initialize the three variables to null..
String firstLine=null, secondLine=null, thirdLine=null;

Java input keeps being empty?

This is a simple question selection, and then answer program:
import java.util.Scanner;
public class Mains {
static Scanner console = new Scanner(System.in);
static Tof tof = new Tof();
static int Ievel = 0;
static int Input = 0;
static boolean GAME = true;
static boolean AT_START = true;
static boolean IN_QUESTION = false;
public static void main (String[] args) {
while (GAME) {
String InputS = "";
if (AT_START) {
System.out.println("Welcome to the game! Please select a number from 1 to 10.");
AT_START = false;
}
if (!IN_QUESTION)
Input = console.nextInt();
if (Input == -1) {
GAME = false;
console.close();
} else {
String question = tof.getQuestion(Input);
String answer = tof.getAnswer(Input);
System.out.println(question);
IN_QUESTION = true;
while (IN_QUESTION) {
InputS = console.nextLine();
if (InputS != console.nextLine()) {
if (InputS.equals(answer)) {
System.out.println("Correct!");
} else {
System.out.println("Incorrect. " + InputS + " " + answer);
}
}
}
}
}
}
}
Problem:
When entering the IN_QUESTION loop, and writing a answer, it will always be incorrect.
That's because the InputS variable is ALWAYS empty, no matter what, while it has console.nextLine() set on it.
Why is it empty? How do I fix this?
In-case you need the other class Tof: http://pastebin.com/Fn5HEpL2
nextInt doesn't get the line terminator after the integer and you're reading from the console twice (the second time being in the if-statement).
So if you enter:
123
apple
The following happens:
Input gets assigned a value of 123
InputS gets assigned an empty string
InputS gets compared against apple and it is not equal (from InputS != console.nextLine() - I'm not sure why it's there)
You can fix it by:
Putting a console.nextLine(); after console.nextInt();
OR
Use Input = Integer.parseInt(console.nextLine()) instead of nextInt
Removing this - if (InputS != console.nextLine())
You're reading from the console twice. This should work:
while (IN_QUESTION) {
InputS = console.nextLine();
if (InputS.equals(answer)) {
System.out.println("Correct!");
} else {
System.out.println("Incorrect. " + InputS + " " + answer);
}
}
The problem is that the new line character was not read by the nextInt() method so it remain in the scanner buffer and when the next time you called nextLine() that character was printed first.
This is how to fix the issue:
//empty the newline character from the scanner
console.nextLine();
while (IN_QUESTION) {
InputS= console.nextLine();
if (InputS.equals(answer)) {
System.out.println("Correct!");
} else {
System.out.println("Incorrect. " + InputS + " " + answer);
}
}
You call console.nextLine twice. This means that you read a line that you'll check, and another you won't. This is probably not what you are after. Also note that your initial call of nextInt will not consume the newline you pressed after entering the number. You need a nextLine right after that, but before the main loop.
Some general remarks:
uppercase names are only for constants, so your variables should be lowercase;
you should really be using local variables instead of static ones. Right now this isn't hurting you, but it soon could.

Categories

Resources