当未输入字符串源码时,程序输出Wrong Format JAVA 代码实现简单易懂
时间: 2024-02-13 13:06:05 浏览: 38
好的,我可以给您一个简单易懂的Java代码,来实现当未输入字符串源码时,程序输出"Wrong Format JAVA"的功能。代码如下:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String sourceCode = scanner.nextLine();
if (sourceCode.trim().isEmpty()) {
System.out.println("Wrong Format JAVA");
} else {
// 在这里添加您的程序逻辑
}
}
}
```
这段代码使用了Java标准库中的Scanner类,从命令行读取用户输入的字符串源码。然后判断该字符串是否为空,如果为空,就输出"Wrong Format JAVA";反之,就执行您想要实现的程序逻辑。您可以根据实际需求,修改这段代码中的逻辑部分。
相关问题
编写程序统计一个输入的Java源码中关键字(区分大小写)出现的次数未输入源码则认为输入非法, 当未输入源码时,程序输出Wrong Format 当没有统计数据时,输出为空 当有统计数据时,关键字按照升序排列,
以下是代码实现:
```java
import java.util.*;
public class KeywordCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入Java源码:");
String sourceCode = scanner.nextLine().trim();
if (sourceCode.isEmpty()) {
System.out.println("Wrong Format");
return;
}
String[] keywords = {
"abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const",
"continue", "default", "do", "double", "else", "enum", "extends", "final", "finally", "float",
"for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native",
"new", "package", "private", "protected", "public", "return", "short", "static", "strictfp",
"super", "switch", "synchronized", "this", "throw", "throws", "transient", "try", "void",
"volatile", "while"
};
Map<String, Integer> keywordCountMap = new TreeMap<>();
String[] lines = sourceCode.split("\n");
for (String line : lines) {
line = line.trim();
if (!line.isEmpty() && !line.startsWith("//") && !line.startsWith("/*")) {
String[] words = line.split("[\\s\\p{Punct}&&[^$_]]+");
for (String word : words) {
if (Arrays.asList(keywords).contains(word)) {
keywordCountMap.put(word, keywordCountMap.getOrDefault(word, 0) + 1);
}
}
}
}
if (keywordCountMap.isEmpty()) {
System.out.println("没有统计数据");
} else {
System.out.println("关键字\t数量");
for (String keyword : keywordCountMap.keySet()) {
System.out.println(keywordCountMap.get(keyword) + "\t" + keyword);
}
}
}
}
```
这个程序使用了一个字符串数组 `keywords` 来存储 Java 中的关键字,使用了一个 Map `keywordCountMap` 来存储每个关键字出现的次数。程序将输入的源码按行分割,对每一行进行分词,统计出现的关键字的数量。最后按照关键字升序输出统计结果。
在字符串中实现字符串的查找输出的代码用java
可以使用 Java 中的 String 类的 indexOf() 方法进行字符串查找。以下是一个简单的示例程序:
```java
public class FindString {
public static void main(String[] args) {
// 定义一个字符串
String str = "Hello, world!";
// 查找字符串中是否包含子字符串 "world"
int index = str.indexOf("world");
if (index >= 0) {
// 找到了,输出结果
System.out.println("Substring found at index " + index);
// 输出子字符串
System.out.println("Substring is: " + str.substring(index, index + 5));
} else {
// 没找到
System.out.println("Substring not found");
}
}
}
```
这段程序会在字符串 "Hello, world!" 中查找子字符串 "world",如果找到了就输出子字符串的位置和内容。如果没有找到,就输出 "Substring not found"。注意,indexOf() 方法返回的是子字符串出现的位置,如果找不到会返回 -1。substring() 方法用于获取子字符串,它接受两个参数,第一个参数是子字符串的起始位置,第二个参数是子字符串的长度。